Moved API files to correct dir
This commit is contained in:
1 parent
ea32a698a3
commit
47488f5fff
176 files changed
No files matched your search
@@ -0,0 +1,17 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
import { schemaQueryIdAsString } from "~/lib/validations/shared/queryIdString";
|
||||
|
||||
export async function authMiddleware(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const { id } = schemaQueryIdAsString.parse(req.query);
|
||||
// Admin can check any api key
|
||||
if (isAdmin) return;
|
||||
// Check if user can access the api key
|
||||
const apiKey = await prisma.apiKey.findFirst({
|
||||
where: { id, userId },
|
||||
});
|
||||
if (!apiKey) throw new HttpError({ statusCode: 404, message: "API key not found" });
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaQueryIdAsString } from "~/lib/validations/shared/queryIdString";
|
||||
|
||||
async function deleteHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdAsString.parse(query);
|
||||
await prisma.apiKey.delete({ where: { id } });
|
||||
return { message: `ApiKey with id: ${id} deleted` };
|
||||
}
|
||||
|
||||
export default defaultResponder(deleteHandler);
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { apiKeyPublicSchema } from "~/lib/validations/api-key";
|
||||
import { schemaQueryIdAsString } from "~/lib/validations/shared/queryIdString";
|
||||
|
||||
async function getHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdAsString.parse(query);
|
||||
const api_key = await prisma.apiKey.findUniqueOrThrow({ where: { id } });
|
||||
return { api_key: apiKeyPublicSchema.parse(api_key) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { apiKeyEditBodySchema, apiKeyPublicSchema } from "~/lib/validations/api-key";
|
||||
import { schemaQueryIdAsString } from "~/lib/validations/shared/queryIdString";
|
||||
|
||||
async function patchHandler(req: NextApiRequest) {
|
||||
const { prisma, body } = req;
|
||||
const { id } = schemaQueryIdAsString.parse(req.query);
|
||||
const data = apiKeyEditBodySchema.parse(body);
|
||||
const api_key = await prisma.apiKey.update({ where: { id }, data });
|
||||
return { api_key: apiKeyPublicSchema.parse(api_key) };
|
||||
}
|
||||
|
||||
export default defaultResponder(patchHandler);
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
import { authMiddleware } from "./_auth-middleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await authMiddleware(req);
|
||||
return defaultHandler({
|
||||
GET: import("./_get"),
|
||||
PATCH: import("./_patch"),
|
||||
DELETE: import("./_delete"),
|
||||
})(req, res);
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
import type { Ensure } from "@calcom/types/utils";
|
||||
|
||||
import { apiKeyPublicSchema } from "~/lib/validations/api-key";
|
||||
import { schemaQuerySingleOrMultipleUserIds } from "~/lib/validations/shared/queryUserId";
|
||||
|
||||
type CustomNextApiRequest = NextApiRequest & {
|
||||
args?: Prisma.ApiKeyFindManyArgs;
|
||||
};
|
||||
|
||||
/** Admins can query other users' API keys */
|
||||
function handleAdminRequests(req: CustomNextApiRequest) {
|
||||
// To match type safety with runtime
|
||||
if (!hasReqArgs(req)) throw Error("Missing req.args");
|
||||
const { userId, isAdmin } = req;
|
||||
if (isAdmin && req.query.userId) {
|
||||
const query = schemaQuerySingleOrMultipleUserIds.parse(req.query);
|
||||
const userIds = Array.isArray(query.userId) ? query.userId : [query.userId || userId];
|
||||
req.args.where = { userId: { in: userIds } };
|
||||
if (Array.isArray(query.userId)) req.args.orderBy = { userId: "asc" };
|
||||
}
|
||||
}
|
||||
|
||||
function hasReqArgs(req: CustomNextApiRequest): req is Ensure<CustomNextApiRequest, "args"> {
|
||||
return "args" in req;
|
||||
}
|
||||
|
||||
async function getHandler(req: CustomNextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
req.args = isAdmin ? {} : { where: { userId } };
|
||||
// Proof of concept: allowing mutation in exchange of composability
|
||||
handleAdminRequests(req);
|
||||
const data = await prisma.apiKey.findMany(req.args);
|
||||
return { api_keys: data.map((v) => apiKeyPublicSchema.parse(v)) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
import { v4 } from "uuid";
|
||||
|
||||
import { generateUniqueAPIKey } from "@calcom/features/ee/api-keys/lib/apiKeys";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { apiKeyCreateBodySchema, apiKeyPublicSchema } from "~/lib/validations/api-key";
|
||||
|
||||
async function postHandler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const { neverExpires, userId: bodyUserId, ...input } = apiKeyCreateBodySchema.parse(req.body);
|
||||
const [hashedKey, apiKey] = generateUniqueAPIKey();
|
||||
const args: Prisma.ApiKeyCreateArgs = {
|
||||
data: {
|
||||
id: v4(),
|
||||
userId,
|
||||
...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,
|
||||
},
|
||||
};
|
||||
|
||||
if (!isAdmin && bodyUserId) throw new HttpError({ statusCode: 403, message: `ADMIN required for userId` });
|
||||
|
||||
if (isAdmin && bodyUserId) {
|
||||
const where: Prisma.UserWhereInput = { id: bodyUserId };
|
||||
await prisma.user.findFirstOrThrow({ where });
|
||||
args.data.userId = bodyUserId;
|
||||
}
|
||||
|
||||
const result = await prisma.apiKey.create(args);
|
||||
return {
|
||||
api_key: {
|
||||
...apiKeyPublicSchema.parse(result),
|
||||
key: `${process.env.API_KEY_PREFIX ?? "cal_"}${apiKey}`,
|
||||
},
|
||||
message: "API key created successfully. Save the `key` value as it won't be displayed again.",
|
||||
};
|
||||
}
|
||||
|
||||
export default defaultResponder(postHandler);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware("HTTP_GET_OR_POST")(
|
||||
defaultHandler({
|
||||
GET: import("./_get"),
|
||||
POST: import("./_post"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
async function authMiddleware(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const query = schemaQueryIdParseInt.parse(req.query);
|
||||
// @note: Here we make sure to only return attendee's of the user's own bookings if the user is not an admin.
|
||||
if (isAdmin) return;
|
||||
// Find all user bookings, including attendees
|
||||
const attendee = await prisma.attendee.findFirst({
|
||||
where: { id: query.id, booking: { userId } },
|
||||
});
|
||||
// Flatten and merge all the attendees in one array
|
||||
if (!attendee) throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
}
|
||||
|
||||
export default authMiddleware;
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /attendees/{id}:
|
||||
* delete:
|
||||
* operationId: removeAttendeeById
|
||||
* summary: Remove an existing attendee
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the attendee to delete
|
||||
* tags:
|
||||
* - attendees
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, attendee removed successfully
|
||||
* 400:
|
||||
* description: Bad request. Attendee id is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function deleteHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
await prisma.attendee.delete({ where: { id } });
|
||||
return { message: `Attendee with id: ${id} deleted successfully` };
|
||||
}
|
||||
|
||||
export default defaultResponder(deleteHandler);
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaAttendeeReadPublic } from "~/lib/validations/attendee";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /attendees/{id}:
|
||||
* get:
|
||||
* operationId: getAttendeeById
|
||||
* summary: Find an attendee
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the attendee to get
|
||||
* tags:
|
||||
* - attendees
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: Attendee was not found
|
||||
*/
|
||||
export async function getHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const attendee = await prisma.attendee.findUnique({ where: { id } });
|
||||
return { attendee: schemaAttendeeReadPublic.parse(attendee) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaAttendeeEditBodyParams, schemaAttendeeReadPublic } from "~/lib/validations/attendee";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /attendees/{id}:
|
||||
* patch:
|
||||
* operationId: editAttendeeById
|
||||
* summary: Edit an existing attendee
|
||||
* requestBody:
|
||||
* description: Edit an existing attendee related to one of your bookings
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* email:
|
||||
* type: string
|
||||
* format: email
|
||||
* name:
|
||||
* type: string
|
||||
* timeZone:
|
||||
* type: string
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the attendee to get
|
||||
* tags:
|
||||
* - attendees
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, attendee edited successfully
|
||||
* 400:
|
||||
* description: Bad request. Attendee body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
|
||||
export async function patchHandler(req: NextApiRequest) {
|
||||
const { prisma, query, body } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const data = schemaAttendeeEditBodyParams.parse(body);
|
||||
await checkPermissions(req, data);
|
||||
const attendee = await prisma.attendee.update({ where: { id }, data });
|
||||
return { attendee: schemaAttendeeReadPublic.parse(attendee) };
|
||||
}
|
||||
|
||||
async function checkPermissions(req: NextApiRequest, body: z.infer<typeof schemaAttendeeEditBodyParams>) {
|
||||
const { isAdmin, prisma } = req;
|
||||
if (isAdmin) return;
|
||||
const { userId } = req;
|
||||
const { bookingId } = body;
|
||||
if (bookingId) {
|
||||
// Ensure that the booking the attendee is being added to belongs to the user
|
||||
const booking = await prisma.booking.findFirst({ where: { id: bookingId, userId } });
|
||||
if (!booking) throw new HttpError({ statusCode: 403, message: "You don't have access to the booking" });
|
||||
}
|
||||
}
|
||||
|
||||
export default defaultResponder(patchHandler);
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
import authMiddleware from "./_auth-middleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await authMiddleware(req);
|
||||
return defaultHandler({
|
||||
GET: import("./_get"),
|
||||
PATCH: import("./_patch"),
|
||||
DELETE: import("./_delete"),
|
||||
})(req, res);
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaAttendeeReadPublic } from "~/lib/validations/attendee";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /attendees:
|
||||
* get:
|
||||
* operationId: listAttendees
|
||||
* summary: Find all attendees
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - attendees
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: No attendees were found
|
||||
*/
|
||||
async function handler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const args: Prisma.AttendeeFindManyArgs = isAdmin ? {} : { where: { booking: { userId } } };
|
||||
const data = await prisma.attendee.findMany(args);
|
||||
const attendees = data.map((attendee) => schemaAttendeeReadPublic.parse(attendee));
|
||||
if (!attendees) throw new HttpError({ statusCode: 404, message: "No attendees were found" });
|
||||
return { attendees };
|
||||
}
|
||||
|
||||
export default defaultResponder(handler);
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaAttendeeCreateBodyParams, schemaAttendeeReadPublic } from "~/lib/validations/attendee";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /attendees:
|
||||
* post:
|
||||
* operationId: addAttendee
|
||||
* summary: Creates a new attendee
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* requestBody:
|
||||
* description: Create a new attendee related to one of your bookings
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - bookingId
|
||||
* - name
|
||||
* - email
|
||||
* - timeZone
|
||||
* properties:
|
||||
* bookingId:
|
||||
* type: number
|
||||
* email:
|
||||
* type: string
|
||||
* format: email
|
||||
* name:
|
||||
* type: string
|
||||
* timeZone:
|
||||
* type: string
|
||||
* tags:
|
||||
* - attendees
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, attendee created
|
||||
* 400:
|
||||
* description: Bad request. Attendee body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
async function postHandler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const body = schemaAttendeeCreateBodyParams.parse(req.body);
|
||||
|
||||
if (!isAdmin) {
|
||||
const userBooking = await prisma.booking.findFirst({
|
||||
where: { userId, id: body.bookingId },
|
||||
select: { id: true },
|
||||
});
|
||||
// Here we make sure to only return attendee's of the user's own bookings.
|
||||
if (!userBooking) throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
}
|
||||
|
||||
const data = await prisma.attendee.create({
|
||||
data: {
|
||||
email: body.email,
|
||||
name: body.name,
|
||||
timeZone: body.timeZone,
|
||||
booking: { connect: { id: body.bookingId } },
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
attendee: schemaAttendeeReadPublic.parse(data),
|
||||
message: "Attendee created successfully",
|
||||
};
|
||||
}
|
||||
|
||||
export default defaultResponder(postHandler);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
GET: import("./_get"),
|
||||
POST: import("./_post"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
async function authMiddleware(req: NextApiRequest) {
|
||||
const { userId, prisma, isAdmin, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
/** Admins can skip the ownership verification */
|
||||
if (isAdmin) return;
|
||||
/**
|
||||
* There's a caveat here. If the availability exists but the user doesn't own it,
|
||||
* the user will see a 404 error which may or not be the desired behavior.
|
||||
*/
|
||||
await prisma.availability.findFirstOrThrow({
|
||||
where: { id, Schedule: { userId } },
|
||||
});
|
||||
}
|
||||
|
||||
export default authMiddleware;
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /availabilities/{id}:
|
||||
* delete:
|
||||
* operationId: removeAvailabilityById
|
||||
* summary: Remove an existing availability
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the availability to delete
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - availabilities
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/availability
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, availability removed successfully
|
||||
* 400:
|
||||
* description: Bad request. Availability id is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function deleteHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
await prisma.availability.delete({ where: { id } });
|
||||
return { message: `Availability with id: ${id} deleted successfully` };
|
||||
}
|
||||
|
||||
export default defaultResponder(deleteHandler);
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaAvailabilityReadPublic } from "~/lib/validations/availability";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /availabilities/{id}:
|
||||
* get:
|
||||
* operationId: getAvailabilityById
|
||||
* summary: Find an availability
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the availability to get
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - availabilities
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/availability
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid
|
||||
* 404:
|
||||
* description: Availability not found
|
||||
*/
|
||||
export async function getHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const availability = await prisma.availability.findUnique({
|
||||
where: { id },
|
||||
include: { Schedule: { select: { userId: true } } },
|
||||
});
|
||||
return { availability: schemaAvailabilityReadPublic.parse(availability) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import {
|
||||
schemaAvailabilityEditBodyParams,
|
||||
schemaAvailabilityReadPublic,
|
||||
} from "~/lib/validations/availability";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /availabilities/{id}:
|
||||
* patch:
|
||||
* operationId: editAvailabilityById
|
||||
* summary: Edit an existing availability
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* description: Your API key
|
||||
* schema:
|
||||
* type: integer
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: ID of the availability to edit
|
||||
* requestBody:
|
||||
* description: Edit an existing availability related to one of your bookings
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* days:
|
||||
* type: array
|
||||
* description: Array of integers depicting weekdays
|
||||
* items:
|
||||
* type: integer
|
||||
* enum: [0, 1, 2, 3, 4, 5]
|
||||
* scheduleId:
|
||||
* type: integer
|
||||
* description: ID of schedule this availability is associated with
|
||||
* startTime:
|
||||
* type: string
|
||||
* description: Start time of the availability
|
||||
* endTime:
|
||||
* type: string
|
||||
* description: End time of the availability
|
||||
* examples:
|
||||
* availability:
|
||||
* summary: An example of availability
|
||||
* value:
|
||||
* scheduleId: 123
|
||||
* days: [1,2,3,5]
|
||||
* startTime: 1970-01-01T17:00:00.000Z
|
||||
* endTime: 1970-01-01T17:00:00.000Z
|
||||
*
|
||||
* tags:
|
||||
* - availabilities
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/availability
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, availability edited successfully
|
||||
* 400:
|
||||
* description: Bad request. Availability body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function patchHandler(req: NextApiRequest) {
|
||||
const { prisma, query, body } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const data = schemaAvailabilityEditBodyParams.parse(body);
|
||||
const availability = await prisma.availability.update({
|
||||
where: { id },
|
||||
data,
|
||||
include: { Schedule: { select: { userId: true } } },
|
||||
});
|
||||
return { availability: schemaAvailabilityReadPublic.parse(availability) };
|
||||
}
|
||||
|
||||
export default defaultResponder(patchHandler);
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
import authMiddleware from "./_auth-middleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await authMiddleware(req);
|
||||
return defaultHandler({
|
||||
GET: import("./_get"),
|
||||
PATCH: import("./_patch"),
|
||||
DELETE: import("./_delete"),
|
||||
})(req, res);
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import {
|
||||
schemaAvailabilityCreateBodyParams,
|
||||
schemaAvailabilityReadPublic,
|
||||
} from "~/lib/validations/availability";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /availabilities:
|
||||
* post:
|
||||
* operationId: addAvailability
|
||||
* summary: Creates a new availability
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* requestBody:
|
||||
* description: Edit an existing availability related to one of your bookings
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - scheduleId
|
||||
* - startTime
|
||||
* - endTime
|
||||
* properties:
|
||||
* days:
|
||||
* type: array
|
||||
* description: Array of integers depicting weekdays
|
||||
* items:
|
||||
* type: integer
|
||||
* enum: [0, 1, 2, 3, 4, 5]
|
||||
* scheduleId:
|
||||
* type: integer
|
||||
* description: ID of schedule this availability is associated with
|
||||
* startTime:
|
||||
* type: string
|
||||
* description: Start time of the availability
|
||||
* endTime:
|
||||
* type: string
|
||||
* description: End time of the availability
|
||||
* examples:
|
||||
* availability:
|
||||
* summary: An example of availability
|
||||
* value:
|
||||
* scheduleId: 123
|
||||
* days: [1,2,3,5]
|
||||
* startTime: 1970-01-01T17:00:00.000Z
|
||||
* endTime: 1970-01-01T17:00:00.000Z
|
||||
*
|
||||
*
|
||||
* tags:
|
||||
* - availabilities
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/availability
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, availability created
|
||||
* 400:
|
||||
* description: Bad request. Availability body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
async function postHandler(req: NextApiRequest) {
|
||||
const { prisma } = req;
|
||||
const data = schemaAvailabilityCreateBodyParams.parse(req.body);
|
||||
await checkPermissions(req);
|
||||
const availability = await prisma.availability.create({
|
||||
data,
|
||||
include: { Schedule: { select: { userId: true } } },
|
||||
});
|
||||
req.statusCode = 201;
|
||||
return {
|
||||
availability: schemaAvailabilityReadPublic.parse(availability),
|
||||
message: "Availability created successfully",
|
||||
};
|
||||
}
|
||||
|
||||
async function checkPermissions(req: NextApiRequest) {
|
||||
const { userId, prisma, isAdmin } = req;
|
||||
if (isAdmin) return;
|
||||
const data = schemaAvailabilityCreateBodyParams.parse(req.body);
|
||||
const schedule = await prisma.schedule.findFirst({
|
||||
where: { userId, id: data.scheduleId },
|
||||
});
|
||||
if (!schedule)
|
||||
throw new HttpError({ statusCode: 401, message: "You can't add availabilities to this schedule" });
|
||||
}
|
||||
|
||||
export default defaultResponder(postHandler);
|
||||
@@ -0,0 +1,9 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
POST: import("./_post"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,158 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getUserAvailability } from "@calcom/core/getUserAvailability";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
import { availabilityUserSelect } from "@calcom/prisma";
|
||||
import { stringOrNumber } from "@calcom/prisma/zod-utils";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /availability:
|
||||
* get:
|
||||
* summary: Find user or team availability
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* example: "1234abcd5678efgh"
|
||||
* description: Your API key
|
||||
* - in: query
|
||||
* name: userId
|
||||
* schema:
|
||||
* type: integer
|
||||
* example: 101
|
||||
* description: ID of the user to fetch the availability for
|
||||
* - in: query
|
||||
* name: teamId
|
||||
* schema:
|
||||
* type: integer
|
||||
* example: 123
|
||||
* description: ID of the team to fetch the availability for
|
||||
* - in: query
|
||||
* name: username
|
||||
* schema:
|
||||
* type: string
|
||||
* example: "alice"
|
||||
* description: username of the user to fetch the availability for
|
||||
* - in: query
|
||||
* name: dateFrom
|
||||
* schema:
|
||||
* type: string
|
||||
* format: date
|
||||
* example: "2023-05-14 00:00:00"
|
||||
* description: Start Date of the availability query
|
||||
* - in: query
|
||||
* name: dateTo
|
||||
* schema:
|
||||
* type: string
|
||||
* format: date
|
||||
* example: "2023-05-20 00:00:00"
|
||||
* description: End Date of the availability query
|
||||
* - in: query
|
||||
* name: eventTypeId
|
||||
* schema:
|
||||
* type: integer
|
||||
* example: 123
|
||||
* description: Event Type ID of the event type to fetch the availability for
|
||||
* operationId: availability
|
||||
* tags:
|
||||
* - availability
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* example:
|
||||
* busy:
|
||||
* - start: "2023-05-14T10:00:00.000Z"
|
||||
* end: "2023-05-14T11:00:00.000Z"
|
||||
* title: "Team meeting between Alice and Bob"
|
||||
* - start: "2023-05-15T14:00:00.000Z"
|
||||
* end: "2023-05-15T15:00:00.000Z"
|
||||
* title: "Project review between Carol and Dave"
|
||||
* - start: "2023-05-16T09:00:00.000Z"
|
||||
* end: "2023-05-16T10:00:00.000Z"
|
||||
* - start: "2023-05-17T13:00:00.000Z"
|
||||
* end: "2023-05-17T14:00:00.000Z"
|
||||
* timeZone: "America/New_York"
|
||||
* workingHours:
|
||||
* - days: [1, 2, 3, 4, 5]
|
||||
* startTime: 540
|
||||
* endTime: 1020
|
||||
* userId: 101
|
||||
* dateOverrides:
|
||||
* - date: "2023-05-15"
|
||||
* startTime: 600
|
||||
* endTime: 960
|
||||
* userId: 101
|
||||
* currentSeats: 4
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: User not found | Team not found | Team has no members
|
||||
*/
|
||||
|
||||
const availabilitySchema = z
|
||||
.object({
|
||||
userId: stringOrNumber.optional(),
|
||||
teamId: stringOrNumber.optional(),
|
||||
username: z.string().optional(),
|
||||
dateFrom: z.string(),
|
||||
dateTo: z.string(),
|
||||
eventTypeId: stringOrNumber.optional(),
|
||||
})
|
||||
.refine(
|
||||
(data) => !!data.username || !!data.userId || !!data.teamId,
|
||||
"Either username or userId or teamId should be filled in."
|
||||
);
|
||||
|
||||
async function handler(req: NextApiRequest) {
|
||||
const { prisma, isAdmin } = req;
|
||||
const { username, userId, eventTypeId, dateTo, dateFrom, teamId } = availabilitySchema.parse(req.query);
|
||||
if (!teamId)
|
||||
return getUserAvailability({
|
||||
username,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
eventTypeId,
|
||||
userId,
|
||||
});
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { members: true },
|
||||
});
|
||||
if (!team) throw new HttpError({ statusCode: 404, message: "teamId not found" });
|
||||
if (!team.members) throw new HttpError({ statusCode: 404, message: "team has no members" });
|
||||
const allMemberIds = team.members.map((membership) => membership.userId);
|
||||
const members = await prisma.user.findMany({
|
||||
where: { id: { in: allMemberIds } },
|
||||
select: availabilityUserSelect,
|
||||
});
|
||||
if (!isAdmin) throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
const availabilities = members.map(async (user) => {
|
||||
return {
|
||||
userId: user.id,
|
||||
availability: await getUserAvailability({
|
||||
userId: user.id,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
eventTypeId,
|
||||
}),
|
||||
};
|
||||
});
|
||||
const settled = await Promise.all(availabilities);
|
||||
if (!settled)
|
||||
throw new HttpError({
|
||||
statusCode: 401,
|
||||
message: "We had an issue retrieving all your members availabilities",
|
||||
});
|
||||
return settled;
|
||||
}
|
||||
|
||||
export default defaultResponder(handler);
|
||||
@@ -0,0 +1,9 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
GET: import("./_get"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
async function authMiddleware(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(req.query);
|
||||
// Here we make sure to only return references of the user's own bookings if the user is not an admin.
|
||||
if (isAdmin) return;
|
||||
// Find all references where the user has bookings
|
||||
const bookingReference = await prisma.bookingReference.findFirst({
|
||||
where: { id, booking: { userId } },
|
||||
});
|
||||
if (!bookingReference) throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
}
|
||||
|
||||
export default authMiddleware;
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /booking-references/{id}:
|
||||
* delete:
|
||||
* operationId: removeBookingReferenceById
|
||||
* summary: Remove an existing booking reference
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the booking reference to delete
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - booking-references
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, bookingReference removed successfully
|
||||
* 400:
|
||||
* description: Bad request. BookingReference id is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function deleteHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
await prisma.bookingReference.delete({ where: { id } });
|
||||
return { message: `BookingReference with id: ${id} deleted` };
|
||||
}
|
||||
|
||||
export default defaultResponder(deleteHandler);
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaBookingReferenceReadPublic } from "~/lib/validations/booking-reference";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /booking-references/{id}:
|
||||
* get:
|
||||
* operationId: getBookingReferenceById
|
||||
* summary: Find a booking reference
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the booking reference to get
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - booking-references
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: BookingReference was not found
|
||||
*/
|
||||
export async function getHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const booking_reference = await prisma.bookingReference.findUniqueOrThrow({ where: { id } });
|
||||
return { booking_reference: schemaBookingReferenceReadPublic.parse(booking_reference) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import {
|
||||
schemaBookingEditBodyParams,
|
||||
schemaBookingReferenceReadPublic,
|
||||
} from "~/lib/validations/booking-reference";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /booking-references/{id}:
|
||||
* patch:
|
||||
* operationId: editBookingReferenceById
|
||||
* summary: Edit an existing booking reference
|
||||
* requestBody:
|
||||
* description: Edit an existing booking reference related to one of your bookings
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* type:
|
||||
* type: string
|
||||
* meetingId:
|
||||
* type: string
|
||||
* meetingPassword:
|
||||
* type: string
|
||||
* externalCalendarId:
|
||||
* type: string
|
||||
* deleted:
|
||||
* type: boolean
|
||||
* credentialId:
|
||||
* type: integer
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the booking reference to edit
|
||||
* tags:
|
||||
* - booking-references
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, BookingReference edited successfully
|
||||
* 400:
|
||||
* description: Bad request. BookingReference body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function patchHandler(req: NextApiRequest) {
|
||||
const { prisma, query, body, isAdmin, userId } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const data = schemaBookingEditBodyParams.parse(body);
|
||||
/* If user tries to update bookingId, we run extra checks */
|
||||
if (data.bookingId) {
|
||||
const args: Prisma.BookingFindFirstOrThrowArgs = isAdmin
|
||||
? /* If admin, we only check that the booking exists */
|
||||
{ where: { id: data.bookingId } }
|
||||
: /* For non-admins we make sure the booking belongs to the user */
|
||||
{ where: { id: data.bookingId, userId } };
|
||||
await prisma.booking.findFirstOrThrow(args);
|
||||
}
|
||||
const booking_reference = await prisma.bookingReference.update({ where: { id }, data });
|
||||
return { booking_reference: schemaBookingReferenceReadPublic.parse(booking_reference) };
|
||||
}
|
||||
|
||||
export default defaultResponder(patchHandler);
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
import authMiddleware from "./_auth-middleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await authMiddleware(req);
|
||||
return defaultHandler({
|
||||
GET: import("./_get"),
|
||||
PATCH: import("./_patch"),
|
||||
DELETE: import("./_delete"),
|
||||
})(req, res);
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaBookingReferenceReadPublic } from "~/lib/validations/booking-reference";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /booking-references:
|
||||
* get:
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* operationId: listBookingReferences
|
||||
* summary: Find all booking references
|
||||
* tags:
|
||||
* - booking-references
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: No booking references were found
|
||||
*/
|
||||
async function getHandler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const args: Prisma.BookingReferenceFindManyArgs = isAdmin ? {} : { where: { booking: { userId } } };
|
||||
const data = await prisma.bookingReference.findMany(args);
|
||||
return { booking_references: data.map((br) => schemaBookingReferenceReadPublic.parse(br)) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import {
|
||||
schemaBookingCreateBodyParams,
|
||||
schemaBookingReferenceReadPublic,
|
||||
} from "~/lib/validations/booking-reference";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /booking-references:
|
||||
* post:
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* operationId: addBookingReference
|
||||
* summary: Creates a new booking reference
|
||||
* requestBody:
|
||||
* description: Create a new booking reference related to one of your bookings
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - type
|
||||
* - uid
|
||||
* properties:
|
||||
* type:
|
||||
* type: string
|
||||
* uid:
|
||||
* type: string
|
||||
* meetingId:
|
||||
* type: string
|
||||
* meetingPassword:
|
||||
* type: string
|
||||
* meetingUrl:
|
||||
* type: string
|
||||
* bookingId:
|
||||
* type: boolean
|
||||
* externalCalendarId:
|
||||
* type: string
|
||||
* deleted:
|
||||
* type: boolean
|
||||
* credentialId:
|
||||
* type: integer
|
||||
* tags:
|
||||
* - booking-references
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, booking reference created
|
||||
* 400:
|
||||
* description: Bad request. BookingReference body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
async function postHandler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const body = schemaBookingCreateBodyParams.parse(req.body);
|
||||
const args: Prisma.BookingFindFirstOrThrowArgs = isAdmin
|
||||
? /* If admin, we only check that the booking exists */
|
||||
{ where: { id: body.bookingId } }
|
||||
: /* For non-admins we make sure the booking belongs to the user */
|
||||
{ where: { id: body.bookingId, userId } };
|
||||
await prisma.booking.findFirstOrThrow(args);
|
||||
|
||||
const data = await prisma.bookingReference.create({
|
||||
data: {
|
||||
...body,
|
||||
bookingId: body.bookingId,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
booking_reference: schemaBookingReferenceReadPublic.parse(data),
|
||||
message: "Booking reference created successfully",
|
||||
};
|
||||
}
|
||||
|
||||
export default defaultResponder(postHandler);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
GET: import("./_get"),
|
||||
POST: import("./_post"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
async function authMiddleware(req: NextApiRequest) {
|
||||
const { userId, prisma, isAdmin, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const userWithBookings = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
include: { bookings: true },
|
||||
});
|
||||
|
||||
if (!userWithBookings) throw new HttpError({ statusCode: 404, message: "User not found" });
|
||||
|
||||
const userBookingIds = userWithBookings.bookings.map((booking) => booking.id);
|
||||
|
||||
if (!isAdmin && !userBookingIds.includes(id)) {
|
||||
throw new HttpError({ statusCode: 401, message: "You are not authorized" });
|
||||
}
|
||||
}
|
||||
|
||||
export default authMiddleware;
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import handleCancelBooking from "@calcom/features/bookings/lib/handleCancelBooking";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
import { schemaBookingCancelParams } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /bookings/{id}/cancel:
|
||||
* delete:
|
||||
* summary: Booking cancellation
|
||||
* operationId: cancelBookingById
|
||||
*
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the booking to cancel
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* - in: query
|
||||
* name: allRemainingBookings
|
||||
* required: false
|
||||
* schema:
|
||||
* type: boolean
|
||||
* description: Delete all remaining bookings
|
||||
* - in: query
|
||||
* name: reason
|
||||
* required: false
|
||||
* schema:
|
||||
* type: string
|
||||
* description: The reason for cancellation of the booking
|
||||
* tags:
|
||||
* - bookings
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK, booking cancelled successfully
|
||||
* 400:
|
||||
* description: |
|
||||
* Bad request
|
||||
* <table>
|
||||
* <tr>
|
||||
* <td>Message</td>
|
||||
* <td>Cause</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>Booking not found</td>
|
||||
* <td>The provided id didn't correspond to any existing booking.</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>Cannot cancel past events</td>
|
||||
* <td>The provided id matched an existing booking with a past startDate.</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>User not found</td>
|
||||
* <td>The userId did not matched an existing user.</td>
|
||||
* </tr>
|
||||
* </table>
|
||||
* 404:
|
||||
* description: User not found
|
||||
*/
|
||||
async function handler(req: NextApiRequest) {
|
||||
const { id, allRemainingBookings, cancellationReason } = schemaQueryIdParseInt
|
||||
.merge(schemaBookingCancelParams.pick({ allRemainingBookings: true, cancellationReason: true }))
|
||||
.parse({
|
||||
...req.query,
|
||||
allRemainingBookings: req.query.allRemainingBookings === "true",
|
||||
});
|
||||
// Normalizing for universal handler
|
||||
req.body = { id, allRemainingBookings, cancellationReason };
|
||||
return await handleCancelBooking(req);
|
||||
}
|
||||
|
||||
export default defaultResponder(handler);
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaBookingReadPublic } from "~/lib/validations/booking";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /bookings/{id}:
|
||||
* get:
|
||||
* summary: Find a booking
|
||||
* operationId: getBookingById
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the booking to get
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - bookings
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: "#/components/schemas/ArrayOfBookings"
|
||||
* examples:
|
||||
* bookings:
|
||||
* value: [
|
||||
* {
|
||||
* "id": 1,
|
||||
* "description": "Meeting with John",
|
||||
* "eventTypeId": 2,
|
||||
* "uid": "a1b2c3d4-e5f6-7890-g1h2-i3j4k5l6m7n8",
|
||||
* "title": "Business Meeting",
|
||||
* "startTime": "2023-04-20T10:00:00.000Z",
|
||||
* "endTime": "2023-04-20T11:00:00.000Z",
|
||||
* "timeZone": "Europe/London",
|
||||
* "attendees": [
|
||||
* {
|
||||
* "email": "[email protected]",
|
||||
* "name": "John Doe",
|
||||
* "timeZone": "Europe/London",
|
||||
* "locale": "en"
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ]
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: Booking was not found
|
||||
*/
|
||||
export async function getHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const booking = await prisma.booking.findUnique({
|
||||
where: { id },
|
||||
include: { attendees: true, user: true },
|
||||
});
|
||||
return { booking: schemaBookingReadPublic.parse(booking) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,110 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaBookingEditBodyParams, schemaBookingReadPublic } from "~/lib/validations/booking";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /bookings/{id}:
|
||||
* patch:
|
||||
* summary: Edit an existing booking
|
||||
* operationId: editBookingById
|
||||
* requestBody:
|
||||
* description: Edit an existing booking related to one of your event-types
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* title:
|
||||
* type: string
|
||||
* description: 'Booking event title'
|
||||
* start:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* description: 'Start time of the Event'
|
||||
* end:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* description: 'End time of the Event'
|
||||
* status:
|
||||
* type: string
|
||||
* description: 'Acceptable values one of ["ACCEPTED", "PENDING", "CANCELLED", "REJECTED"]'
|
||||
* examples:
|
||||
* editBooking:
|
||||
* value:
|
||||
* {
|
||||
* "title": "Debugging between Syed Ali Shahbaz and Hello Hello",
|
||||
* "start": "2023-05-24T13:00:00.000Z",
|
||||
* "end": "2023-05-24T13:30:00.000Z",
|
||||
* "status": "CANCELLED"
|
||||
* }
|
||||
*
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the booking to edit
|
||||
* tags:
|
||||
* - bookings
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK, booking edited successfully
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* bookings:
|
||||
* value:
|
||||
* {
|
||||
* "booking": {
|
||||
* "id": 11223344,
|
||||
* "userId": 182,
|
||||
* "description": null,
|
||||
* "eventTypeId": 2323232,
|
||||
* "uid": "stoSJtnh83PEL4rZmqdHe2",
|
||||
* "title": "Debugging between Syed Ali Shahbaz and Hello Hello",
|
||||
* "startTime": "2023-05-24T13:00:00.000Z",
|
||||
* "endTime": "2023-05-24T13:30:00.000Z",
|
||||
* "metadata": {},
|
||||
* "status": "CANCELLED"
|
||||
* }
|
||||
* }
|
||||
* 400:
|
||||
* description: Bad request. Booking body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function patchHandler(req: NextApiRequest) {
|
||||
const { prisma, query, body } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const data = schemaBookingEditBodyParams.parse(body);
|
||||
await checkPermissions(req, data);
|
||||
const booking = await prisma.booking.update({ where: { id }, data });
|
||||
return { booking: schemaBookingReadPublic.parse(booking) };
|
||||
}
|
||||
|
||||
async function checkPermissions(req: NextApiRequest, body: z.infer<typeof schemaBookingEditBodyParams>) {
|
||||
const { isAdmin } = req;
|
||||
if (body.userId && !isAdmin) {
|
||||
// Organizer has to be a cal user and we can't allow a booking to be transfered to some other cal user's name
|
||||
throw new HttpError({
|
||||
statusCode: 403,
|
||||
message: "Only admin can change the organizer of a booking",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default defaultResponder(patchHandler);
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
import authMiddleware from "./_auth-middleware";
|
||||
|
||||
export default withMiddleware()(async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await authMiddleware(req);
|
||||
return defaultHandler({
|
||||
DELETE: import("./_delete"),
|
||||
})(req, res);
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
import authMiddleware from "./_auth-middleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await authMiddleware(req);
|
||||
return defaultHandler({
|
||||
GET: import("./_get"),
|
||||
PATCH: import("./_patch"),
|
||||
DELETE: import("./_delete"),
|
||||
})(req, res);
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,130 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaBookingReadPublic } from "~/lib/validations/booking";
|
||||
import { schemaQuerySingleOrMultipleUserIds } from "~/lib/validations/shared/queryUserId";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /bookings:
|
||||
* get:
|
||||
* summary: Find all bookings
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* example: 123456789abcdefgh
|
||||
* - in: query
|
||||
* name: userId
|
||||
* required: false
|
||||
* schema:
|
||||
* oneOf:
|
||||
* - type: integer
|
||||
* example: 1
|
||||
* - type: array
|
||||
* items:
|
||||
* type: integer
|
||||
* example: [2, 3, 4]
|
||||
* operationId: listBookings
|
||||
* tags:
|
||||
* - bookings
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: "#/components/schemas/ArrayOfBookings"
|
||||
* examples:
|
||||
* bookings:
|
||||
* value: [
|
||||
* {
|
||||
* "id": 1,
|
||||
* "description": "Meeting with John",
|
||||
* "eventTypeId": 2,
|
||||
* "uid": "a1b2c3d4-e5f6-7890-g1h2-i3j4k5l6m7n8",
|
||||
* "title": "Business Meeting",
|
||||
* "startTime": "2023-04-20T10:00:00.000Z",
|
||||
* "endTime": "2023-04-20T11:00:00.000Z",
|
||||
* "timeZone": "Europe/London",
|
||||
* "attendees": [
|
||||
* {
|
||||
* "email": "[email protected]",
|
||||
* "name": "John Doe",
|
||||
* "timeZone": "Europe/London",
|
||||
* "locale": "en"
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ]
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: No bookings were found
|
||||
*/
|
||||
|
||||
async function handler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const args: Prisma.BookingFindManyArgs = {};
|
||||
args.include = {
|
||||
attendees: true,
|
||||
user: true,
|
||||
};
|
||||
|
||||
/** Only admins can query other users */
|
||||
if (isAdmin && req.query.userId) {
|
||||
const query = schemaQuerySingleOrMultipleUserIds.parse(req.query);
|
||||
const userIds = Array.isArray(query.userId) ? query.userId : [query.userId || userId];
|
||||
const users = await prisma.user.findMany({
|
||||
where: { id: { in: userIds } },
|
||||
select: { email: true },
|
||||
});
|
||||
const userEmails = users.map((u) => u.email);
|
||||
args.where = {
|
||||
OR: [
|
||||
{ userId: { in: userIds } },
|
||||
{
|
||||
attendees: {
|
||||
some: {
|
||||
email: { in: userEmails },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
} else if (!isAdmin) {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
email: true,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
throw new HttpError({ message: "User not found", statusCode: 500 });
|
||||
}
|
||||
args.where = {
|
||||
OR: [
|
||||
{
|
||||
userId,
|
||||
},
|
||||
{
|
||||
attendees: {
|
||||
some: {
|
||||
email: user.email,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
const data = await prisma.booking.findMany(args);
|
||||
return { bookings: data.map((booking) => schemaBookingReadPublic.parse(booking)) };
|
||||
}
|
||||
|
||||
export default defaultResponder(handler);
|
||||
@@ -0,0 +1,204 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import handleNewBooking from "@calcom/features/bookings/lib/handleNewBooking";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /bookings:
|
||||
* post:
|
||||
* summary: Creates a new booking
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* operationId: addBooking
|
||||
* requestBody:
|
||||
* description: Create a new booking related to one of your event-types
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - eventTypeId
|
||||
* - start
|
||||
* - end
|
||||
* - name
|
||||
* - email
|
||||
* - timeZone
|
||||
* - language
|
||||
* - metadata
|
||||
* - customInputs
|
||||
* - location
|
||||
* properties:
|
||||
* eventTypeId:
|
||||
* type: integer
|
||||
* description: 'ID of the event type to book'
|
||||
* start:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* description: 'Start time of the Event'
|
||||
* end:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* description: 'End time of the Event'
|
||||
* name:
|
||||
* type: string
|
||||
* description: 'Name of the Attendee'
|
||||
* email:
|
||||
* type: string
|
||||
* format: email
|
||||
* description: 'Email ID of the Attendee'
|
||||
* timeZone:
|
||||
* type: string
|
||||
* description: 'TimeZone of the Attendee'
|
||||
* language:
|
||||
* type: string
|
||||
* description: 'Language of the Attendee'
|
||||
* metadata:
|
||||
* type: object
|
||||
* properties: {}
|
||||
* description: 'Any metadata associated with the booking'
|
||||
* customInputs:
|
||||
* type: array
|
||||
* items: {}
|
||||
* location:
|
||||
* type: string
|
||||
* description: 'Meeting location'
|
||||
* title:
|
||||
* type: string
|
||||
* description: 'Booking event title'
|
||||
* recurringEventId:
|
||||
* type: integer
|
||||
* description: 'Recurring event ID if the event is recurring'
|
||||
* description:
|
||||
* type: string
|
||||
* description: 'Event description'
|
||||
* status:
|
||||
* type: string
|
||||
* description: 'Acceptable values one of ["ACCEPTED", "PENDING", "CANCELLED", "REJECTED"]'
|
||||
* seatsPerTimeSlot:
|
||||
* type: integer
|
||||
* description: 'The number of seats for each time slot'
|
||||
* seatsShowAttendees:
|
||||
* type: boolean
|
||||
* description: 'Share Attendee information in seats'
|
||||
* smsReminderNumber:
|
||||
* type: number
|
||||
* description: 'SMS reminder number'
|
||||
* examples:
|
||||
* New Booking example:
|
||||
* value:
|
||||
* {
|
||||
* "eventTypeId": 2323232,
|
||||
* "start": "2023-05-24T13:00:00.000Z",
|
||||
* "end": "2023-05-24T13:30:00.000Z",
|
||||
* "name": "Hello Hello",
|
||||
* "email": "[email protected]",
|
||||
* "timeZone": "Europe/London",
|
||||
* "language": "en",
|
||||
* "metadata": {},
|
||||
* "customInputs": [],
|
||||
* "location": "Calcom HQ",
|
||||
* "title": "Debugging between Syed Ali Shahbaz and Hello Hello",
|
||||
* "description": null,
|
||||
* "status": "PENDING",
|
||||
* "smsReminderNumber": null
|
||||
* }
|
||||
*
|
||||
* tags:
|
||||
* - bookings
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Booking(s) created successfully.
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* bookings:
|
||||
* value:
|
||||
* {
|
||||
* "id": 11223344,
|
||||
* "uid": "5yUjmAYTDF6MXo98re8SkX",
|
||||
* "userId": 123,
|
||||
* "eventTypeId": 2323232,
|
||||
* "title": "Debugging between Syed Ali Shahbaz and Hello Hello",
|
||||
* "description": null,
|
||||
* "customInputs": {},
|
||||
* "responses": null,
|
||||
* "startTime": "2023-05-24T13:00:00.000Z",
|
||||
* "endTime": "2023-05-24T13:30:00.000Z",
|
||||
* "location": "Calcom HQ",
|
||||
* "createdAt": "2023-04-19T10:17:58.580Z",
|
||||
* "updatedAt": null,
|
||||
* "status": "PENDING",
|
||||
* "paid": false,
|
||||
* "destinationCalendarId": 2180,
|
||||
* "cancellationReason": null,
|
||||
* "rejectionReason": null,
|
||||
* "dynamicEventSlugRef": null,
|
||||
* "dynamicGroupSlugRef": null,
|
||||
* "rescheduled": null,
|
||||
* "fromReschedule": null,
|
||||
* "recurringEventId": null,
|
||||
* "smsReminderNumber": null,
|
||||
* "scheduledJobs": [],
|
||||
* "metadata": {},
|
||||
* "isRecorded": false,
|
||||
* "user": {
|
||||
* "email": "[email protected]",
|
||||
* "name": "Syed Ali Shahbaz",
|
||||
* "timeZone": "Asia/Calcutta"
|
||||
* },
|
||||
* "attendees": [
|
||||
* {
|
||||
* "id": 12345,
|
||||
* "email": "[email protected]",
|
||||
* "name": "Hello Hello",
|
||||
* "timeZone": "Europe/London",
|
||||
* "locale": "en",
|
||||
* "bookingId": 11223344
|
||||
* }
|
||||
* ],
|
||||
* "payment": [],
|
||||
* "references": []
|
||||
* }
|
||||
* 400:
|
||||
* description: |
|
||||
* Bad request
|
||||
* <table>
|
||||
* <tr>
|
||||
* <td>Message</td>
|
||||
* <td>Cause</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>Booking body is invalid</td>
|
||||
* <td>Missing property on booking entity.</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>Invalid eventTypeId</td>
|
||||
* <td>The provided eventTypeId does not exist.</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>Missing recurringCount</td>
|
||||
* <td>The eventType is recurring, and no recurringCount was passed.</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>Invalid recurringCount</td>
|
||||
* <td>The provided recurringCount is greater than the eventType recurring config</td>
|
||||
* </tr>
|
||||
* </table>
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
async function handler(req: NextApiRequest) {
|
||||
const { userId, isAdmin } = req;
|
||||
if (isAdmin) req.userId = req.body.userId || userId;
|
||||
const booking = await handleNewBooking(req);
|
||||
return booking;
|
||||
}
|
||||
|
||||
export default defaultResponder(handler);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
GET: import("./_get"),
|
||||
POST: import("./_post"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
async function authMiddleware(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(req.query);
|
||||
// Admins can just skip this check
|
||||
if (isAdmin) return;
|
||||
// Check if the current user can access the event type of this input
|
||||
const eventTypeCustomInput = await prisma.eventTypeCustomInput.findFirst({
|
||||
where: { id, eventType: { userId } },
|
||||
});
|
||||
if (!eventTypeCustomInput) throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
}
|
||||
|
||||
export default authMiddleware;
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /custom-inputs/{id}:
|
||||
* delete:
|
||||
* summary: Remove an existing eventTypeCustomInput
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the eventTypeCustomInput to delete
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - custom-inputs
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, eventTypeCustomInput removed successfully
|
||||
* 400:
|
||||
* description: Bad request. EventType id is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function deleteHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
await prisma.eventTypeCustomInput.delete({ where: { id } });
|
||||
return { message: `CustomInputEventType with id: ${id} deleted successfully` };
|
||||
}
|
||||
|
||||
export default defaultResponder(deleteHandler);
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaEventTypeCustomInputPublic } from "~/lib/validations/event-type-custom-input";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /custom-inputs/{id}:
|
||||
* get:
|
||||
* summary: Find a eventTypeCustomInput
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the eventTypeCustomInput to get
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - custom-inputs
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: EventType was not found
|
||||
*/
|
||||
export async function getHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const data = await prisma.eventTypeCustomInput.findUniqueOrThrow({ where: { id } });
|
||||
return { event_type_custom_input: schemaEventTypeCustomInputPublic.parse(data) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import {
|
||||
schemaEventTypeCustomInputEditBodyParams,
|
||||
schemaEventTypeCustomInputPublic,
|
||||
} from "~/lib/validations/event-type-custom-input";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /custom-inputs/{id}:
|
||||
* patch:
|
||||
* summary: Edit an existing eventTypeCustomInput
|
||||
* requestBody:
|
||||
* description: Edit an existing eventTypeCustomInput for an event type
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* eventTypeId:
|
||||
* type: integer
|
||||
* description: 'ID of the event type to which the custom input is being added'
|
||||
* label:
|
||||
* type: string
|
||||
* description: 'Label of the custom input'
|
||||
* type:
|
||||
* type: string
|
||||
* description: 'Type of the custom input. The value is ENUM; one of [TEXT, TEXTLONG, NUMBER, BOOL, RADIO, PHONE]'
|
||||
* options:
|
||||
* type: object
|
||||
* properties:
|
||||
* label:
|
||||
* type: string
|
||||
* type:
|
||||
* type: string
|
||||
* description: 'Options for the custom input'
|
||||
* required:
|
||||
* type: boolean
|
||||
* description: 'If the custom input is required before booking'
|
||||
* placeholder:
|
||||
* type: string
|
||||
* description: 'Placeholder text for the custom input'
|
||||
*
|
||||
* examples:
|
||||
* custom-inputs:
|
||||
* summary: Example of patching an existing Custom Input
|
||||
* value:
|
||||
* required: true
|
||||
*
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the eventTypeCustomInput to edit
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
*
|
||||
* tags:
|
||||
* - custom-inputs
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, eventTypeCustomInput edited successfully
|
||||
* 400:
|
||||
* description: Bad request. EventType body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function patchHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const data = schemaEventTypeCustomInputEditBodyParams.parse(req.body);
|
||||
const result = await prisma.eventTypeCustomInput.update({ where: { id }, data });
|
||||
return { event_type_custom_input: schemaEventTypeCustomInputPublic.parse(result) };
|
||||
}
|
||||
|
||||
export default defaultResponder(patchHandler);
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
import authMiddleware from "./_auth-middleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await authMiddleware(req);
|
||||
return defaultHandler({
|
||||
GET: import("./_get"),
|
||||
PATCH: import("./_patch"),
|
||||
DELETE: import("./_delete"),
|
||||
})(req, res);
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaEventTypeCustomInputPublic } from "~/lib/validations/event-type-custom-input";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /custom-inputs:
|
||||
* get:
|
||||
* summary: Find all eventTypeCustomInputs
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - custom-inputs
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: No eventTypeCustomInputs were found
|
||||
*/
|
||||
async function getHandler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const args: Prisma.EventTypeCustomInputFindManyArgs = isAdmin ? {} : { where: { eventType: { userId } } };
|
||||
const data = await prisma.eventTypeCustomInput.findMany(args);
|
||||
return { event_type_custom_inputs: data.map((v) => schemaEventTypeCustomInputPublic.parse(v)) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import {
|
||||
schemaEventTypeCustomInputBodyParams,
|
||||
schemaEventTypeCustomInputPublic,
|
||||
} from "~/lib/validations/event-type-custom-input";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /custom-inputs:
|
||||
* post:
|
||||
* summary: Creates a new eventTypeCustomInput
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* requestBody:
|
||||
* description: Create a new custom input for an event type
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - eventTypeId
|
||||
* - label
|
||||
* - type
|
||||
* - required
|
||||
* - placeholder
|
||||
* properties:
|
||||
* eventTypeId:
|
||||
* type: integer
|
||||
* description: 'ID of the event type to which the custom input is being added'
|
||||
* label:
|
||||
* type: string
|
||||
* description: 'Label of the custom input'
|
||||
* type:
|
||||
* type: string
|
||||
* description: 'Type of the custom input. The value is ENUM; one of [TEXT, TEXTLONG, NUMBER, BOOL, RADIO, PHONE]'
|
||||
* options:
|
||||
* type: object
|
||||
* properties:
|
||||
* label:
|
||||
* type: string
|
||||
* type:
|
||||
* type: string
|
||||
* description: 'Options for the custom input'
|
||||
* required:
|
||||
* type: boolean
|
||||
* description: 'If the custom input is required before booking'
|
||||
* placeholder:
|
||||
* type: string
|
||||
* description: 'Placeholder text for the custom input'
|
||||
*
|
||||
* examples:
|
||||
* custom-inputs:
|
||||
* summary: An example of custom-inputs
|
||||
* value:
|
||||
* eventTypeID: 1
|
||||
* label: "Phone Number"
|
||||
* type: "PHONE"
|
||||
* required: true
|
||||
* placeholder: "100 101 1234"
|
||||
*
|
||||
* tags:
|
||||
* - custom-inputs
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, eventTypeCustomInput created
|
||||
* 400:
|
||||
* description: Bad request. EventTypeCustomInput body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
async function postHandler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const { eventTypeId, ...body } = schemaEventTypeCustomInputBodyParams.parse(req.body);
|
||||
|
||||
if (!isAdmin) {
|
||||
/* We check that the user has access to the event type he's trying to add a custom input to. */
|
||||
const eventType = await prisma.eventType.findFirst({
|
||||
where: { id: eventTypeId, userId },
|
||||
});
|
||||
if (!eventType) throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
}
|
||||
|
||||
const data = await prisma.eventTypeCustomInput.create({
|
||||
data: { ...body, eventType: { connect: { id: eventTypeId } } },
|
||||
});
|
||||
|
||||
return {
|
||||
event_type_custom_input: schemaEventTypeCustomInputPublic.parse(data),
|
||||
message: "EventTypeCustomInput created successfully",
|
||||
};
|
||||
}
|
||||
|
||||
export default defaultResponder(postHandler);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
GET: import("./_get"),
|
||||
POST: import("./_post"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,240 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
import type { DestinationCalendarResponse } from "~/lib/types";
|
||||
import {
|
||||
schemaDestinationCalendarEditBodyParams,
|
||||
schemaDestinationCalendarReadPublic,
|
||||
} from "~/lib/validations/destination-calendar";
|
||||
import {
|
||||
schemaQueryIdParseInt,
|
||||
withValidQueryIdTransformParseInt,
|
||||
} from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
export async function destionationCalendarById(
|
||||
{ method, query, body, userId, prisma }: NextApiRequest,
|
||||
res: NextApiResponse<DestinationCalendarResponse>
|
||||
) {
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const safeBody = schemaDestinationCalendarEditBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) {
|
||||
res.status(400).json({ message: "Your query was invalid" });
|
||||
return;
|
||||
}
|
||||
const data = await prisma.destinationCalendar.findMany({ where: { userId } });
|
||||
const userDestinationCalendars = data.map((destinationCalendar) => destinationCalendar.id);
|
||||
// FIXME: Should we also check ownership of bokingId and eventTypeId to avoid users cross-pollinating other users calendars.
|
||||
// On a related note, moving from sequential integer IDs to UUIDs would be a good idea. and maybe help avoid having this problem.
|
||||
if (userDestinationCalendars.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
/**
|
||||
* @swagger
|
||||
* /destination-calendars/{id}:
|
||||
* get:
|
||||
* summary: Find a destination calendar
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the destination calendar to get
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - destination-calendars
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: DestinationCalendar was not found
|
||||
* patch:
|
||||
* summary: Edit an existing destination calendar
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the destination calendar to edit
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* requestBody:
|
||||
* description: Create a new booking related to one of your event-types
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* integration:
|
||||
* type: string
|
||||
* description: 'The integration'
|
||||
* externalId:
|
||||
* type: string
|
||||
* description: 'The external ID of the integration'
|
||||
* eventTypeId:
|
||||
* type: integer
|
||||
* description: 'The ID of the eventType it is associated with'
|
||||
* bookingId:
|
||||
* type: integer
|
||||
* description: 'The booking ID it is associated with'
|
||||
* tags:
|
||||
* - destination-calendars
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, destinationCalendar edited successfuly
|
||||
* 400:
|
||||
* description: Bad request. DestinationCalendar body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* delete:
|
||||
* summary: Remove an existing destination calendar
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the destination calendar to delete
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - destination-calendars
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, destinationCalendar removed successfuly
|
||||
* 400:
|
||||
* description: Bad request. DestinationCalendar id is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
case "GET":
|
||||
await prisma.destinationCalendar
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaDestinationCalendarReadPublic.parse(data))
|
||||
.then((destination_calendar) => res.status(200).json({ destination_calendar }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `DestinationCalendar with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
/**
|
||||
* @swagger
|
||||
* /destination-calendars/{id}:
|
||||
* patch:
|
||||
* summary: Edit an existing destination calendar
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the destination calendar to edit
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - destination-calendars
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, destinationCalendar edited successfuly
|
||||
* 400:
|
||||
* description: Bad request. DestinationCalendar body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
case "PATCH":
|
||||
if (!safeBody.success) {
|
||||
{
|
||||
res.status(400).json({ message: "Invalid request body" });
|
||||
return;
|
||||
}
|
||||
}
|
||||
await prisma.destinationCalendar
|
||||
.update({ where: { id: safeQuery.data.id }, data: safeBody.data })
|
||||
.then((data) => schemaDestinationCalendarReadPublic.parse(data))
|
||||
.then((destination_calendar) => res.status(200).json({ destination_calendar }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `DestinationCalendar with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
/**
|
||||
* @swagger
|
||||
* /destination-calendars/{id}:
|
||||
* delete:
|
||||
* summary: Remove an existing destination calendar
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the destination calendar to delete
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - destination-calendars
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, destinationCalendar removed successfuly
|
||||
* 400:
|
||||
* description: Bad request. DestinationCalendar id is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
case "DELETE":
|
||||
await prisma.destinationCalendar
|
||||
.delete({
|
||||
where: { id: safeQuery.data.id },
|
||||
})
|
||||
.then(() =>
|
||||
res.status(200).json({
|
||||
message: `DestinationCalendar with id: ${safeQuery.data.id} deleted`,
|
||||
})
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `DestinationCalendar with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default withMiddleware("HTTP_GET_DELETE_PATCH")(
|
||||
withValidQueryIdTransformParseInt(destionationCalendarById)
|
||||
);
|
||||
@@ -0,0 +1,114 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
import type { DestinationCalendarResponse, DestinationCalendarsResponse } from "~/lib/types";
|
||||
import {
|
||||
schemaDestinationCalendarCreateBodyParams,
|
||||
schemaDestinationCalendarReadPublic,
|
||||
} from "~/lib/validations/destination-calendar";
|
||||
|
||||
async function createOrlistAllDestinationCalendars(
|
||||
{ method, body, userId, prisma }: NextApiRequest,
|
||||
res: NextApiResponse<DestinationCalendarsResponse | DestinationCalendarResponse>
|
||||
) {
|
||||
if (method === "GET") {
|
||||
/**
|
||||
* @swagger
|
||||
* /destination-calendars:
|
||||
* get:
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* summary: Find all destination calendars
|
||||
* tags:
|
||||
* - destination-calendars
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: No destination calendars were found
|
||||
*/
|
||||
const data = await prisma.destinationCalendar.findMany({ where: { userId } });
|
||||
const destination_calendars = data.map((destinationCalendar) =>
|
||||
schemaDestinationCalendarReadPublic.parse(destinationCalendar)
|
||||
);
|
||||
if (data) res.status(200).json({ destination_calendars });
|
||||
else
|
||||
(error: Error) =>
|
||||
res.status(404).json({
|
||||
message: "No DestinationCalendars were found",
|
||||
error,
|
||||
});
|
||||
} else if (method === "POST") {
|
||||
/**
|
||||
* @swagger
|
||||
* /destination-calendars:
|
||||
* post:
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* summary: Creates a new destination calendar
|
||||
* requestBody:
|
||||
* description: Create a new destination calendar for your events
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - integration
|
||||
* - externalId
|
||||
* properties:
|
||||
* integration:
|
||||
* type: string
|
||||
* description: 'The integration'
|
||||
* externalId:
|
||||
* type: string
|
||||
* description: 'The external ID of the integration'
|
||||
* eventTypeId:
|
||||
* type: integer
|
||||
* description: 'The ID of the eventType it is associated with'
|
||||
* bookingId:
|
||||
* type: integer
|
||||
* description: 'The booking ID it is associated with'
|
||||
* tags:
|
||||
* - destination-calendars
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, destination calendar created
|
||||
* 400:
|
||||
* description: Bad request. DestinationCalendar body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
const safe = schemaDestinationCalendarCreateBodyParams.safeParse(body);
|
||||
if (!safe.success) {
|
||||
res.status(400).json({ message: "Invalid request body" });
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await prisma.destinationCalendar.create({ data: { ...safe.data, userId } });
|
||||
const destination_calendar = schemaDestinationCalendarReadPublic.parse(data);
|
||||
|
||||
if (destination_calendar)
|
||||
res.status(201).json({ destination_calendar, message: "DestinationCalendar created successfully" });
|
||||
else
|
||||
(error: Error) =>
|
||||
res.status(400).json({
|
||||
message: "Could not create new destinationCalendar",
|
||||
error,
|
||||
});
|
||||
} else res.status(405).json({ message: `Method ${method} not allowed` });
|
||||
}
|
||||
|
||||
export default withMiddleware("HTTP_GET_OR_POST")(createOrlistAllDestinationCalendars);
|
||||
@@ -0,0 +1,129 @@
|
||||
import { withSwagger } from "next-swagger-doc";
|
||||
|
||||
import pjson from "~/package.json";
|
||||
|
||||
const swaggerHandler = withSwagger({
|
||||
definition: {
|
||||
openapi: "3.0.3",
|
||||
servers: [
|
||||
{ url: "http://localhost:3002/v1" },
|
||||
{ url: "https://api.cal.dev/v1" },
|
||||
{ url: "https://api.cal.com/v1" },
|
||||
],
|
||||
externalDocs: {
|
||||
url: "https://docs.cal.com",
|
||||
description: "Find more info at our main docs: https://docs.cal.com/",
|
||||
},
|
||||
info: {
|
||||
title: `${pjson.name}: ${pjson.description}`,
|
||||
version: pjson.version,
|
||||
},
|
||||
components: {
|
||||
securitySchemes: { ApiKeyAuth: { type: "apiKey", in: "query", name: "apiKey" } },
|
||||
schemas: {
|
||||
ArrayOfBookings: {
|
||||
type: "array",
|
||||
items: {
|
||||
$ref: "#/components/schemas/Booking",
|
||||
},
|
||||
},
|
||||
Booking: {
|
||||
properties: {
|
||||
id: {
|
||||
type: "number",
|
||||
},
|
||||
description: {
|
||||
type: "string",
|
||||
},
|
||||
eventTypeId: {
|
||||
type: "number",
|
||||
},
|
||||
uid: {
|
||||
type: "string",
|
||||
format: "uuid",
|
||||
},
|
||||
title: {
|
||||
type: "string",
|
||||
},
|
||||
startTime: {
|
||||
type: "string",
|
||||
format: "date-time",
|
||||
},
|
||||
endTime: {
|
||||
type: "string",
|
||||
format: "date-time",
|
||||
},
|
||||
timeZone: {
|
||||
type: "string",
|
||||
example: "Europe/London",
|
||||
},
|
||||
attendees: {
|
||||
type: "array",
|
||||
items: {
|
||||
properties: {
|
||||
email: {
|
||||
type: "string",
|
||||
example: "[email protected]",
|
||||
},
|
||||
name: {
|
||||
type: "string",
|
||||
},
|
||||
timeZone: {
|
||||
type: "string",
|
||||
example: "Europe/London",
|
||||
},
|
||||
locale: {
|
||||
type: "string",
|
||||
example: "en",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
user: {
|
||||
properties: {
|
||||
email: {
|
||||
type: "string",
|
||||
example: "[email protected]",
|
||||
},
|
||||
name: {
|
||||
type: "string",
|
||||
},
|
||||
timeZone: {
|
||||
type: "string",
|
||||
example: "Europe/London",
|
||||
},
|
||||
locale: {
|
||||
type: "string",
|
||||
example: "en",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
security: [{ ApiKeyAuth: [] }],
|
||||
tags: [
|
||||
{ name: "users" },
|
||||
{ name: "event-types" },
|
||||
{ name: "bookings" },
|
||||
{ name: "attendees" },
|
||||
{ name: "payments" },
|
||||
{ name: "schedules" },
|
||||
{ name: "teams" },
|
||||
{ name: "memberships" },
|
||||
{
|
||||
name: "availabilities",
|
||||
description: "Allows modifying unique availabilities tied to a schedule.",
|
||||
},
|
||||
{ name: "custom-inputs" },
|
||||
{ name: "event-references" },
|
||||
{ name: "booking-references" },
|
||||
{ name: "destination-calendars" },
|
||||
{ name: "selected-calendars" },
|
||||
],
|
||||
},
|
||||
apiFolder: "pages/api",
|
||||
});
|
||||
|
||||
export default swaggerHandler();
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
async function authMiddleware(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(req.query);
|
||||
if (isAdmin) return;
|
||||
const eventType = await prisma.eventType.findFirst({
|
||||
where: { id, users: { some: { id: userId } } },
|
||||
});
|
||||
if (!eventType) throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
}
|
||||
|
||||
export default authMiddleware;
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /event-types/{id}:
|
||||
* delete:
|
||||
* operationId: removeEventTypeById
|
||||
* summary: Remove an existing eventType
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the eventType to delete
|
||||
* tags:
|
||||
* - event-types
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/core-features/event-types
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, eventType removed successfully
|
||||
* 400:
|
||||
* description: Bad request. EventType id is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function deleteHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
await checkPermissions(req);
|
||||
await prisma.eventType.delete({ where: { id } });
|
||||
return { message: `Event Type with id: ${id} deleted successfully` };
|
||||
}
|
||||
|
||||
async function checkPermissions(req: NextApiRequest) {
|
||||
const { userId, prisma, isAdmin } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(req.query);
|
||||
if (isAdmin) return;
|
||||
/** Only event type owners can delete it */
|
||||
const eventType = await prisma.eventType.findFirst({ where: { id, userId } });
|
||||
if (!eventType) throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
}
|
||||
|
||||
export default defaultResponder(deleteHandler);
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaEventTypeReadPublic } from "~/lib/validations/event-type";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
import getCalLink from "../_utils/getCalLink";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /event-types/{id}:
|
||||
* get:
|
||||
* operationId: getEventTypeById
|
||||
* summary: Find a eventType
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* - in: path
|
||||
* name: id
|
||||
* example: 4
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the eventType to get
|
||||
* tags:
|
||||
* - event-types
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/core-features/event-types
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: EventType was not found
|
||||
*/
|
||||
export async function getHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const event_type = await prisma.eventType.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
customInputs: true,
|
||||
team: { select: { slug: true } },
|
||||
users: true,
|
||||
owner: { select: { username: true, id: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const link = event_type ? getCalLink(event_type) : null;
|
||||
|
||||
return { event_type: schemaEventTypeReadPublic.parse({ ...event_type, link }) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,233 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
|
||||
import type { schemaEventTypeBaseBodyParams } from "~/lib/validations/event-type";
|
||||
import { schemaEventTypeEditBodyParams, schemaEventTypeReadPublic } from "~/lib/validations/event-type";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
import ensureOnlyMembersAsHosts from "~/pages/api/event-types/_utils/ensureOnlyMembersAsHosts";
|
||||
|
||||
import checkTeamEventEditPermission from "../_utils/checkTeamEventEditPermission";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /event-types/{id}:
|
||||
* patch:
|
||||
* operationId: editEventTypeById
|
||||
* summary: Edit an existing eventType
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the eventType to edit
|
||||
* requestBody:
|
||||
* description: Create a new event-type related to your user or team
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* length:
|
||||
* type: integer
|
||||
* description: Duration of the event type in minutes
|
||||
* metadata:
|
||||
* type: object
|
||||
* description: Metadata relating to event type. Pass {} if empty
|
||||
* title:
|
||||
* type: string
|
||||
* description: Title of the event type
|
||||
* slug:
|
||||
* type: string
|
||||
* description: Unique slug for the event type
|
||||
* hosts:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* userId:
|
||||
* type: number
|
||||
* isFixed:
|
||||
* type: boolean
|
||||
* description: Host MUST be available for any slot to be bookable.
|
||||
* hidden:
|
||||
* type: boolean
|
||||
* description: If the event type should be hidden from your public booking page
|
||||
* position:
|
||||
* type: integer
|
||||
* description: The position of the event type on the public booking page
|
||||
* teamId:
|
||||
* type: integer
|
||||
* description: Team ID if the event type should belong to a team
|
||||
* periodType:
|
||||
* type: string
|
||||
* enum: [UNLIMITED, ROLLING, RANGE]
|
||||
* description: To decide how far into the future an invitee can book an event with you
|
||||
* periodStartDate:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* description: Start date of bookable period (Required if periodType is 'range')
|
||||
* periodEndDate:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* description: End date of bookable period (Required if periodType is 'range')
|
||||
* periodDays:
|
||||
* type: integer
|
||||
* description: Number of bookable days (Required if periodType is rolling)
|
||||
* periodCountCalendarDays:
|
||||
* type: boolean
|
||||
* description: If calendar days should be counted for period days
|
||||
* requiresConfirmation:
|
||||
* type: boolean
|
||||
* description: If the event type should require your confirmation before completing the booking
|
||||
* recurringEvent:
|
||||
* type: object
|
||||
* description: If the event should recur every week/month/year with the selected frequency
|
||||
* properties:
|
||||
* interval:
|
||||
* type: integer
|
||||
* count:
|
||||
* type: integer
|
||||
* freq:
|
||||
* type: integer
|
||||
* disableGuests:
|
||||
* type: boolean
|
||||
* description: If the event type should disable adding guests to the booking
|
||||
* hideCalendarNotes:
|
||||
* type: boolean
|
||||
* description: If the calendar notes should be hidden from the booking
|
||||
* minimumBookingNotice:
|
||||
* type: integer
|
||||
* description: Minimum time in minutes before the event is bookable
|
||||
* beforeEventBuffer:
|
||||
* type: integer
|
||||
* description: Number of minutes of buffer time before a Cal Event
|
||||
* afterEventBuffer:
|
||||
* type: integer
|
||||
* description: Number of minutes of buffer time after a Cal Event
|
||||
* schedulingType:
|
||||
* type: string
|
||||
* description: The type of scheduling if a Team event. Required for team events only
|
||||
* enum: [ROUND_ROBIN, COLLECTIVE]
|
||||
* price:
|
||||
* type: integer
|
||||
* description: Price of the event type booking
|
||||
* currency:
|
||||
* type: string
|
||||
* description: Currency acronym. Eg- usd, eur, gbp, etc.
|
||||
* slotInterval:
|
||||
* type: integer
|
||||
* description: The intervals of available bookable slots in minutes
|
||||
* successRedirectUrl:
|
||||
* type: string
|
||||
* format: url
|
||||
* description: A valid URL where the booker will redirect to, once the booking is completed successfully
|
||||
* description:
|
||||
* type: string
|
||||
* description: Description of the event type
|
||||
* seatsPerTimeSlot:
|
||||
* type: integer
|
||||
* description: 'The number of seats for each time slot'
|
||||
* seatsShowAttendees:
|
||||
* type: boolean
|
||||
* description: 'Share Attendee information in seats'
|
||||
* locations:
|
||||
* type: array
|
||||
* description: A list of all available locations for the event type
|
||||
* items:
|
||||
* type: array
|
||||
* items:
|
||||
* oneOf:
|
||||
* - type: object
|
||||
* properties:
|
||||
* type:
|
||||
* type: string
|
||||
* enum: ['integrations:daily']
|
||||
* - type: object
|
||||
* properties:
|
||||
* type:
|
||||
* type: string
|
||||
* enum: ['attendeeInPerson']
|
||||
* - type: object
|
||||
* properties:
|
||||
* type:
|
||||
* type: string
|
||||
* enum: ['inPerson']
|
||||
* address:
|
||||
* type: string
|
||||
* displayLocationPublicly:
|
||||
* type: boolean
|
||||
* - type: object
|
||||
* properties:
|
||||
* type:
|
||||
* type: string
|
||||
* enum: ['link']
|
||||
* link:
|
||||
* type: string
|
||||
* displayLocationPublicly:
|
||||
* type: boolean
|
||||
* example:
|
||||
* event-type:
|
||||
* summary: An example of event type PATCH request
|
||||
* value:
|
||||
* length: 60
|
||||
* requiresConfirmation: true
|
||||
* tags:
|
||||
* - event-types
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/core-features/event-types
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, eventType edited successfully
|
||||
* 400:
|
||||
* description: Bad request. EventType body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function patchHandler(req: NextApiRequest) {
|
||||
const { prisma, query, body } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const { hosts = [], ...parsedBody } = schemaEventTypeEditBodyParams.parse(body);
|
||||
|
||||
const data: Prisma.EventTypeUpdateArgs["data"] = {
|
||||
...parsedBody,
|
||||
};
|
||||
|
||||
if (hosts) {
|
||||
await ensureOnlyMembersAsHosts(req, parsedBody);
|
||||
data.hosts = {
|
||||
deleteMany: {},
|
||||
create: hosts.map((host) => ({
|
||||
...host,
|
||||
isFixed: data.schedulingType === SchedulingType.COLLECTIVE || host.isFixed,
|
||||
})),
|
||||
};
|
||||
}
|
||||
await checkPermissions(req, parsedBody);
|
||||
const eventType = await prisma.eventType.update({ where: { id }, data });
|
||||
return { event_type: schemaEventTypeReadPublic.parse(eventType) };
|
||||
}
|
||||
|
||||
async function checkPermissions(req: NextApiRequest, body: z.infer<typeof schemaEventTypeBaseBodyParams>) {
|
||||
const { userId, prisma, isAdmin } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(req.query);
|
||||
if (isAdmin) return;
|
||||
/** Only event type owners can modify it */
|
||||
const eventType = await prisma.eventType.findFirst({ where: { id, userId } });
|
||||
if (!eventType) throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
await checkTeamEventEditPermission(req, body);
|
||||
}
|
||||
|
||||
export default defaultResponder(patchHandler);
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
import authMiddleware from "./_auth-middleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await authMiddleware(req);
|
||||
return defaultHandler({
|
||||
GET: import("./_get"),
|
||||
PATCH: import("./_patch"),
|
||||
DELETE: import("./_delete"),
|
||||
})(req, res);
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaEventTypeReadPublic } from "~/lib/validations/event-type";
|
||||
import { schemaQuerySingleOrMultipleUserIds } from "~/lib/validations/shared/queryUserId";
|
||||
|
||||
import getCalLink from "./_utils/getCalLink";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /event-types:
|
||||
* get:
|
||||
* summary: Find all event types
|
||||
* operationId: listEventTypes
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* tags:
|
||||
* - event-types
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/core-features/event-types
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: No event types were found
|
||||
*/
|
||||
async function getHandler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
|
||||
const args: Prisma.EventTypeFindManyArgs = {
|
||||
where: { userId },
|
||||
};
|
||||
/** Only admins can query other users */
|
||||
if (!isAdmin && req.query.userId) throw new HttpError({ statusCode: 401, message: "ADMIN required" });
|
||||
if (isAdmin && req.query.userId) {
|
||||
const query = schemaQuerySingleOrMultipleUserIds.parse(req.query);
|
||||
const userIds = Array.isArray(query.userId) ? query.userId : [query.userId || userId];
|
||||
args.where = { userId: { in: userIds } };
|
||||
}
|
||||
const data = await prisma.eventType.findMany({
|
||||
...args,
|
||||
include: {
|
||||
customInputs: true,
|
||||
team: { select: { slug: true } },
|
||||
users: true,
|
||||
owner: { select: { username: true, id: true } },
|
||||
},
|
||||
});
|
||||
return {
|
||||
event_types: data.map((eventType) => {
|
||||
const link = getCalLink(eventType);
|
||||
return schemaEventTypeReadPublic.parse({ ...eventType, link });
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,265 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaEventTypeCreateBodyParams, schemaEventTypeReadPublic } from "~/lib/validations/event-type";
|
||||
|
||||
import checkTeamEventEditPermission from "./_utils/checkTeamEventEditPermission";
|
||||
import ensureOnlyMembersAsHosts from "./_utils/ensureOnlyMembersAsHosts";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /event-types:
|
||||
* post:
|
||||
* summary: Creates a new event type
|
||||
* operationId: addEventType
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* requestBody:
|
||||
* description: Create a new event-type related to your user or team
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - title
|
||||
* - slug
|
||||
* - length
|
||||
* - metadata
|
||||
* properties:
|
||||
* length:
|
||||
* type: integer
|
||||
* description: Duration of the event type in minutes
|
||||
* metadata:
|
||||
* type: object
|
||||
* description: Metadata relating to event type. Pass {} if empty
|
||||
* title:
|
||||
* type: string
|
||||
* description: Title of the event type
|
||||
* slug:
|
||||
* type: string
|
||||
* description: Unique slug for the event type
|
||||
* example: my-event
|
||||
* hosts:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* userId:
|
||||
* type: number
|
||||
* isFixed:
|
||||
* type: boolean
|
||||
* description: Host MUST be available for any slot to be bookable.
|
||||
* hidden:
|
||||
* type: boolean
|
||||
* description: If the event type should be hidden from your public booking page
|
||||
* position:
|
||||
* type: integer
|
||||
* description: The position of the event type on the public booking page
|
||||
* teamId:
|
||||
* type: integer
|
||||
* description: Team ID if the event type should belong to a team
|
||||
* periodType:
|
||||
* type: string
|
||||
* enum: [UNLIMITED, ROLLING, RANGE]
|
||||
* description: To decide how far into the future an invitee can book an event with you
|
||||
* periodStartDate:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* description: Start date of bookable period (Required if periodType is 'range')
|
||||
* periodEndDate:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* description: End date of bookable period (Required if periodType is 'range')
|
||||
* periodDays:
|
||||
* type: integer
|
||||
* description: Number of bookable days (Required if periodType is rolling)
|
||||
* periodCountCalendarDays:
|
||||
* type: boolean
|
||||
* description: If calendar days should be counted for period days
|
||||
* requiresConfirmation:
|
||||
* type: boolean
|
||||
* description: If the event type should require your confirmation before completing the booking
|
||||
* recurringEvent:
|
||||
* type: object
|
||||
* description: If the event should recur every week/month/year with the selected frequency
|
||||
* properties:
|
||||
* interval:
|
||||
* type: integer
|
||||
* count:
|
||||
* type: integer
|
||||
* freq:
|
||||
* type: integer
|
||||
* disableGuests:
|
||||
* type: boolean
|
||||
* description: If the event type should disable adding guests to the booking
|
||||
* hideCalendarNotes:
|
||||
* type: boolean
|
||||
* description: If the calendar notes should be hidden from the booking
|
||||
* minimumBookingNotice:
|
||||
* type: integer
|
||||
* description: Minimum time in minutes before the event is bookable
|
||||
* beforeEventBuffer:
|
||||
* type: integer
|
||||
* description: Number of minutes of buffer time before a Cal Event
|
||||
* afterEventBuffer:
|
||||
* type: integer
|
||||
* description: Number of minutes of buffer time after a Cal Event
|
||||
* schedulingType:
|
||||
* type: string
|
||||
* description: The type of scheduling if a Team event. Required for team events only
|
||||
* enum: [ROUND_ROBIN, COLLECTIVE]
|
||||
* price:
|
||||
* type: integer
|
||||
* description: Price of the event type booking
|
||||
* currency:
|
||||
* type: string
|
||||
* description: Currency acronym. Eg- usd, eur, gbp, etc.
|
||||
* slotInterval:
|
||||
* type: integer
|
||||
* description: The intervals of available bookable slots in minutes
|
||||
* successRedirectUrl:
|
||||
* type: string
|
||||
* format: url
|
||||
* description: A valid URL where the booker will redirect to, once the booking is completed successfully
|
||||
* description:
|
||||
* type: string
|
||||
* description: Description of the event type
|
||||
* locations:
|
||||
* type: array
|
||||
* description: A list of all available locations for the event type
|
||||
* items:
|
||||
* type: array
|
||||
* items:
|
||||
* oneOf:
|
||||
* - type: object
|
||||
* properties:
|
||||
* type:
|
||||
* type: string
|
||||
* enum: ['integrations:daily']
|
||||
* - type: object
|
||||
* properties:
|
||||
* type:
|
||||
* type: string
|
||||
* enum: ['attendeeInPerson']
|
||||
* - type: object
|
||||
* properties:
|
||||
* type:
|
||||
* type: string
|
||||
* enum: ['inPerson']
|
||||
* address:
|
||||
* type: string
|
||||
* displayLocationPublicly:
|
||||
* type: boolean
|
||||
* - type: object
|
||||
* properties:
|
||||
* type:
|
||||
* type: string
|
||||
* enum: ['link']
|
||||
* link:
|
||||
* type: string
|
||||
* displayLocationPublicly:
|
||||
* type: boolean
|
||||
* example:
|
||||
* event-type:
|
||||
* summary: An example of event type POST request
|
||||
* value:
|
||||
* title: Hello World
|
||||
* slug: hello-world
|
||||
* length: 30
|
||||
* hidden: false
|
||||
* position: 0
|
||||
* eventName: null
|
||||
* timeZone: null
|
||||
* periodType: UNLIMITED
|
||||
* periodStartDate: 2023-02-15T08:46:16.000Z
|
||||
* periodEndDate: 2023-0-15T08:46:16.000Z
|
||||
* periodDays: null
|
||||
* periodCountCalendarDays: false
|
||||
* requiresConfirmation: false
|
||||
* recurringEvent: null
|
||||
* disableGuests: false
|
||||
* hideCalendarNotes: false
|
||||
* minimumBookingNotice: 120
|
||||
* beforeEventBuffer: 0
|
||||
* afterEventBuffer: 0
|
||||
* price: 0
|
||||
* currency: usd
|
||||
* slotInterval: null
|
||||
* successRedirectUrl: null
|
||||
* description: A test event type
|
||||
* metadata: {
|
||||
* apps: {
|
||||
* stripe: {
|
||||
* price: 0,
|
||||
* enabled: false,
|
||||
* currency: usd
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* tags:
|
||||
* - event-types
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/core-features/event-types
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, event type created
|
||||
* 400:
|
||||
* description: Bad request. EventType body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
async function postHandler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma, body } = req;
|
||||
|
||||
const { hosts = [], ...parsedBody } = schemaEventTypeCreateBodyParams.parse(body || {});
|
||||
|
||||
let data: Prisma.EventTypeCreateArgs["data"] = {
|
||||
...parsedBody,
|
||||
userId,
|
||||
users: { connect: { id: userId } },
|
||||
};
|
||||
|
||||
await checkPermissions(req);
|
||||
|
||||
if (isAdmin && parsedBody.userId) {
|
||||
data = { ...parsedBody, users: { connect: { id: parsedBody.userId } } };
|
||||
}
|
||||
|
||||
await checkTeamEventEditPermission(req, parsedBody);
|
||||
await ensureOnlyMembersAsHosts(req, parsedBody);
|
||||
|
||||
if (hosts) {
|
||||
data.hosts = { createMany: { data: hosts } };
|
||||
}
|
||||
|
||||
const eventType = await prisma.eventType.create({ data });
|
||||
|
||||
return {
|
||||
event_type: schemaEventTypeReadPublic.parse(eventType),
|
||||
message: "Event type created successfully",
|
||||
};
|
||||
}
|
||||
|
||||
async function checkPermissions(req: NextApiRequest) {
|
||||
const { isAdmin } = req;
|
||||
const body = schemaEventTypeCreateBodyParams.parse(req.body);
|
||||
/* Non-admin users can only create event types for themselves */
|
||||
if (!isAdmin && body.userId)
|
||||
throw new HttpError({
|
||||
statusCode: 401,
|
||||
message: "ADMIN required for `userId`",
|
||||
});
|
||||
/* Admin users are required to pass in a userId */
|
||||
if (isAdmin && !body.userId) throw new HttpError({ statusCode: 400, message: "`userId` required" });
|
||||
}
|
||||
|
||||
export default defaultResponder(postHandler);
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
import type { schemaEventTypeBaseBodyParams } from "~/lib/validations/event-type";
|
||||
|
||||
export default async function checkTeamEventEditPermission(
|
||||
req: NextApiRequest,
|
||||
body: Pick<z.infer<typeof schemaEventTypeBaseBodyParams>, "teamId">
|
||||
) {
|
||||
const { prisma, userId } = req;
|
||||
if (body.teamId) {
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId: body.teamId,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership?.role || !["ADMIN", "OWNER"].includes(membership.role)) {
|
||||
throw new HttpError({
|
||||
statusCode: 401,
|
||||
message: "No permission to operate on event-type for this team",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
import type { z } from "zod";
|
||||
|
||||
import type { schemaEventTypeCreateBodyParams } from "~/lib/validations/event-type";
|
||||
|
||||
export default async function ensureOnlyMembersAsHosts(
|
||||
req: NextApiRequest,
|
||||
body: Pick<z.infer<typeof schemaEventTypeCreateBodyParams>, "hosts" | "teamId">
|
||||
) {
|
||||
if (body.teamId && body.hosts && body.hosts.length > 0) {
|
||||
const teamMemberCount = await req.prisma.membership.count({
|
||||
where: {
|
||||
teamId: body.teamId,
|
||||
userId: { in: body.hosts.map((host) => host.userId) },
|
||||
},
|
||||
});
|
||||
if (teamMemberCount !== body.hosts.length) {
|
||||
throw new Error("You can only add members of the team to a team event type.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { CAL_URL } from "@calcom/lib/constants";
|
||||
|
||||
export default function getCalLink(eventType: {
|
||||
team?: { slug: string | null } | null;
|
||||
owner: { username: string | null } | null;
|
||||
users?: { username: string | null }[];
|
||||
slug: string;
|
||||
}) {
|
||||
return `${CAL_URL}/${
|
||||
eventType?.team
|
||||
? `team/${eventType?.team?.slug}`
|
||||
: eventType?.owner
|
||||
? eventType.owner.username
|
||||
: eventType?.users?.[0]?.username
|
||||
}/${eventType?.slug}`;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
GET: import("./_get"),
|
||||
POST: import("./_post"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,5 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function CalcomApi(_: NextApiRequest, res: NextApiResponse) {
|
||||
res.status(201).json({ message: "Welcome to Cal.com API - docs are at https://developer.cal.com/api" });
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaUserReadPublic } from "~/lib/validations/user";
|
||||
|
||||
async function handler({ userId, prisma }: NextApiRequest) {
|
||||
const data = await prisma.user.findUniqueOrThrow({ where: { id: userId } });
|
||||
return { user: schemaUserReadPublic.parse(data) };
|
||||
}
|
||||
|
||||
export default defaultResponder(handler);
|
||||
@@ -0,0 +1,9 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
GET: import("./_get"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
import { membershipIdSchema } from "~/lib/validations/membership";
|
||||
|
||||
async function authMiddleware(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const { teamId } = membershipIdSchema.parse(req.query);
|
||||
// Admins can just skip this check
|
||||
if (isAdmin) return;
|
||||
// Only team members can modify a membership
|
||||
const membership = await prisma.membership.findFirst({ where: { userId, teamId } });
|
||||
if (!membership) throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
}
|
||||
|
||||
export default authMiddleware;
|
||||
@@ -0,0 +1,102 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { membershipIdSchema } from "~/lib/validations/membership";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /memberships/{userId}_{teamId}:
|
||||
* delete:
|
||||
* summary: Remove an existing membership
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: userId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: Numeric userId of the membership to get
|
||||
* - in: path
|
||||
* name: teamId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: Numeric teamId of the membership to get
|
||||
* tags:
|
||||
* - memberships
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, membership removed successfuly
|
||||
* 400:
|
||||
* description: Bad request. Membership id is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function deleteHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const userId_teamId = membershipIdSchema.parse(query);
|
||||
await checkPermissions(req);
|
||||
await prisma.membership.delete({ where: { userId_teamId } });
|
||||
return { message: `Membership with id: ${query.id} deleted successfully` };
|
||||
}
|
||||
|
||||
async function checkPermissions(req: NextApiRequest) {
|
||||
const { prisma, isAdmin, userId, query } = req;
|
||||
const userId_teamId = membershipIdSchema.parse(query);
|
||||
// Admin User can do anything including deletion of Admin Team Member in any team
|
||||
if (isAdmin) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Owner can delete Admin and Member
|
||||
// Admin Team Member can delete Member
|
||||
// Member can't delete anyone
|
||||
const PRIVILEGE_ORDER = ["OWNER", "ADMIN", "MEMBER"];
|
||||
|
||||
const memberShipToBeDeleted = await prisma.membership.findUnique({
|
||||
where: { userId_teamId },
|
||||
});
|
||||
|
||||
if (!memberShipToBeDeleted) {
|
||||
throw new HttpError({ statusCode: 404, message: "Membership not found" });
|
||||
}
|
||||
|
||||
// If a user is deleting their own membership, then they can do it
|
||||
if (userId === memberShipToBeDeleted.userId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentUserMembership = await prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId,
|
||||
teamId: memberShipToBeDeleted.teamId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!currentUserMembership) {
|
||||
// Current User isn't a member of the team
|
||||
throw new HttpError({ statusCode: 403, message: "You are not a member of the team" });
|
||||
}
|
||||
|
||||
if (
|
||||
PRIVILEGE_ORDER.indexOf(memberShipToBeDeleted.role) === -1 ||
|
||||
PRIVILEGE_ORDER.indexOf(currentUserMembership.role) === -1
|
||||
) {
|
||||
throw new HttpError({ statusCode: 400, message: "Invalid role" });
|
||||
}
|
||||
|
||||
// If Role that is being deleted comes before the current User's Role, or it's the same ROLE, throw error
|
||||
if (
|
||||
PRIVILEGE_ORDER.indexOf(memberShipToBeDeleted.role) <= PRIVILEGE_ORDER.indexOf(currentUserMembership.role)
|
||||
) {
|
||||
throw new HttpError({
|
||||
statusCode: 403,
|
||||
message: "You don't have the appropriate role to delete this membership",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default defaultResponder(deleteHandler);
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { membershipIdSchema, schemaMembershipPublic } from "~/lib/validations/membership";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /memberships/{userId}_{teamId}:
|
||||
* get:
|
||||
* summary: Find a membership by userID and teamID
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: userId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: Numeric userId of the membership to get
|
||||
* - in: path
|
||||
* name: teamId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: Numeric teamId of the membership to get
|
||||
* tags:
|
||||
* - memberships
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: Membership was not found
|
||||
*/
|
||||
export async function getHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const userId_teamId = membershipIdSchema.parse(query);
|
||||
const args: Prisma.MembershipFindUniqueOrThrowArgs = { where: { userId_teamId } };
|
||||
// Just in case the user want to get more info about the team itself
|
||||
if (req.query.include === "team") args.include = { team: true };
|
||||
const data = await prisma.membership.findUniqueOrThrow(args);
|
||||
return { membership: schemaMembershipPublic.parse(data) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import {
|
||||
membershipEditBodySchema,
|
||||
membershipIdSchema,
|
||||
schemaMembershipPublic,
|
||||
} from "~/lib/validations/membership";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /memberships/{userId}_{teamId}:
|
||||
* patch:
|
||||
* summary: Edit an existing membership
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: userId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: Numeric userId of the membership to get
|
||||
* - in: path
|
||||
* name: teamId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: Numeric teamId of the membership to get
|
||||
* tags:
|
||||
* - memberships
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, membership edited successfully
|
||||
* 400:
|
||||
* description: Bad request. Membership body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function patchHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const userId_teamId = membershipIdSchema.parse(query);
|
||||
const data = membershipEditBodySchema.parse(req.body);
|
||||
const args: Prisma.MembershipUpdateArgs = { where: { userId_teamId }, data };
|
||||
|
||||
await checkPermissions(req);
|
||||
|
||||
const result = await prisma.membership.update(args);
|
||||
return { membership: schemaMembershipPublic.parse(result) };
|
||||
}
|
||||
|
||||
async function checkPermissions(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const { userId: queryUserId, teamId } = membershipIdSchema.parse(req.query);
|
||||
const data = membershipEditBodySchema.parse(req.body);
|
||||
// Admins can just skip this check
|
||||
if (isAdmin) return;
|
||||
// Only the invited user can accept the invite
|
||||
if ("accepted" in data && queryUserId !== userId)
|
||||
throw new HttpError({
|
||||
statusCode: 403,
|
||||
message: "Only the invited user can accept the invite",
|
||||
});
|
||||
// Only team OWNERS and ADMINS can modify `role`
|
||||
if ("role" in data) {
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: { userId, teamId, role: { in: ["ADMIN", "OWNER"] } },
|
||||
});
|
||||
if (!membership || (membership.role !== "OWNER" && req.body.role === "OWNER"))
|
||||
throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
}
|
||||
}
|
||||
|
||||
export default defaultResponder(patchHandler);
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
import authMiddleware from "./_auth-middleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await authMiddleware(req);
|
||||
return defaultHandler({
|
||||
GET: import("./_get"),
|
||||
PATCH: import("./_patch"),
|
||||
DELETE: import("./_delete"),
|
||||
})(req, res);
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaMembershipPublic } from "~/lib/validations/membership";
|
||||
import {
|
||||
schemaQuerySingleOrMultipleTeamIds,
|
||||
schemaQuerySingleOrMultipleUserIds,
|
||||
} from "~/lib/validations/shared/queryUserId";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /memberships:
|
||||
* get:
|
||||
* summary: Find all memberships
|
||||
* tags:
|
||||
* - memberships
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: No memberships were found
|
||||
*/
|
||||
async function getHandler(req: NextApiRequest) {
|
||||
const { prisma } = req;
|
||||
const args: Prisma.MembershipFindManyArgs = {
|
||||
where: {
|
||||
/** Admins can query multiple users */
|
||||
userId: { in: getUserIds(req) },
|
||||
/** Admins can query multiple teams as well */
|
||||
teamId: { in: getTeamIds(req) },
|
||||
},
|
||||
};
|
||||
// Just in case the user want to get more info about the team itself
|
||||
if (req.query.include === "team") args.include = { team: true };
|
||||
|
||||
const data = await prisma.membership.findMany(args);
|
||||
return { memberships: data.map((v) => schemaMembershipPublic.parse(v)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns requested users IDs only if admin, otherwise return only current user ID
|
||||
*/
|
||||
function getUserIds(req: NextApiRequest) {
|
||||
const { userId, isAdmin } = req;
|
||||
/** Only admins can query other users */
|
||||
if (!isAdmin && req.query.userId) throw new HttpError({ statusCode: 403, message: "ADMIN required" });
|
||||
if (isAdmin && req.query.userId) {
|
||||
const query = schemaQuerySingleOrMultipleUserIds.parse(req.query);
|
||||
const userIds = Array.isArray(query.userId) ? query.userId : [query.userId || userId];
|
||||
return userIds;
|
||||
}
|
||||
// Return all memberships for ADMIN, limit to current user to non-admins
|
||||
return isAdmin ? undefined : [userId];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns requested teams IDs only if admin
|
||||
*/
|
||||
function getTeamIds(req: NextApiRequest) {
|
||||
const { isAdmin } = req;
|
||||
/** Only admins can query other teams */
|
||||
if (!isAdmin && req.query.teamId) throw new HttpError({ statusCode: 403, message: "ADMIN required" });
|
||||
if (isAdmin && req.query.teamId) {
|
||||
const query = schemaQuerySingleOrMultipleTeamIds.parse(req.query);
|
||||
const teamIds = Array.isArray(query.teamId) ? query.teamId : [query.teamId];
|
||||
return teamIds;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { membershipCreateBodySchema, schemaMembershipPublic } from "~/lib/validations/membership";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /memberships:
|
||||
* post:
|
||||
* summary: Creates a new membership
|
||||
* tags:
|
||||
* - memberships
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, membership created
|
||||
* 400:
|
||||
* description: Bad request. Membership body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
async function postHandler(req: NextApiRequest) {
|
||||
const { prisma } = req;
|
||||
const data = membershipCreateBodySchema.parse(req.body);
|
||||
const args: Prisma.MembershipCreateArgs = { data };
|
||||
|
||||
await checkPermissions(req);
|
||||
|
||||
const result = await prisma.membership.create(args);
|
||||
|
||||
return {
|
||||
membership: schemaMembershipPublic.parse(result),
|
||||
message: "Membership created successfully",
|
||||
};
|
||||
}
|
||||
|
||||
async function checkPermissions(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
if (isAdmin) return;
|
||||
const body = membershipCreateBodySchema.parse(req.body);
|
||||
// To prevent auto-accepted invites, limit it to ADMIN users
|
||||
if (!isAdmin && "accepted" in body)
|
||||
throw new HttpError({ statusCode: 403, message: "ADMIN needed for `accepted`" });
|
||||
// Only team OWNERS and ADMINS can add other members
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: { userId, teamId: body.teamId, role: { in: ["ADMIN", "OWNER"] } },
|
||||
});
|
||||
if (!membership) throw new HttpError({ statusCode: 403, message: "You can't add members to this team" });
|
||||
}
|
||||
|
||||
export default defaultResponder(postHandler);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
GET: import("./_get"),
|
||||
POST: import("./_post"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
import type { PaymentResponse } from "~/lib/types";
|
||||
import { schemaPaymentPublic } from "~/lib/validations/payment";
|
||||
import {
|
||||
schemaQueryIdParseInt,
|
||||
withValidQueryIdTransformParseInt,
|
||||
} from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /payments/{id}:
|
||||
* get:
|
||||
* summary: Find a payment
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the payment to get
|
||||
* tags:
|
||||
* - payments
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: Payment was not found
|
||||
*/
|
||||
export async function paymentById(
|
||||
{ method, query, userId, prisma }: NextApiRequest,
|
||||
res: NextApiResponse<PaymentResponse>
|
||||
) {
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
if (safeQuery.success && method === "GET") {
|
||||
const userWithBookings = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
include: { bookings: true },
|
||||
});
|
||||
await prisma.payment
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaPaymentPublic.parse(data))
|
||||
.then((payment) => {
|
||||
if (!userWithBookings?.bookings.map((b) => b.id).includes(payment.bookingId)) {
|
||||
res.status(401).json({ message: "Unauthorized" });
|
||||
} else {
|
||||
res.status(200).json({ payment });
|
||||
}
|
||||
})
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `Payment with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
export default withMiddleware("HTTP_GET")(withValidQueryIdTransformParseInt(paymentById));
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
import type { PaymentsResponse } from "~/lib/types";
|
||||
import { schemaPaymentPublic } from "~/lib/validations/payment";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /payments:
|
||||
* get:
|
||||
* summary: Find all payments
|
||||
* tags:
|
||||
* - payments
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: No payments were found
|
||||
*/
|
||||
async function allPayments({ userId, prisma }: NextApiRequest, res: NextApiResponse<PaymentsResponse>) {
|
||||
const userWithBookings = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
include: { bookings: true },
|
||||
});
|
||||
if (!userWithBookings) throw new Error("No user found");
|
||||
const bookings = userWithBookings.bookings;
|
||||
const bookingIds = bookings.map((booking) => booking.id);
|
||||
const data = await prisma.payment.findMany({ where: { bookingId: { in: bookingIds } } });
|
||||
const payments = data.map((payment) => schemaPaymentPublic.parse(payment));
|
||||
|
||||
if (payments) res.status(200).json({ payments });
|
||||
else
|
||||
(error: Error) =>
|
||||
res.status(404).json({
|
||||
message: "No Payments were found",
|
||||
error,
|
||||
});
|
||||
}
|
||||
// NO POST FOR PAYMENTS FOR NOW
|
||||
export default withMiddleware("HTTP_GET")(allPayments);
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
async function authMiddleware(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(req.query);
|
||||
// Admins can just skip this check
|
||||
if (isAdmin) return;
|
||||
// Check if the current user can access the schedule
|
||||
const schedule = await prisma.schedule.findFirst({
|
||||
where: { id, userId },
|
||||
});
|
||||
if (!schedule) throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
}
|
||||
|
||||
export default authMiddleware;
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /schedules/{id}:
|
||||
* delete:
|
||||
* operationId: removeScheduleById
|
||||
* summary: Remove an existing schedule
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the schedule to delete
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* tags:
|
||||
* - schedules
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, schedule removed successfully
|
||||
* 400:
|
||||
* description: Bad request. Schedule id is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function deleteHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
|
||||
/* If we're deleting any default user schedule, we unset it */
|
||||
await prisma.user.updateMany({ where: { defaultScheduleId: id }, data: { defaultScheduleId: undefined } });
|
||||
|
||||
await prisma.schedule.delete({ where: { id } });
|
||||
return { message: `Schedule with id: ${id} deleted successfully` };
|
||||
}
|
||||
|
||||
export default defaultResponder(deleteHandler);
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaSchedulePublic } from "~/lib/validations/schedule";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /schedules/{id}:
|
||||
* get:
|
||||
* operationId: getScheduleById
|
||||
* summary: Find a schedule
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the schedule to get
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* tags:
|
||||
* - schedules
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* schedule:
|
||||
* value:
|
||||
* {
|
||||
* "schedule": {
|
||||
* "id": 12345,
|
||||
* "userId": 182,
|
||||
* "name": "Sample Schedule",
|
||||
* "timeZone": "Asia/Calcutta",
|
||||
* "availability": [
|
||||
* {
|
||||
* "id": 111,
|
||||
* "eventTypeId": null,
|
||||
* "days": [0, 1, 2, 3, 4, 6],
|
||||
* "startTime": "00:00:00",
|
||||
* "endTime": "23:45:00"
|
||||
* },
|
||||
* {
|
||||
* "id": 112,
|
||||
* "eventTypeId": null,
|
||||
* "days": [5],
|
||||
* "startTime": "00:00:00",
|
||||
* "endTime": "12:00:00"
|
||||
* },
|
||||
* {
|
||||
* "id": 113,
|
||||
* "eventTypeId": null,
|
||||
* "days": [5],
|
||||
* "startTime": "15:00:00",
|
||||
* "endTime": "23:45:00"
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: Schedule was not found
|
||||
*/
|
||||
|
||||
export async function getHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const data = await prisma.schedule.findUniqueOrThrow({ where: { id }, include: { availability: true } });
|
||||
return { schedule: schemaSchedulePublic.parse(data) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaSchedulePublic, schemaSingleScheduleBodyParams } from "~/lib/validations/schedule";
|
||||
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /schedules/{id}:
|
||||
* patch:
|
||||
* operationId: editScheduleById
|
||||
* summary: Edit an existing schedule
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the schedule to edit
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* requestBody:
|
||||
* description: Edit an existing schedule
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* name:
|
||||
* type: string
|
||||
* description: Name of the schedule
|
||||
* timeZone:
|
||||
* type: string
|
||||
* description: The timezone for this schedule
|
||||
* examples:
|
||||
* schedule:
|
||||
* value:
|
||||
* {
|
||||
* "name": "Updated Schedule",
|
||||
* "timeZone": "Asia/Calcutta"
|
||||
* }
|
||||
* tags:
|
||||
* - schedules
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK, schedule edited successfully
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* schedule:
|
||||
* value:
|
||||
* {
|
||||
* "schedule": {
|
||||
* "id": 12345,
|
||||
* "userId": 1,
|
||||
* "name": "Total Testing Part 2",
|
||||
* "timeZone": "Asia/Calcutta",
|
||||
* "availability": [
|
||||
* {
|
||||
* "id": 4567,
|
||||
* "eventTypeId": null,
|
||||
* "days": [1, 2, 3, 4, 5],
|
||||
* "startTime": "09:00:00",
|
||||
* "endTime": "17:00:00"
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
* 400:
|
||||
* description: Bad request. Schedule body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
|
||||
export async function patchHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { id } = schemaQueryIdParseInt.parse(query);
|
||||
const data = schemaSingleScheduleBodyParams.parse(req.body);
|
||||
await checkPermissions(req, data);
|
||||
const result = await prisma.schedule.update({ where: { id }, data, include: { availability: true } });
|
||||
return { schedule: schemaSchedulePublic.parse(result) };
|
||||
}
|
||||
|
||||
async function checkPermissions(req: NextApiRequest, body: z.infer<typeof schemaSingleScheduleBodyParams>) {
|
||||
const { isAdmin } = req;
|
||||
if (isAdmin) return;
|
||||
if (body.userId) {
|
||||
throw new HttpError({ statusCode: 403, message: "Non admin cannot change the owner of a schedule" });
|
||||
}
|
||||
//_auth-middleware takes care of verifying the ownership of schedule.
|
||||
}
|
||||
|
||||
export default defaultResponder(patchHandler);
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
import authMiddleware from "./_auth-middleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await authMiddleware(req);
|
||||
return defaultHandler({
|
||||
GET: import("./_get"),
|
||||
PATCH: import("./_patch"),
|
||||
DELETE: import("./_delete"),
|
||||
})(req, res);
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
import { z } from "zod";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaSchedulePublic } from "~/lib/validations/schedule";
|
||||
import { schemaQuerySingleOrMultipleUserIds } from "~/lib/validations/shared/queryUserId";
|
||||
|
||||
export const schemaUserIds = z
|
||||
.union([z.string(), z.array(z.string())])
|
||||
.transform((val) => (Array.isArray(val) ? val.map((v) => parseInt(v, 10)) : [parseInt(val, 10)]));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /schedules:
|
||||
* get:
|
||||
* operationId: listSchedules
|
||||
* summary: Find all schedules
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* tags:
|
||||
* - schedules
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* schedules:
|
||||
* value:
|
||||
* {
|
||||
* "schedules": [
|
||||
* {
|
||||
* "id": 1234,
|
||||
* "userId": 5678,
|
||||
* "name": "Sample Schedule 1",
|
||||
* "timeZone": "America/Chicago",
|
||||
* "availability": [
|
||||
* {
|
||||
* "id": 987,
|
||||
* "eventTypeId": null,
|
||||
* "days": [1, 2, 3, 4, 5],
|
||||
* "startTime": "09:00:00",
|
||||
* "endTime": "23:00:00"
|
||||
* }
|
||||
* ]
|
||||
* },
|
||||
* {
|
||||
* "id": 2345,
|
||||
* "userId": 6789,
|
||||
* "name": "Sample Schedule 2",
|
||||
* "timeZone": "Europe/Amsterdam",
|
||||
* "availability": [
|
||||
* {
|
||||
* "id": 876,
|
||||
* "eventTypeId": null,
|
||||
* "days": [1, 2, 3, 4, 5],
|
||||
* "startTime": "09:00:00",
|
||||
* "endTime": "17:00:00"
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: No schedules were found
|
||||
*/
|
||||
|
||||
async function handler(req: NextApiRequest) {
|
||||
const { prisma, userId, isAdmin } = req;
|
||||
const args: Prisma.ScheduleFindManyArgs = isAdmin ? {} : { where: { userId } };
|
||||
args.include = { availability: true };
|
||||
|
||||
if (!isAdmin && req.query.userId)
|
||||
throw new HttpError({
|
||||
statusCode: 401,
|
||||
message: "Unauthorized: Only admins can query other users",
|
||||
});
|
||||
|
||||
if (isAdmin && req.query.userId) {
|
||||
const query = schemaQuerySingleOrMultipleUserIds.parse(req.query);
|
||||
const userIds = Array.isArray(query.userId) ? query.userId : [query.userId || userId];
|
||||
args.where = { userId: { in: userIds } };
|
||||
if (Array.isArray(query.userId)) args.orderBy = { userId: "asc" };
|
||||
}
|
||||
const data = await prisma.schedule.findMany(args);
|
||||
return { schedules: data.map((s) => schemaSchedulePublic.parse(s)) };
|
||||
}
|
||||
|
||||
export default defaultResponder(handler);
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaCreateScheduleBodyParams, schemaSchedulePublic } from "~/lib/validations/schedule";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /schedules:
|
||||
* post:
|
||||
* operationId: addSchedule
|
||||
* summary: Creates a new schedule
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* requestBody:
|
||||
* description: Create a new schedule
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - name
|
||||
* - timeZone
|
||||
* properties:
|
||||
* name:
|
||||
* type: string
|
||||
* description: Name of the schedule
|
||||
* timeZone:
|
||||
* type: string
|
||||
* description: The timeZone for this schedule
|
||||
* examples:
|
||||
* schedule:
|
||||
* value:
|
||||
* {
|
||||
* "name": "Sample Schedule",
|
||||
* "timeZone": "Asia/Calcutta"
|
||||
* }
|
||||
* tags:
|
||||
* - schedules
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK, schedule created
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* schedule:
|
||||
* value:
|
||||
* {
|
||||
* "schedule": {
|
||||
* "id": 79471,
|
||||
* "userId": 182,
|
||||
* "name": "Total Testing",
|
||||
* "timeZone": "Asia/Calcutta",
|
||||
* "availability": [
|
||||
* {
|
||||
* "id": 337917,
|
||||
* "eventTypeId": null,
|
||||
* "days": [1, 2, 3, 4, 5],
|
||||
* "startTime": "09:00:00",
|
||||
* "endTime": "17:00:00"
|
||||
* }
|
||||
* ]
|
||||
* },
|
||||
* "message": "Schedule created successfully"
|
||||
* }
|
||||
* 400:
|
||||
* description: Bad request. Schedule body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
|
||||
async function postHandler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const body = schemaCreateScheduleBodyParams.parse(req.body);
|
||||
let args: Prisma.ScheduleCreateArgs = { data: { ...body, userId } };
|
||||
|
||||
/* If ADMIN we create the schedule for selected user */
|
||||
if (isAdmin && body.userId) args = { data: { ...body, userId: body.userId } };
|
||||
|
||||
if (!isAdmin && body.userId)
|
||||
throw new HttpError({ statusCode: 403, message: "ADMIN required for `userId`" });
|
||||
|
||||
// We create default availabilities for the schedule
|
||||
args.data.availability = {
|
||||
createMany: {
|
||||
data: getAvailabilityFromSchedule(DEFAULT_SCHEDULE).map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
},
|
||||
};
|
||||
// We include the recently created availability
|
||||
args.include = { availability: true };
|
||||
|
||||
const data = await prisma.schedule.create(args);
|
||||
|
||||
return {
|
||||
schedule: schemaSchedulePublic.parse(data),
|
||||
message: "Schedule created successfully",
|
||||
};
|
||||
}
|
||||
|
||||
export default defaultResponder(postHandler);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
GET: import("./_get"),
|
||||
POST: import("./_post"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
import { selectedCalendarIdSchema } from "~/lib/validations/selected-calendar";
|
||||
|
||||
async function authMiddleware(req: NextApiRequest) {
|
||||
const { userId, isAdmin } = req;
|
||||
const { userId: queryUserId } = selectedCalendarIdSchema.parse(req.query);
|
||||
// Admins can just skip this check
|
||||
if (isAdmin) return;
|
||||
// Check if the current user requesting is the same as the one being requested
|
||||
if (userId !== queryUserId) throw new HttpError({ statusCode: 403, message: "Forbidden" });
|
||||
}
|
||||
|
||||
export default authMiddleware;
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { selectedCalendarIdSchema } from "~/lib/validations/selected-calendar";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /selected-calendars/{userId}_{integration}_{externalId}:
|
||||
* delete:
|
||||
* operationId: removeSelectedCalendarById
|
||||
* summary: Remove a selected calendar
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* - in: path
|
||||
* name: userId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: userId of the selected calendar to get
|
||||
* - in: path
|
||||
* name: externalId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: externalId of the selected-calendar to get
|
||||
* - in: path
|
||||
* name: integration
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: integration of the selected calendar to get
|
||||
* tags:
|
||||
* - selected-calendars
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, selected-calendar removed successfully
|
||||
* 400:
|
||||
* description: Bad request. SelectedCalendar id is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function deleteHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const userId_integration_externalId = selectedCalendarIdSchema.parse(query);
|
||||
await prisma.selectedCalendar.delete({ where: { userId_integration_externalId } });
|
||||
return { message: `Selected Calendar with id: ${query.id} deleted successfully` };
|
||||
}
|
||||
|
||||
export default defaultResponder(deleteHandler);
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaSelectedCalendarPublic, selectedCalendarIdSchema } from "~/lib/validations/selected-calendar";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /selected-calendars/{userId}_{integration}_{externalId}:
|
||||
* get:
|
||||
* operationId: getSelectedCalendarById
|
||||
* summary: Find a selected calendar by providing the compoundId(userId_integration_externalId) separated by `_`
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* - in: path
|
||||
* name: userId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: userId of the selected calendar to get
|
||||
* - in: path
|
||||
* name: externalId
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: externalId of the selected calendar to get
|
||||
* - in: path
|
||||
* name: integration
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: integration of the selected calendar to get
|
||||
* tags:
|
||||
* - selected-calendars
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: SelectedCalendar was not found
|
||||
*/
|
||||
export async function getHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const userId_integration_externalId = selectedCalendarIdSchema.parse(query);
|
||||
const data = await prisma.selectedCalendar.findUniqueOrThrow({
|
||||
where: { userId_integration_externalId },
|
||||
});
|
||||
return { selected_calendar: schemaSelectedCalendarPublic.parse(data) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import {
|
||||
schemaSelectedCalendarPublic,
|
||||
schemaSelectedCalendarUpdateBodyParams,
|
||||
selectedCalendarIdSchema,
|
||||
} from "~/lib/validations/selected-calendar";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /selected-calendars/{userId}_{integration}_{externalId}:
|
||||
* patch:
|
||||
* operationId: editSelectedCalendarById
|
||||
* summary: Edit a selected calendar
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* - in: path
|
||||
* name: userId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: userId of the selected calendar to get
|
||||
* - in: path
|
||||
* name: externalId
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: externalId of the selected calendar to get
|
||||
* - in: path
|
||||
* name: integration
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: integration of the selected calendar to get
|
||||
* tags:
|
||||
* - selected-calendars
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, selected-calendar edited successfully
|
||||
* 400:
|
||||
* description: Bad request. SelectedCalendar body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function patchHandler(req: NextApiRequest) {
|
||||
const { prisma, query, isAdmin } = req;
|
||||
const userId_integration_externalId = selectedCalendarIdSchema.parse(query);
|
||||
const { userId: bodyUserId, ...data } = schemaSelectedCalendarUpdateBodyParams.parse(req.body);
|
||||
const args: Prisma.SelectedCalendarUpdateArgs = { where: { userId_integration_externalId }, data };
|
||||
|
||||
if (!isAdmin && bodyUserId) throw new HttpError({ statusCode: 403, message: `ADMIN required for userId` });
|
||||
|
||||
if (isAdmin && bodyUserId) {
|
||||
const where: Prisma.UserWhereInput = { id: bodyUserId };
|
||||
await prisma.user.findFirstOrThrow({ where });
|
||||
args.data.userId = bodyUserId;
|
||||
}
|
||||
|
||||
const result = await prisma.selectedCalendar.update(args);
|
||||
return { selected_calendar: schemaSelectedCalendarPublic.parse(result) };
|
||||
}
|
||||
|
||||
export default defaultResponder(patchHandler);
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
import authMiddleware from "./_auth-middleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await authMiddleware(req);
|
||||
return defaultHandler({
|
||||
GET: import("./_get"),
|
||||
PATCH: import("./_patch"),
|
||||
DELETE: import("./_delete"),
|
||||
})(req, res);
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaSelectedCalendarPublic } from "~/lib/validations/selected-calendar";
|
||||
import { schemaQuerySingleOrMultipleUserIds } from "~/lib/validations/shared/queryUserId";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /selected-calendars:
|
||||
* get:
|
||||
* operationId: listSelectedCalendars
|
||||
* summary: Find all selected calendars
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* tags:
|
||||
* - selected-calendars
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: No selected calendars were found
|
||||
*/
|
||||
async function getHandler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
/* Admin gets all selected calendar by default, otherwise only the user's ones */
|
||||
const args: Prisma.SelectedCalendarFindManyArgs = isAdmin ? {} : { where: { userId } };
|
||||
|
||||
/** Only admins can query other users */
|
||||
if (!isAdmin && req.query.userId) throw new HttpError({ statusCode: 403, message: "ADMIN required" });
|
||||
if (isAdmin && req.query.userId) {
|
||||
const query = schemaQuerySingleOrMultipleUserIds.parse(req.query);
|
||||
const userIds = Array.isArray(query.userId) ? query.userId : [query.userId || userId];
|
||||
args.where = { userId: { in: userIds } };
|
||||
if (Array.isArray(query.userId)) args.orderBy = { userId: "asc" };
|
||||
}
|
||||
|
||||
const data = await prisma.selectedCalendar.findMany(args);
|
||||
return { selected_calendars: data.map((v) => schemaSelectedCalendarPublic.parse(v)) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import {
|
||||
schemaSelectedCalendarBodyParams,
|
||||
schemaSelectedCalendarPublic,
|
||||
} from "~/lib/validations/selected-calendar";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /selected-calendars:
|
||||
* post:
|
||||
* summary: Creates a new selected calendar
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* requestBody:
|
||||
* description: Create a new selected calendar
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - integration
|
||||
* - externalId
|
||||
* properties:
|
||||
* integration:
|
||||
* type: string
|
||||
* description: The integration name
|
||||
* externalId:
|
||||
* type: string
|
||||
* description: The external ID of the integration
|
||||
* tags:
|
||||
* - selected-calendars
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, selected calendar created
|
||||
* 400:
|
||||
* description: Bad request. SelectedCalendar body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
async function postHandler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
const { userId: bodyUserId, ...body } = schemaSelectedCalendarBodyParams.parse(req.body);
|
||||
const args: Prisma.SelectedCalendarCreateArgs = { data: { ...body, userId } };
|
||||
|
||||
if (!isAdmin && bodyUserId) throw new HttpError({ statusCode: 403, message: `ADMIN required for userId` });
|
||||
|
||||
if (isAdmin && bodyUserId) {
|
||||
const where: Prisma.UserWhereInput = { id: bodyUserId };
|
||||
await prisma.user.findFirstOrThrow({ where });
|
||||
args.data.userId = bodyUserId;
|
||||
}
|
||||
|
||||
const data = await prisma.selectedCalendar.create(args);
|
||||
|
||||
return {
|
||||
selected_calendar: schemaSelectedCalendarPublic.parse(data),
|
||||
message: "Selected Calendar created successfully",
|
||||
};
|
||||
}
|
||||
|
||||
export default defaultResponder(postHandler);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
GET: import("./_get"),
|
||||
POST: import("./_post"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { schemaQueryTeamId } from "~/lib/validations/shared/queryTeamId";
|
||||
|
||||
async function authMiddleware(req: NextApiRequest) {
|
||||
const { userId, prisma, isAdmin } = req;
|
||||
const { teamId } = schemaQueryTeamId.parse(req.query);
|
||||
/** Admins can skip the ownership verification */
|
||||
if (isAdmin) return;
|
||||
/** Non-members will see a 404 error which may or not be the desired behavior. */
|
||||
await prisma.team.findFirstOrThrow({
|
||||
where: { id: teamId, members: { some: { userId } } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function checkPermissions(
|
||||
req: NextApiRequest,
|
||||
role: Prisma.MembershipWhereInput["role"] = MembershipRole.OWNER
|
||||
) {
|
||||
const { userId, prisma, isAdmin } = req;
|
||||
const { teamId } = schemaQueryTeamId.parse(req.query);
|
||||
const args: Prisma.TeamFindFirstArgs = { where: { id: teamId } };
|
||||
/** If not ADMIN then we check if the actual user belongs to team and matches the required role */
|
||||
if (!isAdmin) args.where = { ...args.where, members: { some: { userId, role } } };
|
||||
const team = await prisma.team.findFirst(args);
|
||||
if (!team) throw new HttpError({ statusCode: 401, message: `Unauthorized: ${role.toString()} required` });
|
||||
return team;
|
||||
}
|
||||
|
||||
export default authMiddleware;
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaQueryTeamId } from "~/lib/validations/shared/queryTeamId";
|
||||
|
||||
import { checkPermissions } from "./_auth-middleware";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /teams/{teamId}:
|
||||
* delete:
|
||||
* operationId: removeTeamById
|
||||
* summary: Remove an existing team
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: teamId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the team to delete
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - teams
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, team removed successfully
|
||||
* 400:
|
||||
* description: Bad request. Team id is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function deleteHandler(req: NextApiRequest) {
|
||||
const { prisma, query } = req;
|
||||
const { teamId } = schemaQueryTeamId.parse(query);
|
||||
await checkPermissions(req);
|
||||
await prisma.team.delete({ where: { id: teamId } });
|
||||
return { message: `Team with id: ${teamId} deleted successfully` };
|
||||
}
|
||||
|
||||
export default defaultResponder(deleteHandler);
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaQueryTeamId } from "~/lib/validations/shared/queryTeamId";
|
||||
import { schemaTeamReadPublic } from "~/lib/validations/team";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /teams/{teamId}:
|
||||
* get:
|
||||
* operationId: getTeamById
|
||||
* summary: Find a team
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: teamId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the team to get
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* tags:
|
||||
* - teams
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: Team was not found
|
||||
*/
|
||||
export async function getHandler(req: NextApiRequest) {
|
||||
const { prisma, isAdmin, userId } = req;
|
||||
const { teamId } = schemaQueryTeamId.parse(req.query);
|
||||
const where: Prisma.TeamWhereInput = { id: teamId };
|
||||
// Non-admins can only query the teams they're part of
|
||||
if (!isAdmin) where.members = { some: { userId } };
|
||||
const data = await prisma.team.findFirstOrThrow({ where });
|
||||
return { team: schemaTeamReadPublic.parse(data) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { purchaseTeamSubscription } from "@calcom/features/ee/teams/lib/payments";
|
||||
import { IS_TEAM_BILLING_ENABLED } from "@calcom/lib/constants";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { schemaQueryTeamId } from "~/lib/validations/shared/queryTeamId";
|
||||
import { schemaTeamReadPublic, schemaTeamUpdateBodyParams } from "~/lib/validations/team";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /teams/{teamId}:
|
||||
* patch:
|
||||
* operationId: editTeamById
|
||||
* summary: Edit an existing team
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: teamId
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID of the team to edit
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Your API key
|
||||
* requestBody:
|
||||
* description: Create a new custom input for an event type
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* name:
|
||||
* type: string
|
||||
* description: Name of the team
|
||||
* slug:
|
||||
* type: string
|
||||
* description: A unique slug that works as path for the team public page
|
||||
* tags:
|
||||
* - teams
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, team edited successfully
|
||||
* 400:
|
||||
* description: Bad request. Team body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function patchHandler(req: NextApiRequest) {
|
||||
const { prisma, body, userId } = req;
|
||||
const data = schemaTeamUpdateBodyParams.parse(body);
|
||||
const { teamId } = schemaQueryTeamId.parse(req.query);
|
||||
/** Only OWNERS and ADMINS can edit teams */
|
||||
const _team = await prisma.team.findFirst({
|
||||
include: { members: true },
|
||||
where: { id: teamId, members: { some: { userId, role: { in: ["OWNER", "ADMIN"] } } } },
|
||||
});
|
||||
if (!_team) throw new HttpError({ statusCode: 401, message: "Unauthorized: OWNER or ADMIN required" });
|
||||
let paymentUrl;
|
||||
if (_team.slug === null && data.slug) {
|
||||
data.metadata = {
|
||||
...(_team.metadata as Prisma.JsonObject),
|
||||
requestedSlug: data.slug,
|
||||
};
|
||||
delete data.slug;
|
||||
if (IS_TEAM_BILLING_ENABLED) {
|
||||
const checkoutSession = await purchaseTeamSubscription({
|
||||
teamId: _team.id,
|
||||
seats: _team.members.length,
|
||||
userId,
|
||||
});
|
||||
if (!checkoutSession.url)
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed retrieving a checkout session URL.",
|
||||
});
|
||||
paymentUrl = checkoutSession.url;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Perhaps there is a better fix for this?
|
||||
const cloneData: typeof data & {
|
||||
metadata: NonNullable<typeof data.metadata> | undefined;
|
||||
} = {
|
||||
...data,
|
||||
metadata: data.metadata === null ? {} : data.metadata || undefined,
|
||||
};
|
||||
const team = await prisma.team.update({ where: { id: teamId }, data: cloneData });
|
||||
const result = {
|
||||
team: schemaTeamReadPublic.parse(team),
|
||||
paymentUrl,
|
||||
};
|
||||
if (!paymentUrl) {
|
||||
delete result.paymentUrl;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export default defaultResponder(patchHandler);
|
||||
@@ -0,0 +1,9 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
GET: import("~/pages/api/availability/_get"),
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
import { z } from "zod";
|
||||
|
||||
import { defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { schemaEventTypeReadPublic } from "~/lib/validations/event-type";
|
||||
|
||||
const querySchema = z.object({
|
||||
teamId: z.coerce.number(),
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /teams/{teamId}/event-types:
|
||||
* get:
|
||||
* summary: Find all event types that belong to teamId
|
||||
* operationId: listEventTypesByTeamId
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: apiKey
|
||||
* schema:
|
||||
* type: string
|
||||
* required: true
|
||||
* description: Your API Key
|
||||
* - in: path
|
||||
* name: teamId
|
||||
* schema:
|
||||
* type: number
|
||||
* required: true
|
||||
* tags:
|
||||
* - event-types
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/core-features/event-types
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: No event types were found
|
||||
*/
|
||||
async function getHandler(req: NextApiRequest) {
|
||||
const { userId, isAdmin, prisma } = req;
|
||||
|
||||
const { teamId } = querySchema.parse(req.query);
|
||||
|
||||
const args: Prisma.EventTypeFindManyArgs = {
|
||||
where: {
|
||||
team: isAdmin
|
||||
? {
|
||||
id: teamId,
|
||||
}
|
||||
: {
|
||||
id: teamId,
|
||||
members: { some: { userId } },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const data = await prisma.eventType.findMany(args);
|
||||
return { event_types: data.map((attendee) => schemaEventTypeReadPublic.parse(attendee)) };
|
||||
}
|
||||
|
||||
export default defaultResponder(getHandler);
|
||||
@@ -0,0 +1,9 @@
|
||||
import { defaultHandler } from "@calcom/lib/server";
|
||||
|
||||
import { withMiddleware } from "~/lib/helpers/withMiddleware";
|
||||
|
||||
export default withMiddleware()(
|
||||
defaultHandler({
|
||||
GET: import("./_get"),
|
||||
})
|
||||
);
|
||||
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user