diff --git a/apps/api/apps/api/.env.example b/apps/api/apps/api/.env.example
new file mode 100644
index 0000000000..c5354bfd7d
--- /dev/null
+++ b/apps/api/apps/api/.env.example
@@ -0,0 +1,6 @@
+API_KEY_PREFIX=cal_
+DATABASE_URL="postgresql://postgres:@localhost:5450/calendso"
+NEXT_PUBLIC_WEBAPP_URL=http://localhost:3000
+
+# Get it in console.cal.com
+CALCOM_LICENSE_KEY=""
diff --git a/apps/api/apps/api/.eslintrc.js b/apps/api/apps/api/.eslintrc.js
new file mode 100644
index 0000000000..0e71ec1eae
--- /dev/null
+++ b/apps/api/apps/api/.eslintrc.js
@@ -0,0 +1 @@
+module.exports = require("@calcom/config/eslint-preset");
diff --git a/apps/api/apps/api/.gitignore b/apps/api/apps/api/.gitignore
new file mode 100644
index 0000000000..a2c49f1abb
--- /dev/null
+++ b/apps/api/apps/api/.gitignore
@@ -0,0 +1,81 @@
+# .env file
+.env
+
+# dependencies
+node_modules
+.pnp
+.pnp.js
+
+# testing
+coverage
+/test-results/
+playwright/videos
+playwright/screenshots
+playwright/artifacts
+playwright/results
+playwright/reports/*
+
+# next.js
+.next/
+out/
+build
+
+# misc
+.DS_Store
+*.pem
+
+# debug
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+.pnpm-debug.log*
+
+# local env files
+.env.local
+.env.development.local
+.env.test.local
+.env.production.local
+.env.*
+!.env.example
+
+# vercel
+.vercel
+
+# Webstorm
+.idea
+
+### VisualStudioCode template
+.vscode/
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+*.code-workspace
+
+# Local History for Visual Studio Code
+.history/
+
+# Typescript
+tsconfig.tsbuildinfo
+
+# turbo
+.turbo
+
+# Prisma-Zod
+packages/prisma/zod/*.ts
+
+# Builds
+dist
+
+# Linting
+lint-results
+
+# Yarn
+yarn-error.log
+
+.turbo
+.next
+.husky
+.vscode
+.env
\ No newline at end of file
diff --git a/apps/api/apps/api/.gitkeep b/apps/api/apps/api/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/apps/api/apps/api/.prettierignore b/apps/api/apps/api/.prettierignore
new file mode 100644
index 0000000000..745ffcee46
--- /dev/null
+++ b/apps/api/apps/api/.prettierignore
@@ -0,0 +1,5 @@
+.next/
+coverage/
+node_modules/
+tests/
+templates/
\ No newline at end of file
diff --git a/apps/api/apps/api/LICENSE b/apps/api/apps/api/LICENSE
new file mode 100644
index 0000000000..fa89efec90
--- /dev/null
+++ b/apps/api/apps/api/LICENSE
@@ -0,0 +1,42 @@
+The Cal.com Enterprise Edition (EE) license (the “EE License”)
+Copyright (c) 2020-present Cal.com, Inc
+
+With regard to the Cal.com Software:
+
+This software and associated documentation files (the "Software") may only be
+used in production, if you (and any entity that you represent) have agreed to,
+and are in compliance with, the Cal.com Subscription Terms available
+at https://cal.com/terms (the “EE Terms”), or other agreements governing
+the use of the Software, as mutually agreed by you and Cal.com, Inc ("Cal.com"),
+and otherwise have a valid Cal.com Enterprise Edition subscription ("EE Subscription")
+for the correct number of hosts as defined in the EE Terms ("Hosts"). Subject to the foregoing sentence,
+you are free to modify this Software and publish patches to the Software. You agree
+that Cal.com and/or its licensors (as applicable) retain all right, title and interest in
+and to all such modifications and/or patches, and all such modifications and/or
+patches may only be used, copied, modified, displayed, distributed, or otherwise
+exploited with a valid EE Subscription for the correct number of hosts.
+Notwithstanding the foregoing, you may copy and modify the Software for development
+and testing purposes, without requiring a subscription. You agree that Cal.com and/or
+its licensors (as applicable) retain all right, title and interest in and to all such
+modifications. You are not granted any other rights beyond what is expressly stated herein.
+Subject to the foregoing, it is forbidden to copy, merge, publish, distribute, sublicense,
+and/or sell the Software.
+
+This EE License applies only to the part of this Software that is not distributed under
+the AGPLv3 license. Any part of this Software distributed under the MIT license or which
+is served client-side as an image, font, cascading stylesheet (CSS), file which produces
+or is compiled, arranged, augmented, or combined into client-side JavaScript, in whole or
+in part, is copyrighted under the AGPLv3 license. The full text of this EE License shall
+be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+For all third party components incorporated into the Cal.com Software, those
+components are licensed under the original license provided by the owner of the
+applicable component.
\ No newline at end of file
diff --git a/apps/api/apps/api/README.md b/apps/api/apps/api/README.md
new file mode 100644
index 0000000000..c31304595b
--- /dev/null
+++ b/apps/api/apps/api/README.md
@@ -0,0 +1,229 @@
+
+
+
+# Cal.com Public API - Enterprise Edition
+
+Welcome to the Public API Enterprise Edition ("/apps/api") of the Cal.com Public API.
+
+The [/apps/api](https://github.com/calcom/cal.com/tree/main/apps/api) subfolder is the place for our Public API, which we serve at api.cal.com, and enterprise customers can also run [enterprise-grade](https://cal.com/enterprise)
+
+> _❗ WARNING: This repository is copyrighted (unlike our [main repo](https://github.com/calcom/cal.com)). You are not allowed to use this code to host your own version of app.cal.com without obtaining a proper [license](https://cal.com/pricing?infra) first❗_
+
+This is the public REST api for cal.com.
+It exposes CRUD Endpoints of all our most important resources.
+And it makes it easy for anyone to integrate with Cal.com at the application programming level.
+
+## Stack
+
+- NextJS
+- TypeScript
+- Prisma
+
+## Development
+
+### Setup
+
+1. Clone the main repo (NOT THIS ONE)
+
+ ```sh
+ git clone --recurse-submodules -j8 https://github.com/calcom/cal.com.git
+ ```
+
+1. Go to the project folder
+
+ ```sh
+ cd cal.com
+ ```
+
+1. Copy `apps/api/.env.example` to `apps/api/.env`
+
+ ```sh
+ cp apps/api/.env.example apps/api/.env
+ cp .env.example .env
+ ```
+
+1. Install packages with yarn
+
+ ```sh
+ yarn
+ ```
+
+1. Start developing
+
+ ```sh
+ yarn workspace @calcom/api dev
+ ```
+
+1. Open [http://localhost:3002](http://localhost:3002) with your browser to see the result.
+
+## API Authentication (API Keys)
+
+The API requires a valid apiKey query param to be passed:
+You can generate them at
+
+For example:
+
+```sh
+GET https://api.cal.com/v1/users?apiKey={INSERT_YOUR_CAL.COM_API_KEY_HERE}
+```
+
+API Keys optionally may have expiry dates, if they are expired they won't work. If you create an apiKey without a userId relation, it won't work either for now as it relies on it to establish the current authenticated user.
+
+In the future we might add support for header Bearer Auth if we need to or if our customers require it.
+
+## Middlewares
+
+We don't use the new NextJS 12 Beta Middlewares, mainly because they run on the edge, and are not able to call prisma from api endpoints. We use instead a very nifty library called next-api-middleware that let's us use a similar approach building our own middlewares and applying them as we see fit.
+
+- withMiddleware() requires some default middlewares (verifyApiKey, etc...)
+
+## Next.config.js
+
+### Redirects
+
+Since this is an API only project, we don't want to have to type /api/ in all the routes, and so redirect all traffic to api, so a call to `api.cal.com/v1` will resolve to `api.cal.com/api/v1`
+
+Likewise, v1 is added as param query called version to final /api call so we don't duplicate endpoints in the future for versioning if needed.
+
+### Transpiling locally shared monorepo modules
+
+We're calling several packages from monorepo, this need to be transpiled before building since are not available as regular npm packages. That's what withTM does.
+
+```js
+ "@calcom/app-store",
+ "@calcom/prisma",
+ "@calcom/lib",
+ "@calcom/features",
+```
+
+## API Endpoint Validation
+
+We validate that only the supported methods are accepted at each endpoint, so in
+
+- **/endpoint**: you can only [GET] (all) and [POST] (create new)
+- **/endpoint/id**: you can read create and edit [GET, PATCH, DELETE]
+
+### Zod Validations
+
+The API uses `zod` library like our main web repo. It validates that either GET query parameters or POST body content's are valid and up to our spec. It gives errors when parsing result's with schemas and failing validation.
+
+We use it in several ways, but mainly, we first import the auto-generated schema from @calcom/prisma for each model, which lives in `lib/validations/`
+
+We have some shared validations which several resources require, like baseApiParams which parses apiKey in all requests, or querIdAsString or TransformParseInt which deal with the id's coming from req.query.
+
+- **[*]BaseBodyParams** that omits any values from the model that are too sensitive or we don't want to pick when creating a new resource like id, userId, etc.. (those are gotten from context or elswhere)
+
+- **[*]Public** that also omits any values that we don't want to expose when returning the model as a response, which we parse against before returning all resources.
+
+- **[*]BodyParams** which merges both `[*]BaseBodyParams.merge([*]RequiredParams);`
+
+### Next Validations
+
+[Next-Validations Docs](https://next-validations.productsway.com/)
+[Next-Validations Repo](https://github.com/jellydn/next-validations)
+We also use this useful helper library that let us wrap our endpoints in a validate HOC that checks the req against our validation schema built out with zod for either query and / or body's requests.
+
+## Testing with Jest + node-mocks-http
+
+We aim to provide a fully tested API for our peace of mind, this is accomplished by using jest + node-mocks-http
+
+## Endpoints matrix
+
+| resource | get [id] | get all | create | edit | delete |
+| --------------------- | -------- | ------- | ------ | ---- | ------ |
+| attendees | ✅ | ✅ | ✅ | ✅ | ✅ |
+| availabilities | ✅ | ✅ | ✅ | ✅ | ✅ |
+| booking-references | ✅ | ✅ | ✅ | ✅ | ✅ |
+| event-references | ✅ | ✅ | ✅ | ✅ | ✅ |
+| destination-calendars | ✅ | ✅ | ✅ | ✅ | ✅ |
+| custom-inputs | ✅ | ✅ | ✅ | ✅ | ✅ |
+| event-types | ✅ | ✅ | ✅ | ✅ | ✅ |
+| memberships | ✅ | ✅ | ✅ | ✅ | ✅ |
+| payments | ✅ | ✅ | ❌ | ❌ | ❌ |
+| schedules | ✅ | ✅ | ✅ | ✅ | ✅ |
+| selected-calendars | ✅ | ✅ | ✅ | ✅ | ✅ |
+| teams | ✅ | ✅ | ✅ | ✅ | ✅ |
+| users | ✅ | 👤[1] | ✅ | ✅ | ✅ |
+
+## Models from database that are not exposed
+
+mostly because they're deemed too sensitive can be revisited if needed. Also they are expected to be used via cal's webapp.
+
+- [ ] Api Keys
+- [ ] Credentials
+- [ ] Webhooks
+- [ ] ResetPasswordRequest
+- [ ] VerificationToken
+- [ ] ReminderMail
+
+## Documentation (OpenAPI)
+
+You will see that each endpoint has a comment at the top with the annotation `@swagger` with the documentation of the endpoint, **please update it if you change the code!** This is what auto-generates the OpenAPI spec by collecting the YAML in each endpoint and parsing it in /docs alongside the json-schema (auto-generated from prisma package, not added to code but manually for now, need to fix later)
+
+### @calcom/apps/swagger
+
+The documentation of the API lives inside the code, and it's auto-generated, the only endpoints that return without a valid apiKey are the homepage, with a JSON message redirecting you to the docs. and the /docs endpoint, which returns the OpenAPI 3.0 JSON Spec. Which SwaggerUi then consumes and generates the docs on.
+
+## Deployment
+
+`scripts/vercel-deploy.sh`
+The API is deployed to vercel.com, it uses a similar deployment script to website or webapp, and requires transpilation of several shared packages that are part of our turborepo ["app-store", "prisma", "lib", "ee"]
+in order to build and deploy properly.
+
+## Envirorment variables
+
+### Required
+
+DATABASE_URL=DATABASE_URL="postgresql://postgres:@localhost:5450/calendso"
+
+## Optional
+
+API*KEY_PREFIX=cal*# This can be changed per envirorment so cal*test* for staging for example.
+
+> If you're self-hosting under our commercial license, you can use any prefix you want for api keys. either leave the default cal\_ (not providing any envirorment variable) or modify it
+
+**Ensure that while testing swagger, API project should be run in production mode**
+We make sure of this by not using next in dev, but next build && next start, if you want hot module reloading and such when developing, please use yarn run next directly on apps/api.
+
+See . Here in dev mode OPTIONS method is hardcoded to return only GET and OPTIONS as allowed method. Running in Production mode would cause this file to be not used. This is hot-reloading logic only.
+To remove this limitation, we need to ensure that on local endpoints are requested by swagger at /api/v1 and not /v1
+
+## Hosted api through cal.com
+
+> _❗ WARNING: This is still experimental and not fully implemented yet❗_
+
+Go to console.cal.com
+Add a deployment or go to an existing one.
+Activate API or Admin addon
+Provide your `DATABASE_URL`
+Now you can call api.cal.com?key=CALCOM_LICENSE_KEY, which will connect to your own databaseUrl.
+
+## How to deploy
+
+We recommend deploying API in vercel.
+
+There's some settings that you'll need to setup.
+
+Under Vercel > Your API Project > Settings
+
+In General > Build & Development Settings
+BUILD COMMAND: `yarn turbo run build --scope=@calcom/api --include-dependencies --no-deps`
+OUTPUT DIRECTORY: `apps/api/.next`
+
+In Git > Ignored Build Step
+
+Add this command: `./scripts/vercel-deploy.sh`
+
+See `scripts/vercel-deploy.sh` for more info on how the deployment is done.
+
+> _❗ IMORTANT: If you're forking the API repo you will need to update the URLs in both the main repo [`.gitmodules`](https://github.com/calcom/cal.com/blob/main/.gitmodules#L7) and this repo [`./scripts/vercel-deploy.sh`](https://github.com/calcom/api/blob/main/scripts/vercel-deploy.sh#L3) ❗_
+
+## Environment variables
+
+Lastly API requires an env var for `DATABASE_URL` and `CALCOM_LICENSE_KEY`
diff --git a/apps/api/apps/api/jest.setup.ts b/apps/api/apps/api/jest.setup.ts
new file mode 100644
index 0000000000..b764cee58f
--- /dev/null
+++ b/apps/api/apps/api/jest.setup.ts
@@ -0,0 +1,6 @@
+import prisma from "@calcom/prisma";
+
+afterEach((done) => {
+ prisma.$disconnect().then();
+ done();
+});
diff --git a/apps/api/apps/api/lib/constants.ts b/apps/api/apps/api/lib/constants.ts
new file mode 100644
index 0000000000..fb04db4a1c
--- /dev/null
+++ b/apps/api/apps/api/lib/constants.ts
@@ -0,0 +1 @@
+export const PRISMA_CLIENT_CACHING_TIME = 1000 * 60 * 60 * 24; // one day in ms
diff --git a/apps/api/apps/api/lib/helpers/addRequestid.ts b/apps/api/apps/api/lib/helpers/addRequestid.ts
new file mode 100644
index 0000000000..92d2d6919a
--- /dev/null
+++ b/apps/api/apps/api/lib/helpers/addRequestid.ts
@@ -0,0 +1,24 @@
+import { nanoid } from "nanoid";
+import type { NextMiddleware } from "next-api-middleware";
+
+export const addRequestId: NextMiddleware = async (_req, res, next) => {
+ // Apply header with unique ID to every request
+ res.setHeader("Calcom-Response-ID", nanoid());
+ // Add all headers here instead of next.config.js as it is throwing error( Cannot set headers after they are sent to the client) for OPTIONS method
+ // It is known to happen only in Dev Mode.
+ res.setHeader("Access-Control-Allow-Credentials", "true");
+ res.setHeader("Access-Control-Allow-Origin", "*");
+ res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS, PATCH, DELETE, POST, PUT");
+ res.setHeader(
+ "Access-Control-Allow-Headers",
+ "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Content-Type, api_key, Authorization"
+ );
+
+ // Ensure all OPTIONS request are automatically successful. Headers are already set above.
+ if (_req.method === "OPTIONS") {
+ res.status(200).end();
+ return;
+ }
+ // Let remaining middleware and API route execute
+ await next();
+};
diff --git a/apps/api/apps/api/lib/helpers/captureErrors.ts b/apps/api/apps/api/lib/helpers/captureErrors.ts
new file mode 100644
index 0000000000..0d850b052b
--- /dev/null
+++ b/apps/api/apps/api/lib/helpers/captureErrors.ts
@@ -0,0 +1,14 @@
+import * as Sentry from "@sentry/nextjs";
+import type { NextMiddleware } from "next-api-middleware";
+
+export const captureErrors: NextMiddleware = async (_req, res, next) => {
+ try {
+ // Catch any errors that are thrown in remaining
+ // middleware and the API route handler
+ await next();
+ } catch (error) {
+ Sentry.captureException(error);
+ console.log(error);
+ res.status(400).json({ message: "Something went wrong", error });
+ }
+};
diff --git a/apps/api/apps/api/lib/helpers/customPrisma.ts b/apps/api/apps/api/lib/helpers/customPrisma.ts
new file mode 100644
index 0000000000..a30cb6bcb6
--- /dev/null
+++ b/apps/api/apps/api/lib/helpers/customPrisma.ts
@@ -0,0 +1,43 @@
+import { PrismaClient } from "@prisma/client";
+import type { NextMiddleware } from "next-api-middleware";
+
+import { CONSOLE_URL } from "@calcom/lib/constants";
+
+const LOCAL_CONSOLE_URL = process.env.NEXT_PUBLIC_CONSOLE_URL || CONSOLE_URL;
+
+// This replaces the prisma client for the custom one if the key is valid
+export const customPrismaClient: NextMiddleware = async (req, res, next) => {
+ const {
+ query: { key },
+ } = req;
+ // If no custom api Id is provided, attach to request the regular cal.com prisma client.
+ if (!key) {
+ req.prisma = new PrismaClient();
+ await next();
+ return;
+ }
+
+ // If we have a key, we check if the deployment matching the key, has a databaseUrl value set.
+ const databaseUrl = await fetch(`${LOCAL_CONSOLE_URL}/api/deployments/database?key=${key}`)
+ .then((res) => res.json())
+ .then((res) => res.databaseUrl);
+
+ if (!databaseUrl) {
+ res.status(400).json({ error: "no databaseUrl set up at your instance yet" });
+ return;
+ }
+ req.prisma = new PrismaClient({ datasources: { db: { url: databaseUrl } } });
+ /* @note:
+ In order to skip verifyApiKey for customPrisma requests,
+ we pass isAdmin true, and userId 0, if we detect them later,
+ we skip verifyApiKey logic and pass onto next middleware instead.
+ */
+ req.isAdmin = true;
+ req.isCustomPrisma = true;
+ // We don't need the key from here and on. Prevents unrecognized key errors.
+ delete req.query.key;
+ await next();
+ await req.prisma.$disconnect();
+ // @ts-expect-error testing
+ delete req.prisma;
+};
diff --git a/apps/api/apps/api/lib/helpers/extendRequest.ts b/apps/api/apps/api/lib/helpers/extendRequest.ts
new file mode 100644
index 0000000000..d6fff1cbd0
--- /dev/null
+++ b/apps/api/apps/api/lib/helpers/extendRequest.ts
@@ -0,0 +1,9 @@
+import type { NextMiddleware } from "next-api-middleware";
+
+export const extendRequest: NextMiddleware = async (req, res, next) => {
+ req.pagination = {
+ take: 100,
+ skip: 0,
+ };
+ await next();
+};
diff --git a/apps/api/apps/api/lib/helpers/httpMethods.ts b/apps/api/apps/api/lib/helpers/httpMethods.ts
new file mode 100644
index 0000000000..8003a71984
--- /dev/null
+++ b/apps/api/apps/api/lib/helpers/httpMethods.ts
@@ -0,0 +1,32 @@
+import type { NextMiddleware } from "next-api-middleware";
+
+export const httpMethod = (allowedHttpMethod: "GET" | "POST" | "PATCH" | "DELETE"): NextMiddleware => {
+ return async function (req, res, next) {
+ if (req.method === allowedHttpMethod || req.method == "OPTIONS") {
+ await next();
+ } else {
+ res.status(405).json({ message: `Only ${allowedHttpMethod} Method allowed` });
+ res.end();
+ }
+ };
+};
+// Made this so we can support several HTTP Methods in one route and use it there.
+// Could be further extracted into a third function or refactored into one.
+// that checks if it's just a string or an array and apply the correct logic to both cases.
+export const httpMethods = (allowedHttpMethod: string[]): NextMiddleware => {
+ return async function (req, res, next) {
+ if (allowedHttpMethod.some((method) => method === req.method || req.method == "OPTIONS")) {
+ await next();
+ } else {
+ res.status(405).json({ message: `Only ${allowedHttpMethod} Method allowed` });
+ res.end();
+ }
+ };
+};
+
+export const HTTP_POST = httpMethod("POST");
+export const HTTP_GET = httpMethod("GET");
+export const HTTP_PATCH = httpMethod("PATCH");
+export const HTTP_DELETE = httpMethod("DELETE");
+export const HTTP_GET_DELETE_PATCH = httpMethods(["GET", "DELETE", "PATCH"]);
+export const HTTP_GET_OR_POST = httpMethods(["GET", "POST"]);
diff --git a/apps/api/apps/api/lib/helpers/safeParseJSON.ts b/apps/api/apps/api/lib/helpers/safeParseJSON.ts
new file mode 100644
index 0000000000..3681e42273
--- /dev/null
+++ b/apps/api/apps/api/lib/helpers/safeParseJSON.ts
@@ -0,0 +1,14 @@
+export default function parseJSONSafely(str: string) {
+ try {
+ return JSON.parse(str);
+ } catch (e) {
+ console.error((e as Error).message);
+ if ((e as Error).message.includes("Unexpected token")) {
+ return {
+ success: false,
+ message: `Invalid JSON in the body: ${(e as Error).message}`,
+ };
+ }
+ return {};
+ }
+}
diff --git a/apps/api/apps/api/lib/helpers/verifyApiKey.ts b/apps/api/apps/api/lib/helpers/verifyApiKey.ts
new file mode 100644
index 0000000000..45df30e5ef
--- /dev/null
+++ b/apps/api/apps/api/lib/helpers/verifyApiKey.ts
@@ -0,0 +1,47 @@
+import type { NextMiddleware } from "next-api-middleware";
+
+import { hashAPIKey } from "@calcom/features/ee/api-keys/lib/apiKeys";
+import checkLicense from "@calcom/features/ee/common/server/checkLicense";
+
+import { isAdminGuard } from "~/lib/utils/isAdmin";
+
+// Used to check if the apiKey is not expired, could be extracted if reused. but not for now.
+export const dateNotInPast = function (date: Date) {
+ const now = new Date();
+ if (now.setHours(0, 0, 0, 0) > date.setHours(0, 0, 0, 0)) {
+ return true;
+ }
+};
+
+// This verifies the apiKey and sets the user if it is valid.
+export const verifyApiKey: NextMiddleware = async (req, res, next) => {
+ const { prisma, isCustomPrisma, isAdmin } = req;
+ const hasValidLicense = await checkLicense(prisma);
+ if (!hasValidLicense)
+ return res.status(401).json({ error: "Invalid or missing CALCOM_LICENSE_KEY environment variable" });
+ // If the user is an admin and using a license key (from customPrisma), skip the apiKey check.
+ if (isCustomPrisma && isAdmin) {
+ await next();
+ return;
+ }
+ // Check if the apiKey query param is provided.
+ if (!req.query.apiKey) return res.status(401).json({ message: "No apiKey provided" });
+ // remove the prefix from the user provided api_key. If no env set default to "cal_"
+ const strippedApiKey = `${req.query.apiKey}`.replace(process.env.API_KEY_PREFIX || "cal_", "");
+ // Hash the key again before matching against the database records.
+ const hashedKey = hashAPIKey(strippedApiKey);
+ // Check if the hashed api key exists in database.
+ const apiKey = await prisma.apiKey.findUnique({ where: { hashedKey } });
+ // If cannot find any api key. Throw a 401 Unauthorized.
+ if (!apiKey) return res.status(401).json({ error: "Your apiKey is not valid" });
+ if (apiKey.expiresAt && dateNotInPast(apiKey.expiresAt)) {
+ return res.status(401).json({ error: "This apiKey is expired" });
+ }
+ if (!apiKey.userId) return res.status(404).json({ error: "No user found for this apiKey" });
+ // save the user id in the request for later use
+ req.userId = apiKey.userId;
+ // save the isAdmin boolean here for later use
+ req.isAdmin = await isAdminGuard(req);
+ req.isCustomPrisma = false;
+ await next();
+};
diff --git a/apps/api/apps/api/lib/helpers/withMiddleware.ts b/apps/api/apps/api/lib/helpers/withMiddleware.ts
new file mode 100644
index 0000000000..6f7d7927c0
--- /dev/null
+++ b/apps/api/apps/api/lib/helpers/withMiddleware.ts
@@ -0,0 +1,37 @@
+import { label } from "next-api-middleware";
+
+import { addRequestId } from "./addRequestid";
+import { captureErrors } from "./captureErrors";
+import { customPrismaClient } from "./customPrisma";
+import { extendRequest } from "./extendRequest";
+import {
+ HTTP_POST,
+ HTTP_DELETE,
+ HTTP_PATCH,
+ HTTP_GET,
+ HTTP_GET_OR_POST,
+ HTTP_GET_DELETE_PATCH,
+} from "./httpMethods";
+import { verifyApiKey } from "./verifyApiKey";
+import { withPagination } from "./withPagination";
+
+const withMiddleware = label(
+ {
+ HTTP_GET_OR_POST,
+ HTTP_GET_DELETE_PATCH,
+ HTTP_GET,
+ HTTP_PATCH,
+ HTTP_POST,
+ HTTP_DELETE,
+ addRequestId,
+ verifyApiKey,
+ customPrismaClient,
+ extendRequest,
+ pagination: withPagination,
+ sentry: captureErrors,
+ },
+ // The order here, determines the order of execution, put customPrismaClient before verifyApiKey always.
+ ["extendRequest", "sentry", "customPrismaClient", "verifyApiKey", "addRequestId"] // <-- Provide a list of middleware to call automatically
+);
+
+export { withMiddleware };
diff --git a/apps/api/apps/api/lib/helpers/withPagination.ts b/apps/api/apps/api/lib/helpers/withPagination.ts
new file mode 100644
index 0000000000..f29c08829b
--- /dev/null
+++ b/apps/api/apps/api/lib/helpers/withPagination.ts
@@ -0,0 +1,17 @@
+import type { NextMiddleware } from "next-api-middleware";
+import z from "zod";
+
+const withPage = z.object({
+ page: z.coerce.number().min(1).optional().default(1),
+ take: z.coerce.number().min(1).optional().default(10),
+});
+
+export const withPagination: NextMiddleware = async (req, _, next) => {
+ const { page, take } = withPage.parse(req.query);
+ const skip = (page - 1) * take;
+ req.pagination = {
+ take,
+ skip,
+ };
+ await next();
+};
diff --git a/apps/api/apps/api/lib/types.ts b/apps/api/apps/api/lib/types.ts
new file mode 100644
index 0000000000..3022c8c0c8
--- /dev/null
+++ b/apps/api/apps/api/lib/types.ts
@@ -0,0 +1,187 @@
+import type { EventLocationType } from "@calcom/app-store/locations";
+import type {
+ Attendee,
+ Availability,
+ Booking,
+ BookingReference,
+ Credential,
+ DestinationCalendar,
+ EventType,
+ EventTypeCustomInput,
+ Membership,
+ Payment,
+ ReminderMail,
+ Schedule,
+ SelectedCalendar,
+ Team,
+ User,
+ Webhook,
+} from "@calcom/prisma/client";
+
+// Base response, used for all responses
+export type BaseResponse = {
+ message?: string;
+ error?: Error;
+};
+
+// User
+export type UserResponse = BaseResponse & {
+ user?: Partial;
+};
+
+export type UsersResponse = BaseResponse & {
+ users?: Partial[];
+};
+
+// Team
+export type TeamResponse = BaseResponse & {
+ team?: Partial;
+ owner?: Partial;
+};
+export type TeamsResponse = BaseResponse & {
+ teams?: Partial[];
+};
+
+// SelectedCalendar
+export type SelectedCalendarResponse = BaseResponse & {
+ selected_calendar?: Partial;
+};
+export type SelectedCalendarsResponse = BaseResponse & {
+ selected_calendars?: Partial[];
+};
+
+// Attendee
+export type AttendeeResponse = BaseResponse & {
+ attendee?: Partial;
+};
+// Grouping attendees in booking arrays for now,
+// later might remove endpoint and move to booking endpoint altogether.
+export type AttendeesResponse = BaseResponse & {
+ attendees?: Partial[];
+};
+
+// Availability
+export type AvailabilityResponse = BaseResponse & {
+ availability?: Partial;
+};
+export type AvailabilitiesResponse = BaseResponse & {
+ availabilities?: Partial[];
+};
+
+// BookingReference
+export type BookingReferenceResponse = BaseResponse & {
+ booking_reference?: Partial;
+};
+export type BookingReferencesResponse = BaseResponse & {
+ booking_references?: Partial[];
+};
+
+// Booking
+export type BookingResponse = BaseResponse & {
+ booking?: Partial;
+};
+export type BookingsResponse = BaseResponse & {
+ bookings?: Partial[];
+};
+
+// Credential
+export type CredentialResponse = BaseResponse & {
+ credential?: Partial;
+};
+export type CredentialsResponse = BaseResponse & {
+ credentials?: Partial[];
+};
+
+// DestinationCalendar
+export type DestinationCalendarResponse = BaseResponse & {
+ destination_calendar?: Partial;
+};
+export type DestinationCalendarsResponse = BaseResponse & {
+ destination_calendars?: Partial[];
+};
+
+// Membership
+export type MembershipResponse = BaseResponse & {
+ membership?: Partial;
+};
+export type MembershipsResponse = BaseResponse & {
+ memberships?: Partial[];
+};
+
+// EventTypeCustomInput
+export type EventTypeCustomInputResponse = BaseResponse & {
+ event_type_custom_input?: Partial;
+};
+export type EventTypeCustomInputsResponse = BaseResponse & {
+ event_type_custom_inputs?: Partial[];
+};
+// From rrule https://jakubroztocil.github.io/rrule freq
+export enum Frequency {
+ "YEARLY",
+ "MONTHLY",
+ "WEEKLY",
+ "DAILY",
+ "HOURLY",
+ "MINUTELY",
+ "SECONDLY",
+}
+interface EventTypeExtended extends Omit {
+ recurringEvent: {
+ dtstart?: Date | undefined;
+ interval?: number | undefined;
+ count?: number | undefined;
+ freq?: Frequency | undefined;
+ until?: Date | undefined;
+ tzid?: string | undefined;
+ } | null;
+ locations:
+ | {
+ link?: string | undefined;
+ address?: string | undefined;
+ hostPhoneNumber?: string | undefined;
+ type: EventLocationType;
+ }[]
+ | null
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ | any;
+}
+
+// EventType
+export type EventTypeResponse = BaseResponse & {
+ event_type?: Partial;
+};
+export type EventTypesResponse = BaseResponse & {
+ event_types?: Partial[];
+};
+
+// Payment
+export type PaymentResponse = BaseResponse & {
+ payment?: Partial;
+};
+export type PaymentsResponse = BaseResponse & {
+ payments?: Partial[];
+};
+
+// Schedule
+export type ScheduleResponse = BaseResponse & {
+ schedule?: Partial;
+};
+export type SchedulesResponse = BaseResponse & {
+ schedules?: Partial[];
+};
+
+// Webhook
+export type WebhookResponse = BaseResponse & {
+ webhook?: Partial | null;
+};
+export type WebhooksResponse = BaseResponse & {
+ webhooks?: Partial[];
+};
+
+// ReminderMail
+export type ReminderMailResponse = BaseResponse & {
+ reminder_mail?: Partial;
+};
+export type ReminderMailsResponse = BaseResponse & {
+ reminder_mails?: Partial[];
+};
diff --git a/apps/api/apps/api/lib/utils/isAdmin.ts b/apps/api/apps/api/lib/utils/isAdmin.ts
new file mode 100644
index 0000000000..9b9e6f5342
--- /dev/null
+++ b/apps/api/apps/api/lib/utils/isAdmin.ts
@@ -0,0 +1,9 @@
+import type { NextApiRequest } from "next";
+
+import { UserPermissionRole } from "@calcom/prisma/enums";
+
+export const isAdminGuard = async (req: NextApiRequest) => {
+ const { userId, prisma } = req;
+ const user = await prisma.user.findUnique({ where: { id: userId } });
+ return user?.role === UserPermissionRole.ADMIN;
+};
diff --git a/apps/api/apps/api/lib/utils/stringifyISODate.ts b/apps/api/apps/api/lib/utils/stringifyISODate.ts
new file mode 100644
index 0000000000..cf21cd804b
--- /dev/null
+++ b/apps/api/apps/api/lib/utils/stringifyISODate.ts
@@ -0,0 +1,4 @@
+export const stringifyISODate = (date: Date | undefined): string => {
+ return `${date?.toISOString()}`;
+};
+// TODO: create a function that takes an object and returns a stringified version of dates of it.
diff --git a/apps/api/apps/api/lib/validations/api-key.ts b/apps/api/apps/api/lib/validations/api-key.ts
new file mode 100644
index 0000000000..c0afb8eb16
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/api-key.ts
@@ -0,0 +1,29 @@
+import { z } from "zod";
+
+import { _ApiKeyModel as ApiKey } from "@calcom/prisma/zod";
+
+export const apiKeyCreateBodySchema = ApiKey.pick({
+ note: true,
+ expiresAt: true,
+ userId: true,
+})
+ .partial({ userId: true })
+ .merge(z.object({ neverExpires: z.boolean().optional() }))
+ .strict();
+
+export const apiKeyEditBodySchema = ApiKey.pick({
+ note: true,
+})
+ .partial()
+ .strict();
+
+export const apiKeyPublicSchema = ApiKey.pick({
+ id: true,
+ userId: true,
+ note: true,
+ createdAt: true,
+ expiresAt: true,
+ lastUsedAt: true,
+ /** We might never want to expose these. Leaving this a as reminder. */
+ // hashedKey: true,
+});
diff --git a/apps/api/apps/api/lib/validations/attendee.ts b/apps/api/apps/api/lib/validations/attendee.ts
new file mode 100644
index 0000000000..b1be1c2024
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/attendee.ts
@@ -0,0 +1,39 @@
+import { z } from "zod";
+
+import { _AttendeeModel as Attendee } from "@calcom/prisma/zod";
+
+import { timeZone } from "~/lib/validations/shared/timeZone";
+
+export const schemaAttendeeBaseBodyParams = Attendee.pick({
+ bookingId: true,
+ email: true,
+ name: true,
+ timeZone: true,
+});
+
+const schemaAttendeeCreateParams = z
+ .object({
+ bookingId: z.number().int(),
+ email: z.string().email(),
+ name: z.string(),
+ timeZone: timeZone,
+ })
+ .strict();
+
+const schemaAttendeeEditParams = z
+ .object({
+ name: z.string().optional(),
+ email: z.string().email().optional(),
+ timeZone: timeZone.optional(),
+ })
+ .strict();
+export const schemaAttendeeEditBodyParams = schemaAttendeeBaseBodyParams.merge(schemaAttendeeEditParams);
+export const schemaAttendeeCreateBodyParams = schemaAttendeeBaseBodyParams.merge(schemaAttendeeCreateParams);
+
+export const schemaAttendeeReadPublic = Attendee.pick({
+ id: true,
+ bookingId: true,
+ name: true,
+ email: true,
+ timeZone: true,
+});
diff --git a/apps/api/apps/api/lib/validations/availability.ts b/apps/api/apps/api/lib/validations/availability.ts
new file mode 100644
index 0000000000..9d6fd20d1f
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/availability.ts
@@ -0,0 +1,54 @@
+import { z } from "zod";
+
+import { _AvailabilityModel as Availability, _ScheduleModel as Schedule } from "@calcom/prisma/zod";
+import { denullishShape } from "@calcom/prisma/zod-utils";
+
+export const schemaAvailabilityBaseBodyParams = /** We make all these properties required */ denullishShape(
+ Availability.pick({
+ /** We need to pass the schedule where this availability belongs to */
+ scheduleId: true,
+ })
+);
+
+export const schemaAvailabilityReadPublic = Availability.pick({
+ id: true,
+ startTime: true,
+ endTime: true,
+ date: true,
+ scheduleId: true,
+ days: true,
+ // eventTypeId: true /** @deprecated */,
+ // userId: true /** @deprecated */,
+}).merge(z.object({ success: z.boolean().optional(), Schedule: Schedule.partial() }).partial());
+
+const schemaAvailabilityCreateParams = z
+ .object({
+ startTime: z.date().or(z.string()),
+ endTime: z.date().or(z.string()),
+ days: z.array(z.number()).optional(),
+ })
+ .strict();
+
+const schemaAvailabilityEditParams = z
+ .object({
+ startTime: z.date().or(z.string()).optional(),
+ endTime: z.date().or(z.string()).optional(),
+ days: z.array(z.number()).optional(),
+ })
+ .strict();
+
+export const schemaAvailabilityEditBodyParams = schemaAvailabilityEditParams;
+
+export const schemaAvailabilityCreateBodyParams = schemaAvailabilityBaseBodyParams.merge(
+ schemaAvailabilityCreateParams
+);
+
+export const schemaAvailabilityReadBodyParams = z
+ .object({
+ userId: z.union([z.number(), z.array(z.number())]),
+ })
+ .partial();
+
+export const schemaSingleAvailabilityReadBodyParams = z.object({
+ userId: z.number(),
+});
diff --git a/apps/api/apps/api/lib/validations/booking-reference.ts b/apps/api/apps/api/lib/validations/booking-reference.ts
new file mode 100644
index 0000000000..662285b690
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/booking-reference.ts
@@ -0,0 +1,28 @@
+import { _BookingReferenceModel as BookingReference } from "@calcom/prisma/zod";
+import { denullishShape } from "@calcom/prisma/zod-utils";
+
+export const schemaBookingReferenceBaseBodyParams = BookingReference.pick({
+ type: true,
+ bookingId: true,
+ uid: true,
+ meetingId: true,
+ meetingPassword: true,
+ meetingUrl: true,
+ deleted: true,
+}).partial();
+
+export const schemaBookingReferenceReadPublic = BookingReference.pick({
+ id: true,
+ type: true,
+ bookingId: true,
+ uid: true,
+ meetingId: true,
+ meetingPassword: true,
+ meetingUrl: true,
+ deleted: true,
+});
+
+export const schemaBookingCreateBodyParams = BookingReference.omit({ id: true, bookingId: true })
+ .merge(denullishShape(BookingReference.pick({ bookingId: true })))
+ .strict();
+export const schemaBookingEditBodyParams = schemaBookingCreateBodyParams.partial();
diff --git a/apps/api/apps/api/lib/validations/booking.ts b/apps/api/apps/api/lib/validations/booking.ts
new file mode 100644
index 0000000000..53da5396aa
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/booking.ts
@@ -0,0 +1,67 @@
+import { z } from "zod";
+
+import { _BookingModel as Booking, _AttendeeModel, _UserModel } from "@calcom/prisma/zod";
+import { extendedBookingCreateBody, iso8601 } from "@calcom/prisma/zod-utils";
+
+import { schemaQueryUserId } from "./shared/queryUserId";
+
+const schemaBookingBaseBodyParams = Booking.pick({
+ uid: true,
+ userId: true,
+ eventTypeId: true,
+ title: true,
+ description: true,
+ startTime: true,
+ endTime: true,
+ status: true,
+}).partial();
+
+export const schemaBookingCreateBodyParams = extendedBookingCreateBody.merge(schemaQueryUserId.partial());
+
+const schemaBookingEditParams = z
+ .object({
+ title: z.string().optional(),
+ startTime: iso8601.optional(),
+ endTime: iso8601.optional(),
+ // Not supporting responses in edit as that might require re-triggering emails
+ // responses
+ })
+ .strict();
+
+export const schemaBookingEditBodyParams = schemaBookingBaseBodyParams.merge(schemaBookingEditParams);
+
+export const schemaBookingReadPublic = Booking.extend({
+ attendees: z
+ .array(
+ _AttendeeModel.pick({
+ email: true,
+ name: true,
+ timeZone: true,
+ locale: true,
+ })
+ )
+ .optional(),
+ user: _UserModel
+ .pick({
+ email: true,
+ name: true,
+ timeZone: true,
+ locale: true,
+ })
+ .optional(),
+}).pick({
+ id: true,
+ userId: true,
+ description: true,
+ eventTypeId: true,
+ uid: true,
+ title: true,
+ startTime: true,
+ endTime: true,
+ timeZone: true,
+ attendees: true,
+ user: true,
+ metadata: true,
+ status: true,
+ responses: true,
+});
diff --git a/apps/api/apps/api/lib/validations/destination-calendar.ts b/apps/api/apps/api/lib/validations/destination-calendar.ts
new file mode 100644
index 0000000000..7f90cd0002
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/destination-calendar.ts
@@ -0,0 +1,48 @@
+import { z } from "zod";
+
+import { _DestinationCalendarModel as DestinationCalendar } from "@calcom/prisma/zod";
+
+export const schemaDestinationCalendarBaseBodyParams = DestinationCalendar.pick({
+ integration: true,
+ externalId: true,
+ eventTypeId: true,
+ bookingId: true,
+ userId: true,
+}).partial();
+
+const schemaDestinationCalendarCreateParams = z
+ .object({
+ integration: z.string(),
+ externalId: z.string(),
+ eventTypeId: z.number(),
+ bookingId: z.number(),
+ userId: z.number(),
+ })
+ .strict();
+
+export const schemaDestinationCalendarCreateBodyParams = schemaDestinationCalendarBaseBodyParams.merge(
+ schemaDestinationCalendarCreateParams
+);
+
+const schemaDestinationCalendarEditParams = z
+ .object({
+ integration: z.string().optional(),
+ externalId: z.string().optional(),
+ eventTypeId: z.number().optional(),
+ bookingId: z.number().optional(),
+ userId: z.number().optional(),
+ })
+ .strict();
+
+export const schemaDestinationCalendarEditBodyParams = schemaDestinationCalendarBaseBodyParams.merge(
+ schemaDestinationCalendarEditParams
+);
+
+export const schemaDestinationCalendarReadPublic = DestinationCalendar.pick({
+ id: true,
+ integration: true,
+ externalId: true,
+ eventTypeId: true,
+ bookingId: true,
+ userId: true,
+});
diff --git a/apps/api/apps/api/lib/validations/event-type-custom-input.ts b/apps/api/apps/api/lib/validations/event-type-custom-input.ts
new file mode 100644
index 0000000000..8a9fb3dbbe
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/event-type-custom-input.ts
@@ -0,0 +1,13 @@
+import { _EventTypeCustomInputModel as EventTypeCustomInput } from "@calcom/prisma/zod";
+
+export const schemaEventTypeCustomInputBaseBodyParams = EventTypeCustomInput.omit({
+ id: true,
+});
+
+export const schemaEventTypeCustomInputPublic = EventTypeCustomInput.omit({});
+
+export const schemaEventTypeCustomInputBodyParams = schemaEventTypeCustomInputBaseBodyParams.strict();
+
+export const schemaEventTypeCustomInputEditBodyParams = schemaEventTypeCustomInputBaseBodyParams
+ .partial()
+ .strict();
diff --git a/apps/api/apps/api/lib/validations/event-type.ts b/apps/api/apps/api/lib/validations/event-type.ts
new file mode 100644
index 0000000000..2b7768a656
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/event-type.ts
@@ -0,0 +1,139 @@
+import { z } from "zod";
+
+import { _EventTypeModel as EventType, _HostModel } from "@calcom/prisma/zod";
+import { customInputSchema, eventTypeBookingFields } from "@calcom/prisma/zod-utils";
+
+import { Frequency } from "~/lib/types";
+
+import { jsonSchema } from "./shared/jsonSchema";
+import { schemaQueryUserId } from "./shared/queryUserId";
+import { timeZone } from "./shared/timeZone";
+
+const recurringEventInputSchema = z.object({
+ dtstart: z.string().optional(),
+ interval: z.number().int().optional(),
+ count: z.number().int().optional(),
+ freq: z.nativeEnum(Frequency).optional(),
+ until: z.string().optional(),
+ tzid: timeZone.optional(),
+});
+
+const hostSchema = _HostModel.pick({
+ isFixed: true,
+ userId: true,
+});
+
+export const schemaEventTypeBaseBodyParams = EventType.pick({
+ title: true,
+ description: true,
+ slug: true,
+ length: true,
+ hidden: true,
+ position: true,
+ eventName: true,
+ timeZone: true,
+ periodType: true,
+ periodStartDate: true,
+ schedulingType: true,
+ periodEndDate: true,
+ periodDays: true,
+ periodCountCalendarDays: true,
+ requiresConfirmation: true,
+ disableGuests: true,
+ hideCalendarNotes: true,
+ minimumBookingNotice: true,
+ beforeEventBuffer: true,
+ afterEventBuffer: true,
+ teamId: true,
+ price: true,
+ currency: true,
+ slotInterval: true,
+ successRedirectUrl: true,
+ locations: true,
+})
+ .merge(z.object({ hosts: z.array(hostSchema).optional().default([]) }))
+ .partial()
+ .strict();
+
+const schemaEventTypeCreateParams = z
+ .object({
+ title: z.string(),
+ slug: z.string(),
+ description: z.string().optional().nullable(),
+ length: z.number().int(),
+ metadata: z.any().optional(),
+ recurringEvent: recurringEventInputSchema.optional(),
+ seatsPerTimeSlot: z.number().optional(),
+ seatsShowAttendees: z.boolean().optional(),
+ bookingFields: eventTypeBookingFields.optional(),
+ })
+ .strict();
+
+export const schemaEventTypeCreateBodyParams = schemaEventTypeBaseBodyParams
+ .merge(schemaEventTypeCreateParams)
+ .merge(schemaQueryUserId.partial());
+
+const schemaEventTypeEditParams = z
+ .object({
+ title: z.string().optional(),
+ slug: z.string().optional(),
+ length: z.number().int().optional(),
+ seatsPerTimeSlot: z.number().optional(),
+ seatsShowAttendees: z.boolean().optional(),
+ bookingFields: eventTypeBookingFields.optional(),
+ })
+ .strict();
+
+export const schemaEventTypeEditBodyParams = schemaEventTypeBaseBodyParams.merge(schemaEventTypeEditParams);
+export const schemaEventTypeReadPublic = EventType.pick({
+ id: true,
+ title: true,
+ slug: true,
+ length: true,
+ hidden: true,
+ position: true,
+ userId: true,
+ teamId: true,
+ eventName: true,
+ timeZone: true,
+ periodType: true,
+ periodStartDate: true,
+ periodEndDate: true,
+ periodDays: true,
+ periodCountCalendarDays: true,
+ requiresConfirmation: true,
+ recurringEvent: true,
+ disableGuests: true,
+ hideCalendarNotes: true,
+ minimumBookingNotice: true,
+ beforeEventBuffer: true,
+ afterEventBuffer: true,
+ schedulingType: true,
+ price: true,
+ currency: true,
+ slotInterval: true,
+ successRedirectUrl: true,
+ description: true,
+ locations: true,
+ metadata: true,
+ seatsPerTimeSlot: true,
+ seatsShowAttendees: true,
+ bookingFields: true,
+}).merge(
+ z.object({
+ locations: z
+ .array(
+ z.object({
+ link: z.string().optional(),
+ address: z.string().optional(),
+ hostPhoneNumber: z.string().optional(),
+ type: z.any().optional(),
+ })
+ )
+ .nullable(),
+ metadata: jsonSchema.nullable(),
+ customInputs: customInputSchema.array().optional(),
+ link: z.string().optional(),
+ bookingFields: eventTypeBookingFields.optional().nullable(),
+ })
+);
diff --git a/apps/api/apps/api/lib/validations/membership.ts b/apps/api/apps/api/lib/validations/membership.ts
new file mode 100644
index 0000000000..24740eaa52
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/membership.ts
@@ -0,0 +1,65 @@
+import { z } from "zod";
+
+import { MembershipRole } from "@calcom/prisma/enums";
+import { _MembershipModel as Membership, _TeamModel } from "@calcom/prisma/zod";
+import { stringOrNumber } from "@calcom/prisma/zod-utils";
+
+import { schemaQueryIdAsString } from "~/lib/validations/shared/queryIdString";
+import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
+
+export const schemaMembershipBaseBodyParams = Membership.omit({});
+
+const schemaMembershipRequiredParams = z.object({
+ teamId: z.number(),
+});
+
+export const membershipCreateBodySchema = Membership.partial({
+ accepted: true,
+ role: true,
+ disableImpersonation: true,
+}).transform((v) => ({
+ accepted: false,
+ role: MembershipRole.MEMBER,
+ disableImpersonation: false,
+ ...v,
+}));
+
+export const membershipEditBodySchema = Membership.omit({
+ /** To avoid complication, let's avoid updating these, instead you can delete and create a new invite */
+ teamId: true,
+ userId: true,
+})
+ .partial({
+ accepted: true,
+ role: true,
+ disableImpersonation: true,
+ })
+ .strict();
+
+export const schemaMembershipBodyParams = schemaMembershipBaseBodyParams.merge(
+ schemaMembershipRequiredParams
+);
+
+export const schemaMembershipPublic = Membership.merge(z.object({ team: _TeamModel }).partial());
+
+/** We extract userId and teamId from compound ID string */
+export const membershipIdSchema = schemaQueryIdAsString
+ // So we can query additional team data in memberships
+ .merge(z.object({ teamId: z.union([stringOrNumber, z.array(stringOrNumber)]) }).partial())
+ .transform((v, ctx) => {
+ const [userIdStr, teamIdStr] = v.id.split("_");
+ const userIdInt = schemaQueryIdParseInt.safeParse({ id: userIdStr });
+ const teamIdInt = schemaQueryIdParseInt.safeParse({ id: teamIdStr });
+ if (!userIdInt.success) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "userId is not a number" });
+ return z.NEVER;
+ }
+ if (!teamIdInt.success) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "teamId is not a number " });
+ return z.NEVER;
+ }
+ return {
+ userId: userIdInt.data.id,
+ teamId: teamIdInt.data.id,
+ };
+ });
diff --git a/apps/api/apps/api/lib/validations/payment.ts b/apps/api/apps/api/lib/validations/payment.ts
new file mode 100644
index 0000000000..32c5d8d641
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/payment.ts
@@ -0,0 +1,5 @@
+import { _PaymentModel as Payment } from "@calcom/prisma/zod";
+
+// FIXME: Payment seems a delicate endpoint, do we need to remove anything here?
+export const schemaPaymentBodyParams = Payment.omit({ id: true });
+export const schemaPaymentPublic = Payment.omit({ externalId: true });
diff --git a/apps/api/apps/api/lib/validations/reminder-mail.ts b/apps/api/apps/api/lib/validations/reminder-mail.ts
new file mode 100644
index 0000000000..635dc84dac
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/reminder-mail.ts
@@ -0,0 +1,17 @@
+import { z } from "zod";
+
+import { _ReminderMailModel as ReminderMail } from "@calcom/prisma/zod";
+
+export const schemaReminderMailBaseBodyParams = ReminderMail.omit({ id: true }).partial();
+
+export const schemaReminderMailPublic = ReminderMail.omit({});
+
+const schemaReminderMailRequiredParams = z.object({
+ referenceId: z.number().int(),
+ reminderType: z.enum(["PENDING_BOOKING_CONFIRMATION"]),
+ elapsedMinutes: z.number().int(),
+});
+
+export const schemaReminderMailBodyParams = schemaReminderMailBaseBodyParams.merge(
+ schemaReminderMailRequiredParams
+);
diff --git a/apps/api/apps/api/lib/validations/schedule.ts b/apps/api/apps/api/lib/validations/schedule.ts
new file mode 100644
index 0000000000..51a3fbe1af
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/schedule.ts
@@ -0,0 +1,34 @@
+import { z } from "zod";
+
+import dayjs from "@calcom/dayjs";
+import { _ScheduleModel as Schedule, _AvailabilityModel as Availability } from "@calcom/prisma/zod";
+
+import { timeZone } from "./shared/timeZone";
+
+const schemaScheduleBaseBodyParams = Schedule.omit({ id: true, timeZone: true }).partial();
+
+export const schemaSingleScheduleBodyParams = schemaScheduleBaseBodyParams.merge(
+ z.object({ userId: z.number().optional(), timeZone: timeZone.optional() })
+);
+
+export const schemaCreateScheduleBodyParams = schemaScheduleBaseBodyParams.merge(
+ z.object({ userId: z.number().optional(), name: z.string(), timeZone })
+);
+
+export const schemaSchedulePublic = z
+ .object({ id: z.number() })
+ .merge(Schedule)
+ .merge(
+ z.object({
+ availability: z
+ .array(Availability.pick({ id: true, eventTypeId: true, days: true, startTime: true, endTime: true }))
+ .transform((v) =>
+ v.map((item) => ({
+ ...item,
+ startTime: dayjs.utc(item.startTime).format("HH:mm:ss"),
+ endTime: dayjs.utc(item.endTime).format("HH:mm:ss"),
+ }))
+ )
+ .optional(),
+ })
+ );
diff --git a/apps/api/apps/api/lib/validations/selected-calendar.ts b/apps/api/apps/api/lib/validations/selected-calendar.ts
new file mode 100644
index 0000000000..e1b2138e51
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/selected-calendar.ts
@@ -0,0 +1,48 @@
+import z from "zod";
+
+import { _SelectedCalendarModel as SelectedCalendar } from "@calcom/prisma/zod";
+
+import { schemaQueryIdAsString } from "./shared/queryIdString";
+import { schemaQueryIdParseInt } from "./shared/queryIdTransformParseInt";
+
+export const schemaSelectedCalendarBaseBodyParams = SelectedCalendar;
+
+export const schemaSelectedCalendarPublic = SelectedCalendar.omit({});
+
+export const schemaSelectedCalendarBodyParams = schemaSelectedCalendarBaseBodyParams.partial({
+ userId: true,
+});
+
+export const schemaSelectedCalendarUpdateBodyParams = schemaSelectedCalendarBaseBodyParams.partial();
+
+export const selectedCalendarIdSchema = schemaQueryIdAsString.transform((v, ctx) => {
+ /** We can assume the first part is the userId since it's an integer */
+ const [userIdStr, ...rest] = v.id.split("_");
+ /** We can assume that the remainder is both the integration type and external id combined */
+ const integration_externalId = rest.join("_");
+ /**
+ * Since we only handle calendars here we can split by `_calendar_` and re add it later on.
+ * This handle special cases like `google_calendar_c_blabla@group.calendar.google.com` and
+ * `hubspot_other_calendar`.
+ **/
+ const [_integration, externalId] = integration_externalId.split("_calendar_");
+ const userIdInt = schemaQueryIdParseInt.safeParse({ id: userIdStr });
+ if (!userIdInt.success) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "userId is not a number" });
+ return z.NEVER;
+ }
+ if (!_integration) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Missing integration" });
+ return z.NEVER;
+ }
+ if (!externalId) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Missing externalId" });
+ return z.NEVER;
+ }
+ return {
+ userId: userIdInt.data.id,
+ /** We re-add the split `_calendar` string */
+ integration: `${_integration}_calendar`,
+ externalId,
+ };
+});
diff --git a/apps/api/apps/api/lib/validations/shared/baseApiParams.ts b/apps/api/apps/api/lib/validations/shared/baseApiParams.ts
new file mode 100644
index 0000000000..d0482d0d27
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/shared/baseApiParams.ts
@@ -0,0 +1,11 @@
+import { z } from "zod";
+
+// Extracted out as utility function so can be reused
+// at different endpoints that require this validation.
+export const baseApiParams = z.object({
+ // since we added apiKey as query param this is required by next-validations helper
+ // for query params to work properly and not fail.
+ apiKey: z.string().optional(),
+ // version required for supporting /v1/ redirect to query in api as *?version=1
+ version: z.string().optional(),
+});
diff --git a/apps/api/apps/api/lib/validations/shared/jsonSchema.ts b/apps/api/apps/api/lib/validations/shared/jsonSchema.ts
new file mode 100644
index 0000000000..bfc7ae1f2b
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/shared/jsonSchema.ts
@@ -0,0 +1,9 @@
+import { z } from "zod";
+
+// Helper schema for JSON fields
+type Literal = boolean | number | string;
+type Json = Literal | { [key: string]: Json } | Json[];
+const literalSchema = z.union([z.string(), z.number(), z.boolean()]);
+export const jsonSchema: z.ZodSchema = z.lazy(() =>
+ z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)])
+);
diff --git a/apps/api/apps/api/lib/validations/shared/queryIdString.ts b/apps/api/apps/api/lib/validations/shared/queryIdString.ts
new file mode 100644
index 0000000000..97bdfa4b15
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/shared/queryIdString.ts
@@ -0,0 +1,19 @@
+import { withValidation } from "next-validations";
+import { z } from "zod";
+
+import { baseApiParams } from "./baseApiParams";
+
+// Extracted out as utility function so can be reused
+// at different endpoints that require this validation.
+/** Used for UUID style id queries */
+export const schemaQueryIdAsString = baseApiParams
+ .extend({
+ id: z.string(),
+ })
+ .strict();
+
+export const withValidQueryIdString = withValidation({
+ schema: schemaQueryIdAsString,
+ type: "Zod",
+ mode: "query",
+});
diff --git a/apps/api/apps/api/lib/validations/shared/queryIdTransformParseInt.ts b/apps/api/apps/api/lib/validations/shared/queryIdTransformParseInt.ts
new file mode 100644
index 0000000000..b9ec495f47
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/shared/queryIdTransformParseInt.ts
@@ -0,0 +1,16 @@
+import { withValidation } from "next-validations";
+import { z } from "zod";
+
+import { baseApiParams } from "./baseApiParams";
+
+// Extracted out as utility function so can be reused
+// at different endpoints that require this validation.
+export const schemaQueryIdParseInt = baseApiParams.extend({
+ id: z.coerce.number(),
+});
+
+export const withValidQueryIdTransformParseInt = withValidation({
+ schema: schemaQueryIdParseInt,
+ type: "Zod",
+ mode: "query",
+});
diff --git a/apps/api/apps/api/lib/validations/shared/queryTeamId.ts b/apps/api/apps/api/lib/validations/shared/queryTeamId.ts
new file mode 100644
index 0000000000..f2a80361eb
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/shared/queryTeamId.ts
@@ -0,0 +1,21 @@
+import { withValidation } from "next-validations";
+import { z } from "zod";
+
+import { baseApiParams } from "./baseApiParams";
+
+// Extracted out as utility function so can be reused
+// at different endpoints that require this validation.
+export const schemaQueryTeamId = baseApiParams
+ .extend({
+ teamId: z
+ .string()
+ .regex(/^\d+$/)
+ .transform((id) => parseInt(id)),
+ })
+ .strict();
+
+export const withValidQueryTeamId = withValidation({
+ schema: schemaQueryTeamId,
+ type: "Zod",
+ mode: "query",
+});
diff --git a/apps/api/apps/api/lib/validations/shared/queryUserId.ts b/apps/api/apps/api/lib/validations/shared/queryUserId.ts
new file mode 100644
index 0000000000..f187d0f134
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/shared/queryUserId.ts
@@ -0,0 +1,26 @@
+import { withValidation } from "next-validations";
+import { z } from "zod";
+
+import { stringOrNumber } from "@calcom/prisma/zod-utils";
+
+import { baseApiParams } from "./baseApiParams";
+
+// Extracted out as utility function so can be reused
+// at different endpoints that require this validation.
+export const schemaQueryUserId = baseApiParams.extend({
+ userId: stringOrNumber,
+});
+
+export const schemaQuerySingleOrMultipleUserIds = z.object({
+ userId: z.union([stringOrNumber, z.array(stringOrNumber)]),
+});
+
+export const schemaQuerySingleOrMultipleTeamIds = z.object({
+ teamId: z.union([stringOrNumber, z.array(stringOrNumber)]),
+});
+
+export const withValidQueryUserId = withValidation({
+ schema: schemaQueryUserId,
+ type: "Zod",
+ mode: "query",
+});
diff --git a/apps/api/apps/api/lib/validations/shared/timeZone.ts b/apps/api/apps/api/lib/validations/shared/timeZone.ts
new file mode 100644
index 0000000000..e94b0afa09
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/shared/timeZone.ts
@@ -0,0 +1,7 @@
+import tzdata from "tzdata";
+import * as z from "zod";
+
+// @note: This is a custom validation that checks if the timezone is valid and exists in the tzdb library
+export const timeZone = z.string().refine((tz: string) => Object.keys(tzdata.zones).includes(tz), {
+ message: `Expected one of the following: ${Object.keys(tzdata.zones).join(", ")}`,
+});
diff --git a/apps/api/apps/api/lib/validations/team.ts b/apps/api/apps/api/lib/validations/team.ts
new file mode 100644
index 0000000000..e5f8e3cbfa
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/team.ts
@@ -0,0 +1,18 @@
+import { z } from "zod";
+
+import { _TeamModel as Team } from "@calcom/prisma/zod";
+
+export const schemaTeamBaseBodyParams = Team.omit({ id: true, createdAt: true }).partial({
+ hideBranding: true,
+ metadata: true,
+});
+
+const schemaTeamRequiredParams = z.object({});
+
+export const schemaTeamBodyParams = schemaTeamBaseBodyParams.merge(schemaTeamRequiredParams).strict();
+
+export const schemaTeamUpdateBodyParams = schemaTeamBodyParams.partial();
+
+export const schemaTeamReadPublic = Team.omit({});
+
+export const schemaTeamsReadPublic = z.array(schemaTeamReadPublic);
diff --git a/apps/api/apps/api/lib/validations/user.ts b/apps/api/apps/api/lib/validations/user.ts
new file mode 100644
index 0000000000..25810f27c6
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/user.ts
@@ -0,0 +1,170 @@
+import { z } from "zod";
+
+import { checkUsername } from "@calcom/lib/server/checkUsername";
+import { _UserModel as User } from "@calcom/prisma/zod";
+import { iso8601 } from "@calcom/prisma/zod-utils";
+
+import { timeZone } from "~/lib/validations/shared/timeZone";
+
+// @note: These are the ONLY values allowed as weekStart. So user don't introduce bad data.
+enum weekdays {
+ MONDAY = "Monday",
+ TUESDAY = "Tuesday",
+ WEDNESDAY = "Wednesday",
+ THURSDAY = "Thursday",
+ FRIDAY = "Friday",
+ SATURDAY = "Saturday",
+ SUNDAY = "Sunday",
+}
+
+// @note: extracted from apps/web/next-i18next.config.js, update if new locales.
+enum locales {
+ EN = "en",
+ FR = "fr",
+ IT = "it",
+ RU = "ru",
+ ES = "es",
+ DE = "de",
+ PT = "pt",
+ RO = "ro",
+ NL = "nl",
+ PT_BR = "pt-BR",
+ ES_419 = "es-419",
+ KO = "ko",
+ JA = "ja",
+ PL = "pl",
+ AR = "ar",
+ IW = "iw",
+ ZH_CN = "zh-CN",
+ ZH_TW = "zh-TW",
+ CS = "cs",
+ SR = "sr",
+ SV = "sv",
+ VI = "vi",
+}
+enum theme {
+ DARK = "dark",
+ LIGHT = "light",
+}
+
+enum timeFormat {
+ TWELVE = 12,
+ TWENTY_FOUR = 24,
+}
+
+const usernameSchema = z
+ .string()
+ .transform((v) => v.toLowerCase())
+ // .refine(() => {})
+ .superRefine(async (val, ctx) => {
+ if (val) {
+ const result = await checkUsername(val);
+ if (!result.available) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "already_in_use_error" });
+ if (result.premium) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "premium_username" });
+ }
+ });
+
+// @note: These are the values that are editable via PATCH method on the user Model
+export const schemaUserBaseBodyParams = User.pick({
+ name: true,
+ email: true,
+ username: true,
+ bio: true,
+ timeZone: true,
+ weekStart: true,
+ theme: true,
+ defaultScheduleId: true,
+ locale: true,
+ timeFormat: true,
+ brandColor: true,
+ darkBrandColor: true,
+ allowDynamicBooking: true,
+ away: true,
+ role: true,
+ // @note: disallowing avatar changes via API for now. We can add it later if needed. User should upload image via UI.
+ // avatar: true,
+}).partial();
+// @note: partial() is used to allow for the user to edit only the fields they want to edit making all optional,
+// if want to make any required do it in the schemaRequiredParams
+
+// Here we can both require or not (adding optional or nullish) and also rewrite validations for any value
+// for example making weekStart only accept weekdays as input
+const schemaUserEditParams = z.object({
+ email: z.string().email(),
+ username: usernameSchema,
+ weekStart: z.nativeEnum(weekdays).optional(),
+ brandColor: z.string().min(4).max(9).regex(/^#/).optional(),
+ darkBrandColor: z.string().min(4).max(9).regex(/^#/).optional(),
+ timeZone: timeZone.optional(),
+ theme: z.nativeEnum(theme).optional().nullable(),
+ timeFormat: z.nativeEnum(timeFormat).optional(),
+ defaultScheduleId: z
+ .number()
+ .refine((id: number) => id > 0)
+ .optional()
+ .nullable(),
+ locale: z.nativeEnum(locales).optional().nullable(),
+});
+
+// @note: These are the values that are editable via PATCH method on the user Model,
+// merging both BaseBodyParams with RequiredParams, and omiting whatever we want at the end.
+
+const schemaUserCreateParams = z.object({
+ email: z.string().email(),
+ username: usernameSchema,
+ weekStart: z.nativeEnum(weekdays).optional(),
+ brandColor: z.string().min(4).max(9).regex(/^#/).optional(),
+ darkBrandColor: z.string().min(4).max(9).regex(/^#/).optional(),
+ timeZone: timeZone.optional(),
+ theme: z.nativeEnum(theme).optional().nullable(),
+ timeFormat: z.nativeEnum(timeFormat).optional(),
+ defaultScheduleId: z
+ .number()
+ .refine((id: number) => id > 0)
+ .optional()
+ .nullable(),
+ locale: z.nativeEnum(locales).optional(),
+ createdDate: iso8601.optional(),
+});
+
+// @note: These are the values that are editable via PATCH method on the user Model,
+// merging both BaseBodyParams with RequiredParams, and omiting whatever we want at the end.
+export const schemaUserEditBodyParams = schemaUserBaseBodyParams
+ .merge(schemaUserEditParams)
+ .omit({})
+ .partial()
+ .strict();
+
+export const schemaUserCreateBodyParams = schemaUserBaseBodyParams
+ .merge(schemaUserCreateParams)
+ .omit({})
+ .strict();
+
+// @note: These are the values that are always returned when reading a user
+export const schemaUserReadPublic = User.pick({
+ id: true,
+ username: true,
+ name: true,
+ email: true,
+ emailVerified: true,
+ bio: true,
+ avatar: true,
+ timeZone: true,
+ weekStart: true,
+ endTime: true,
+ bufferTime: true,
+ theme: true,
+ defaultScheduleId: true,
+ locale: true,
+ timeFormat: true,
+ brandColor: true,
+ darkBrandColor: true,
+ allowDynamicBooking: true,
+ away: true,
+ createdDate: true,
+ verified: true,
+ invitedTo: true,
+ role: true,
+});
+
+export const schemaUsersReadPublic = z.array(schemaUserReadPublic);
diff --git a/apps/api/apps/api/lib/validations/webhook.ts b/apps/api/apps/api/lib/validations/webhook.ts
new file mode 100644
index 0000000000..91d8560195
--- /dev/null
+++ b/apps/api/apps/api/lib/validations/webhook.ts
@@ -0,0 +1,55 @@
+import { z } from "zod";
+
+import { WEBHOOK_TRIGGER_EVENTS } from "@calcom/features/webhooks/lib/constants";
+import { _WebhookModel as Webhook } from "@calcom/prisma/zod";
+
+const schemaWebhookBaseBodyParams = Webhook.pick({
+ userId: true,
+ eventTypeId: true,
+ eventTriggers: true,
+ active: true,
+ subscriberUrl: true,
+ payloadTemplate: true,
+});
+
+export const schemaWebhookCreateParams = z
+ .object({
+ // subscriberUrl: z.string().url(),
+ // eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array(),
+ // active: z.boolean(),
+ payloadTemplate: z.string().optional().nullable(),
+ eventTypeId: z.number().optional(),
+ userId: z.number().optional(),
+ // API shouldn't mess with Apps webhooks yet (ie. Zapier)
+ // appId: z.string().optional().nullable(),
+ })
+ .strict();
+
+export const schemaWebhookCreateBodyParams = schemaWebhookBaseBodyParams.merge(schemaWebhookCreateParams);
+
+export const schemaWebhookEditBodyParams = schemaWebhookBaseBodyParams
+ .merge(
+ z.object({
+ eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array().optional(),
+ })
+ )
+ .partial()
+ .strict();
+
+export const schemaWebhookReadPublic = Webhook.pick({
+ id: true,
+ userId: true,
+ eventTypeId: true,
+ payloadTemplate: true,
+ eventTriggers: true,
+ // FIXME: We have some invalid urls saved in the DB
+ // subscriberUrl: true,
+ /** @todo: find out how to properly add back and validate those. */
+ // eventType: true,
+ // app: true,
+ appId: true,
+}).merge(
+ z.object({
+ subscriberUrl: z.string(),
+ })
+);
diff --git a/apps/api/apps/api/next-env.d.ts b/apps/api/apps/api/next-env.d.ts
new file mode 100644
index 0000000000..4f11a03dc6
--- /dev/null
+++ b/apps/api/apps/api/next-env.d.ts
@@ -0,0 +1,5 @@
+///
+///
+
+// NOTE: This file should not be edited
+// see https://nextjs.org/docs/basic-features/typescript for more information.
diff --git a/apps/api/apps/api/next-i18next.config.js b/apps/api/apps/api/next-i18next.config.js
new file mode 100644
index 0000000000..402b72363c
--- /dev/null
+++ b/apps/api/apps/api/next-i18next.config.js
@@ -0,0 +1,10 @@
+const path = require("path");
+const i18nConfig = require("@calcom/config/next-i18next.config");
+
+/** @type {import("next-i18next").UserConfig} */
+const config = {
+ ...i18nConfig,
+ localePath: path.resolve("../web/public/static/locales"),
+};
+
+module.exports = config;
diff --git a/apps/api/apps/api/next.config.js b/apps/api/apps/api/next.config.js
new file mode 100644
index 0000000000..ba2dcbf89b
--- /dev/null
+++ b/apps/api/apps/api/next.config.js
@@ -0,0 +1,69 @@
+const { withAxiom } = require("next-axiom");
+
+module.exports = withAxiom({
+ transpilePackages: [
+ "@calcom/app-store",
+ "@calcom/core",
+ "@calcom/dayjs",
+ "@calcom/emails",
+ "@calcom/features",
+ "@calcom/lib",
+ "@calcom/prisma",
+ "@calcom/trpc",
+ ],
+ async headers() {
+ return [
+ {
+ source: "/docs",
+ headers: [
+ {
+ key: "Access-Control-Allow-Credentials",
+ value: "true",
+ },
+ {
+ key: "Access-Control-Allow-Origin",
+ value: "*",
+ },
+ {
+ key: "Access-Control-Allow-Methods",
+ value: "GET, OPTIONS, PATCH, DELETE, POST, PUT",
+ },
+ {
+ key: "Access-Control-Allow-Headers",
+ value:
+ "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Content-Type, api_key, Authorization",
+ },
+ ],
+ },
+ ];
+ },
+ async rewrites() {
+ return {
+ afterFiles: [
+ // This redirects requests recieved at / the root to the /api/ folder.
+ {
+ source: "/v:version/:rest*",
+ destination: "/api/v:version/:rest*",
+ },
+ // This redirects requests to api/v*/ to /api/ passing version as a query parameter.
+ {
+ source: "/api/v:version/:rest*",
+ destination: "/api/:rest*?version=:version",
+ },
+ // Keeps backwards compatibility with old webhook URLs
+ {
+ source: "/api/hooks/:rest*",
+ destination: "/api/webhooks/:rest*",
+ },
+ ],
+ fallback: [
+ // These rewrites are checked after both pages/public files
+ // and dynamic routes are checked
+ {
+ source: "/:path*",
+ destination: `/api/:path*`,
+ },
+ ],
+ };
+ },
+});
diff --git a/apps/api/apps/api/next.d.ts b/apps/api/apps/api/next.d.ts
new file mode 100644
index 0000000000..7d5f82441a
--- /dev/null
+++ b/apps/api/apps/api/next.d.ts
@@ -0,0 +1,21 @@
+import type { Session } from "next-auth";
+import type { NextApiRequest as BaseNextApiRequest } from "next/types";
+
+import type { PrismaClient } from "@calcom/prisma/client";
+
+export type * from "next/types";
+
+export declare module "next" {
+ interface NextApiRequest extends BaseNextApiRequest {
+ session?: Session | null;
+
+ userId: number;
+ method: string;
+ prisma: PrismaClient;
+ // session: { user: { id: number } };
+ // query: Partial<{ [key: string]: string | string[] }>;
+ isAdmin: boolean;
+ isCustomPrisma: boolean;
+ pagination: { take: number; skip: number };
+ }
+}
diff --git a/apps/api/apps/api/package.json b/apps/api/apps/api/package.json
new file mode 100644
index 0000000000..fea62daa18
--- /dev/null
+++ b/apps/api/apps/api/package.json
@@ -0,0 +1,49 @@
+{
+ "name": "@calcom/api",
+ "version": "1.0.0",
+ "description": "Public API for Cal.com",
+ "main": "index.ts",
+ "repository": "git@github.com:calcom/api.git",
+ "author": "Cal.com Inc.",
+ "private": true,
+ "scripts": {
+ "build": "next build",
+ "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf .next",
+ "dev": "PORT=3002 next dev",
+ "lint": "eslint . --ignore-path .gitignore",
+ "lint:report": "eslint . --format json --output-file ../../lint-results/api.json",
+ "lint:fix": "eslint . --ext .ts,.js,.tsx,.jsx --fix",
+ "start": "PORT=3002 next start",
+ "test": "jest --detectOpenHandles --passWithNoTests",
+ "type-check": "tsc --pretty --noEmit"
+ },
+ "devDependencies": {
+ "@calcom/tsconfig": "*",
+ "@calcom/types": "*",
+ "babel-jest": "^28.1.0",
+ "jest": "^28.1.0",
+ "node-mocks-http": "^1.11.0"
+ },
+ "dependencies": {
+ "@calcom/app-store": "*",
+ "@calcom/core": "*",
+ "@calcom/dayjs": "*",
+ "@calcom/emails": "*",
+ "@calcom/features": "*",
+ "@calcom/lib": "*",
+ "@calcom/prisma": "*",
+ "@calcom/trpc": "*",
+ "@sentry/nextjs": "^7.20.0",
+ "bcryptjs": "^2.4.3",
+ "memory-cache": "^0.2.0",
+ "next": "~13.2.1",
+ "next-api-middleware": "^1.0.1",
+ "next-axiom": "^0.16.0",
+ "next-swagger-doc": "^0.3.6",
+ "next-validations": "^0.2.0",
+ "typescript": "^4.9.4",
+ "tzdata": "^1.0.30",
+ "uuid": "^8.3.2",
+ "zod": "^3.20.2"
+ }
+}
diff --git a/apps/api/apps/api/pages/api/api-keys/[id]/_auth-middleware.ts b/apps/api/apps/api/pages/api/api-keys/[id]/_auth-middleware.ts
new file mode 100644
index 0000000000..fb1c917485
--- /dev/null
+++ b/apps/api/apps/api/pages/api/api-keys/[id]/_auth-middleware.ts
@@ -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" });
+}
diff --git a/apps/api/apps/api/pages/api/api-keys/[id]/_delete.ts b/apps/api/apps/api/pages/api/api-keys/[id]/_delete.ts
new file mode 100644
index 0000000000..099c6ba7b1
--- /dev/null
+++ b/apps/api/apps/api/pages/api/api-keys/[id]/_delete.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/api-keys/[id]/_get.ts b/apps/api/apps/api/pages/api/api-keys/[id]/_get.ts
new file mode 100644
index 0000000000..99b1188507
--- /dev/null
+++ b/apps/api/apps/api/pages/api/api-keys/[id]/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/api-keys/[id]/_patch.ts b/apps/api/apps/api/pages/api/api-keys/[id]/_patch.ts
new file mode 100644
index 0000000000..673a081f54
--- /dev/null
+++ b/apps/api/apps/api/pages/api/api-keys/[id]/_patch.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/api-keys/[id]/index.ts b/apps/api/apps/api/pages/api/api-keys/[id]/index.ts
new file mode 100644
index 0000000000..2e0c358153
--- /dev/null
+++ b/apps/api/apps/api/pages/api/api-keys/[id]/index.ts
@@ -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);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/api-keys/_get.ts b/apps/api/apps/api/pages/api/api-keys/_get.ts
new file mode 100644
index 0000000000..8c23c6fe9e
--- /dev/null
+++ b/apps/api/apps/api/pages/api/api-keys/_get.ts
@@ -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 {
+ 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);
diff --git a/apps/api/apps/api/pages/api/api-keys/_post.ts b/apps/api/apps/api/pages/api/api-keys/_post.ts
new file mode 100644
index 0000000000..8329ac0df5
--- /dev/null
+++ b/apps/api/apps/api/pages/api/api-keys/_post.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/api-keys/index.ts b/apps/api/apps/api/pages/api/api-keys/index.ts
new file mode 100644
index 0000000000..0737e056fb
--- /dev/null
+++ b/apps/api/apps/api/pages/api/api-keys/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/attendees/[id]/_auth-middleware.ts b/apps/api/apps/api/pages/api/attendees/[id]/_auth-middleware.ts
new file mode 100644
index 0000000000..4397583057
--- /dev/null
+++ b/apps/api/apps/api/pages/api/attendees/[id]/_auth-middleware.ts
@@ -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;
diff --git a/apps/api/apps/api/pages/api/attendees/[id]/_delete.ts b/apps/api/apps/api/pages/api/attendees/[id]/_delete.ts
new file mode 100644
index 0000000000..4d0475b864
--- /dev/null
+++ b/apps/api/apps/api/pages/api/attendees/[id]/_delete.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/attendees/[id]/_get.ts b/apps/api/apps/api/pages/api/attendees/[id]/_get.ts
new file mode 100644
index 0000000000..bf1680de29
--- /dev/null
+++ b/apps/api/apps/api/pages/api/attendees/[id]/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/attendees/[id]/_patch.ts b/apps/api/apps/api/pages/api/attendees/[id]/_patch.ts
new file mode 100644
index 0000000000..67269c7197
--- /dev/null
+++ b/apps/api/apps/api/pages/api/attendees/[id]/_patch.ts
@@ -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) {
+ 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);
diff --git a/apps/api/apps/api/pages/api/attendees/[id]/index.ts b/apps/api/apps/api/pages/api/attendees/[id]/index.ts
new file mode 100644
index 0000000000..727ad02843
--- /dev/null
+++ b/apps/api/apps/api/pages/api/attendees/[id]/index.ts
@@ -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);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/attendees/_get.ts b/apps/api/apps/api/pages/api/attendees/_get.ts
new file mode 100644
index 0000000000..d6662d897c
--- /dev/null
+++ b/apps/api/apps/api/pages/api/attendees/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/attendees/_post.ts b/apps/api/apps/api/pages/api/attendees/_post.ts
new file mode 100644
index 0000000000..8570376c55
--- /dev/null
+++ b/apps/api/apps/api/pages/api/attendees/_post.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/attendees/index.ts b/apps/api/apps/api/pages/api/attendees/index.ts
new file mode 100644
index 0000000000..2a15abfa5b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/attendees/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/availabilities/[id]/_auth-middleware.ts b/apps/api/apps/api/pages/api/availabilities/[id]/_auth-middleware.ts
new file mode 100644
index 0000000000..63ad3a3c32
--- /dev/null
+++ b/apps/api/apps/api/pages/api/availabilities/[id]/_auth-middleware.ts
@@ -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;
diff --git a/apps/api/apps/api/pages/api/availabilities/[id]/_delete.ts b/apps/api/apps/api/pages/api/availabilities/[id]/_delete.ts
new file mode 100644
index 0000000000..d480ad4a93
--- /dev/null
+++ b/apps/api/apps/api/pages/api/availabilities/[id]/_delete.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/availabilities/[id]/_get.ts b/apps/api/apps/api/pages/api/availabilities/[id]/_get.ts
new file mode 100644
index 0000000000..a481ac1f89
--- /dev/null
+++ b/apps/api/apps/api/pages/api/availabilities/[id]/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/availabilities/[id]/_patch.ts b/apps/api/apps/api/pages/api/availabilities/[id]/_patch.ts
new file mode 100644
index 0000000000..2b97d01461
--- /dev/null
+++ b/apps/api/apps/api/pages/api/availabilities/[id]/_patch.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/availabilities/[id]/index.ts b/apps/api/apps/api/pages/api/availabilities/[id]/index.ts
new file mode 100644
index 0000000000..727ad02843
--- /dev/null
+++ b/apps/api/apps/api/pages/api/availabilities/[id]/index.ts
@@ -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);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/availabilities/_post.ts b/apps/api/apps/api/pages/api/availabilities/_post.ts
new file mode 100644
index 0000000000..19c76f26cb
--- /dev/null
+++ b/apps/api/apps/api/pages/api/availabilities/_post.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/availabilities/index.ts b/apps/api/apps/api/pages/api/availabilities/index.ts
new file mode 100644
index 0000000000..3ccafb7e55
--- /dev/null
+++ b/apps/api/apps/api/pages/api/availabilities/index.ts
@@ -0,0 +1,9 @@
+import { defaultHandler } from "@calcom/lib/server";
+
+import { withMiddleware } from "~/lib/helpers/withMiddleware";
+
+export default withMiddleware()(
+ defaultHandler({
+ POST: import("./_post"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/availability/_get.ts b/apps/api/apps/api/pages/api/availability/_get.ts
new file mode 100644
index 0000000000..42371e0be7
--- /dev/null
+++ b/apps/api/apps/api/pages/api/availability/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/availability/index.ts b/apps/api/apps/api/pages/api/availability/index.ts
new file mode 100644
index 0000000000..c53e4b8ef3
--- /dev/null
+++ b/apps/api/apps/api/pages/api/availability/index.ts
@@ -0,0 +1,9 @@
+import { defaultHandler } from "@calcom/lib/server";
+
+import { withMiddleware } from "~/lib/helpers/withMiddleware";
+
+export default withMiddleware()(
+ defaultHandler({
+ GET: import("./_get"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/booking-references/[id]/_auth-middleware.ts b/apps/api/apps/api/pages/api/booking-references/[id]/_auth-middleware.ts
new file mode 100644
index 0000000000..fb4d179e61
--- /dev/null
+++ b/apps/api/apps/api/pages/api/booking-references/[id]/_auth-middleware.ts
@@ -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;
diff --git a/apps/api/apps/api/pages/api/booking-references/[id]/_delete.ts b/apps/api/apps/api/pages/api/booking-references/[id]/_delete.ts
new file mode 100644
index 0000000000..23a83ce311
--- /dev/null
+++ b/apps/api/apps/api/pages/api/booking-references/[id]/_delete.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/booking-references/[id]/_get.ts b/apps/api/apps/api/pages/api/booking-references/[id]/_get.ts
new file mode 100644
index 0000000000..6baf71a550
--- /dev/null
+++ b/apps/api/apps/api/pages/api/booking-references/[id]/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/booking-references/[id]/_patch.ts b/apps/api/apps/api/pages/api/booking-references/[id]/_patch.ts
new file mode 100644
index 0000000000..37e17e2e00
--- /dev/null
+++ b/apps/api/apps/api/pages/api/booking-references/[id]/_patch.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/booking-references/[id]/index.ts b/apps/api/apps/api/pages/api/booking-references/[id]/index.ts
new file mode 100644
index 0000000000..727ad02843
--- /dev/null
+++ b/apps/api/apps/api/pages/api/booking-references/[id]/index.ts
@@ -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);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/booking-references/_get.ts b/apps/api/apps/api/pages/api/booking-references/_get.ts
new file mode 100644
index 0000000000..c3b81a4622
--- /dev/null
+++ b/apps/api/apps/api/pages/api/booking-references/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/booking-references/_post.ts b/apps/api/apps/api/pages/api/booking-references/_post.ts
new file mode 100644
index 0000000000..b3b8b713cf
--- /dev/null
+++ b/apps/api/apps/api/pages/api/booking-references/_post.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/booking-references/index.ts b/apps/api/apps/api/pages/api/booking-references/index.ts
new file mode 100644
index 0000000000..2a15abfa5b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/booking-references/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/bookings/[id]/_auth-middleware.ts b/apps/api/apps/api/pages/api/bookings/[id]/_auth-middleware.ts
new file mode 100644
index 0000000000..c785ccc3be
--- /dev/null
+++ b/apps/api/apps/api/pages/api/bookings/[id]/_auth-middleware.ts
@@ -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;
diff --git a/apps/api/apps/api/pages/api/bookings/[id]/_delete.ts b/apps/api/apps/api/pages/api/bookings/[id]/_delete.ts
new file mode 100644
index 0000000000..a1cdbc9c3e
--- /dev/null
+++ b/apps/api/apps/api/pages/api/bookings/[id]/_delete.ts
@@ -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
+ *
+ *
+ * | Message |
+ * Cause |
+ *
+ *
+ * | Booking not found |
+ * The provided id didn't correspond to any existing booking. |
+ *
+ *
+ * | Cannot cancel past events |
+ * The provided id matched an existing booking with a past startDate. |
+ *
+ *
+ * | User not found |
+ * The userId did not matched an existing user. |
+ *
+ *
+ * 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);
diff --git a/apps/api/apps/api/pages/api/bookings/[id]/_get.ts b/apps/api/apps/api/pages/api/bookings/[id]/_get.ts
new file mode 100644
index 0000000000..5064ba2d78
--- /dev/null
+++ b/apps/api/apps/api/pages/api/bookings/[id]/_get.ts
@@ -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": "example@cal.com",
+ * "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);
diff --git a/apps/api/apps/api/pages/api/bookings/[id]/_patch.ts b/apps/api/apps/api/pages/api/bookings/[id]/_patch.ts
new file mode 100644
index 0000000000..74999ab13c
--- /dev/null
+++ b/apps/api/apps/api/pages/api/bookings/[id]/_patch.ts
@@ -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) {
+ 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);
diff --git a/apps/api/apps/api/pages/api/bookings/[id]/cancel.ts b/apps/api/apps/api/pages/api/bookings/[id]/cancel.ts
new file mode 100644
index 0000000000..8dd20bef17
--- /dev/null
+++ b/apps/api/apps/api/pages/api/bookings/[id]/cancel.ts
@@ -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);
+});
diff --git a/apps/api/apps/api/pages/api/bookings/[id]/index.ts b/apps/api/apps/api/pages/api/bookings/[id]/index.ts
new file mode 100644
index 0000000000..727ad02843
--- /dev/null
+++ b/apps/api/apps/api/pages/api/bookings/[id]/index.ts
@@ -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);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/bookings/_get.ts b/apps/api/apps/api/pages/api/bookings/_get.ts
new file mode 100644
index 0000000000..006b39472e
--- /dev/null
+++ b/apps/api/apps/api/pages/api/bookings/_get.ts
@@ -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": "example@cal.com",
+ * "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);
diff --git a/apps/api/apps/api/pages/api/bookings/_post.ts b/apps/api/apps/api/pages/api/bookings/_post.ts
new file mode 100644
index 0000000000..d6baaa4891
--- /dev/null
+++ b/apps/api/apps/api/pages/api/bookings/_post.ts
@@ -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": "hello@gmail.com",
+ * "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": "test@cal.com",
+ * "name": "Syed Ali Shahbaz",
+ * "timeZone": "Asia/Calcutta"
+ * },
+ * "attendees": [
+ * {
+ * "id": 12345,
+ * "email": "hello@gmail.com",
+ * "name": "Hello Hello",
+ * "timeZone": "Europe/London",
+ * "locale": "en",
+ * "bookingId": 11223344
+ * }
+ * ],
+ * "payment": [],
+ * "references": []
+ * }
+ * 400:
+ * description: |
+ * Bad request
+ *
+ *
+ * | Message |
+ * Cause |
+ *
+ *
+ * | Booking body is invalid |
+ * Missing property on booking entity. |
+ *
+ *
+ * | Invalid eventTypeId |
+ * The provided eventTypeId does not exist. |
+ *
+ *
+ * | Missing recurringCount |
+ * The eventType is recurring, and no recurringCount was passed. |
+ *
+ *
+ * | Invalid recurringCount |
+ * The provided recurringCount is greater than the eventType recurring config |
+ *
+ *
+ * 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);
diff --git a/apps/api/apps/api/pages/api/bookings/index.ts b/apps/api/apps/api/pages/api/bookings/index.ts
new file mode 100644
index 0000000000..2a15abfa5b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/bookings/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/custom-inputs/[id]/_auth-middleware.ts b/apps/api/apps/api/pages/api/custom-inputs/[id]/_auth-middleware.ts
new file mode 100644
index 0000000000..3bae379831
--- /dev/null
+++ b/apps/api/apps/api/pages/api/custom-inputs/[id]/_auth-middleware.ts
@@ -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;
diff --git a/apps/api/apps/api/pages/api/custom-inputs/[id]/_delete.ts b/apps/api/apps/api/pages/api/custom-inputs/[id]/_delete.ts
new file mode 100644
index 0000000000..747e1954ff
--- /dev/null
+++ b/apps/api/apps/api/pages/api/custom-inputs/[id]/_delete.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/custom-inputs/[id]/_get.ts b/apps/api/apps/api/pages/api/custom-inputs/[id]/_get.ts
new file mode 100644
index 0000000000..96cb8133dc
--- /dev/null
+++ b/apps/api/apps/api/pages/api/custom-inputs/[id]/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/custom-inputs/[id]/_patch.ts b/apps/api/apps/api/pages/api/custom-inputs/[id]/_patch.ts
new file mode 100644
index 0000000000..9ecdd822de
--- /dev/null
+++ b/apps/api/apps/api/pages/api/custom-inputs/[id]/_patch.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/custom-inputs/[id]/index.ts b/apps/api/apps/api/pages/api/custom-inputs/[id]/index.ts
new file mode 100644
index 0000000000..727ad02843
--- /dev/null
+++ b/apps/api/apps/api/pages/api/custom-inputs/[id]/index.ts
@@ -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);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/custom-inputs/_get.ts b/apps/api/apps/api/pages/api/custom-inputs/_get.ts
new file mode 100644
index 0000000000..db63434ddf
--- /dev/null
+++ b/apps/api/apps/api/pages/api/custom-inputs/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/custom-inputs/_post.ts b/apps/api/apps/api/pages/api/custom-inputs/_post.ts
new file mode 100644
index 0000000000..331fdd732f
--- /dev/null
+++ b/apps/api/apps/api/pages/api/custom-inputs/_post.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/custom-inputs/index.ts b/apps/api/apps/api/pages/api/custom-inputs/index.ts
new file mode 100644
index 0000000000..2a15abfa5b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/custom-inputs/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/destination-calendars/[id].ts b/apps/api/apps/api/pages/api/destination-calendars/[id].ts
new file mode 100644
index 0000000000..1f521c40d7
--- /dev/null
+++ b/apps/api/apps/api/pages/api/destination-calendars/[id].ts
@@ -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
+) {
+ 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)
+);
diff --git a/apps/api/apps/api/pages/api/destination-calendars/index.ts b/apps/api/apps/api/pages/api/destination-calendars/index.ts
new file mode 100644
index 0000000000..c1330d49fa
--- /dev/null
+++ b/apps/api/apps/api/pages/api/destination-calendars/index.ts
@@ -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
+) {
+ 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);
diff --git a/apps/api/apps/api/pages/api/docs.ts b/apps/api/apps/api/pages/api/docs.ts
new file mode 100644
index 0000000000..1773d87457
--- /dev/null
+++ b/apps/api/apps/api/pages/api/docs.ts
@@ -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: "example@cal.com",
+ },
+ name: {
+ type: "string",
+ },
+ timeZone: {
+ type: "string",
+ example: "Europe/London",
+ },
+ locale: {
+ type: "string",
+ example: "en",
+ },
+ },
+ },
+ },
+ user: {
+ properties: {
+ email: {
+ type: "string",
+ example: "example@cal.com",
+ },
+ 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();
diff --git a/apps/api/apps/api/pages/api/event-types/[id]/_auth-middleware.ts b/apps/api/apps/api/pages/api/event-types/[id]/_auth-middleware.ts
new file mode 100644
index 0000000000..8907d7cd3b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/event-types/[id]/_auth-middleware.ts
@@ -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;
diff --git a/apps/api/apps/api/pages/api/event-types/[id]/_delete.ts b/apps/api/apps/api/pages/api/event-types/[id]/_delete.ts
new file mode 100644
index 0000000000..2e598afc54
--- /dev/null
+++ b/apps/api/apps/api/pages/api/event-types/[id]/_delete.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/event-types/[id]/_get.ts b/apps/api/apps/api/pages/api/event-types/[id]/_get.ts
new file mode 100644
index 0000000000..74d9d14456
--- /dev/null
+++ b/apps/api/apps/api/pages/api/event-types/[id]/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/event-types/[id]/_patch.ts b/apps/api/apps/api/pages/api/event-types/[id]/_patch.ts
new file mode 100644
index 0000000000..2468d1621b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/event-types/[id]/_patch.ts
@@ -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) {
+ 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);
diff --git a/apps/api/apps/api/pages/api/event-types/[id]/index.ts b/apps/api/apps/api/pages/api/event-types/[id]/index.ts
new file mode 100644
index 0000000000..727ad02843
--- /dev/null
+++ b/apps/api/apps/api/pages/api/event-types/[id]/index.ts
@@ -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);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/event-types/_get.ts b/apps/api/apps/api/pages/api/event-types/_get.ts
new file mode 100644
index 0000000000..acdfdc4dee
--- /dev/null
+++ b/apps/api/apps/api/pages/api/event-types/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/event-types/_post.ts b/apps/api/apps/api/pages/api/event-types/_post.ts
new file mode 100644
index 0000000000..488a15e6b9
--- /dev/null
+++ b/apps/api/apps/api/pages/api/event-types/_post.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/event-types/_utils/checkTeamEventEditPermission.ts b/apps/api/apps/api/pages/api/event-types/_utils/checkTeamEventEditPermission.ts
new file mode 100644
index 0000000000..abcfc055f2
--- /dev/null
+++ b/apps/api/apps/api/pages/api/event-types/_utils/checkTeamEventEditPermission.ts
@@ -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, "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",
+ });
+ }
+ }
+}
diff --git a/apps/api/apps/api/pages/api/event-types/_utils/ensureOnlyMembersAsHosts.ts b/apps/api/apps/api/pages/api/event-types/_utils/ensureOnlyMembersAsHosts.ts
new file mode 100644
index 0000000000..301c5307a1
--- /dev/null
+++ b/apps/api/apps/api/pages/api/event-types/_utils/ensureOnlyMembersAsHosts.ts
@@ -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, "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.");
+ }
+ }
+}
diff --git a/apps/api/apps/api/pages/api/event-types/_utils/getCalLink.ts b/apps/api/apps/api/pages/api/event-types/_utils/getCalLink.ts
new file mode 100644
index 0000000000..5c46575585
--- /dev/null
+++ b/apps/api/apps/api/pages/api/event-types/_utils/getCalLink.ts
@@ -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}`;
+}
diff --git a/apps/api/apps/api/pages/api/event-types/index.ts b/apps/api/apps/api/pages/api/event-types/index.ts
new file mode 100644
index 0000000000..2a15abfa5b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/event-types/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/index.ts b/apps/api/apps/api/pages/api/index.ts
new file mode 100644
index 0000000000..85f1d6be3b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/index.ts
@@ -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" });
+}
diff --git a/apps/api/apps/api/pages/api/me/_get.ts b/apps/api/apps/api/pages/api/me/_get.ts
new file mode 100644
index 0000000000..d0a3759730
--- /dev/null
+++ b/apps/api/apps/api/pages/api/me/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/me/index.ts b/apps/api/apps/api/pages/api/me/index.ts
new file mode 100644
index 0000000000..c53e4b8ef3
--- /dev/null
+++ b/apps/api/apps/api/pages/api/me/index.ts
@@ -0,0 +1,9 @@
+import { defaultHandler } from "@calcom/lib/server";
+
+import { withMiddleware } from "~/lib/helpers/withMiddleware";
+
+export default withMiddleware()(
+ defaultHandler({
+ GET: import("./_get"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/memberships/[id]/_auth-middleware.ts b/apps/api/apps/api/pages/api/memberships/[id]/_auth-middleware.ts
new file mode 100644
index 0000000000..97ac4ff16d
--- /dev/null
+++ b/apps/api/apps/api/pages/api/memberships/[id]/_auth-middleware.ts
@@ -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;
diff --git a/apps/api/apps/api/pages/api/memberships/[id]/_delete.ts b/apps/api/apps/api/pages/api/memberships/[id]/_delete.ts
new file mode 100644
index 0000000000..06acefb3bb
--- /dev/null
+++ b/apps/api/apps/api/pages/api/memberships/[id]/_delete.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/memberships/[id]/_get.ts b/apps/api/apps/api/pages/api/memberships/[id]/_get.ts
new file mode 100644
index 0000000000..cf44094bfa
--- /dev/null
+++ b/apps/api/apps/api/pages/api/memberships/[id]/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/memberships/[id]/_patch.ts b/apps/api/apps/api/pages/api/memberships/[id]/_patch.ts
new file mode 100644
index 0000000000..98115eff39
--- /dev/null
+++ b/apps/api/apps/api/pages/api/memberships/[id]/_patch.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/memberships/[id]/index.ts b/apps/api/apps/api/pages/api/memberships/[id]/index.ts
new file mode 100644
index 0000000000..727ad02843
--- /dev/null
+++ b/apps/api/apps/api/pages/api/memberships/[id]/index.ts
@@ -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);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/memberships/_get.ts b/apps/api/apps/api/pages/api/memberships/_get.ts
new file mode 100644
index 0000000000..da6e936df3
--- /dev/null
+++ b/apps/api/apps/api/pages/api/memberships/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/memberships/_post.ts b/apps/api/apps/api/pages/api/memberships/_post.ts
new file mode 100644
index 0000000000..11cba74938
--- /dev/null
+++ b/apps/api/apps/api/pages/api/memberships/_post.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/memberships/index.ts b/apps/api/apps/api/pages/api/memberships/index.ts
new file mode 100644
index 0000000000..2a15abfa5b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/memberships/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/payments/[id].ts b/apps/api/apps/api/pages/api/payments/[id].ts
new file mode 100644
index 0000000000..f8a54ff7f4
--- /dev/null
+++ b/apps/api/apps/api/pages/api/payments/[id].ts
@@ -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
+) {
+ 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));
diff --git a/apps/api/apps/api/pages/api/payments/index.ts b/apps/api/apps/api/pages/api/payments/index.ts
new file mode 100644
index 0000000000..c6f8c79fec
--- /dev/null
+++ b/apps/api/apps/api/pages/api/payments/index.ts
@@ -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) {
+ 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);
diff --git a/apps/api/apps/api/pages/api/schedules/[id]/_auth-middleware.ts b/apps/api/apps/api/pages/api/schedules/[id]/_auth-middleware.ts
new file mode 100644
index 0000000000..42184440d3
--- /dev/null
+++ b/apps/api/apps/api/pages/api/schedules/[id]/_auth-middleware.ts
@@ -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;
diff --git a/apps/api/apps/api/pages/api/schedules/[id]/_delete.ts b/apps/api/apps/api/pages/api/schedules/[id]/_delete.ts
new file mode 100644
index 0000000000..e48c76c469
--- /dev/null
+++ b/apps/api/apps/api/pages/api/schedules/[id]/_delete.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/schedules/[id]/_get.ts b/apps/api/apps/api/pages/api/schedules/[id]/_get.ts
new file mode 100644
index 0000000000..fdadce2cba
--- /dev/null
+++ b/apps/api/apps/api/pages/api/schedules/[id]/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/schedules/[id]/_patch.ts b/apps/api/apps/api/pages/api/schedules/[id]/_patch.ts
new file mode 100644
index 0000000000..1c8f52d688
--- /dev/null
+++ b/apps/api/apps/api/pages/api/schedules/[id]/_patch.ts
@@ -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) {
+ 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);
diff --git a/apps/api/apps/api/pages/api/schedules/[id]/index.ts b/apps/api/apps/api/pages/api/schedules/[id]/index.ts
new file mode 100644
index 0000000000..727ad02843
--- /dev/null
+++ b/apps/api/apps/api/pages/api/schedules/[id]/index.ts
@@ -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);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/schedules/_get.ts b/apps/api/apps/api/pages/api/schedules/_get.ts
new file mode 100644
index 0000000000..1b06a116e9
--- /dev/null
+++ b/apps/api/apps/api/pages/api/schedules/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/schedules/_post.ts b/apps/api/apps/api/pages/api/schedules/_post.ts
new file mode 100644
index 0000000000..a50f2cd5b6
--- /dev/null
+++ b/apps/api/apps/api/pages/api/schedules/_post.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/schedules/index.ts b/apps/api/apps/api/pages/api/schedules/index.ts
new file mode 100644
index 0000000000..2a15abfa5b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/schedules/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/selected-calendars/[id]/_auth-middleware.ts b/apps/api/apps/api/pages/api/selected-calendars/[id]/_auth-middleware.ts
new file mode 100644
index 0000000000..620ba818fb
--- /dev/null
+++ b/apps/api/apps/api/pages/api/selected-calendars/[id]/_auth-middleware.ts
@@ -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;
diff --git a/apps/api/apps/api/pages/api/selected-calendars/[id]/_delete.ts b/apps/api/apps/api/pages/api/selected-calendars/[id]/_delete.ts
new file mode 100644
index 0000000000..e04b67f711
--- /dev/null
+++ b/apps/api/apps/api/pages/api/selected-calendars/[id]/_delete.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/selected-calendars/[id]/_get.ts b/apps/api/apps/api/pages/api/selected-calendars/[id]/_get.ts
new file mode 100644
index 0000000000..a5549f1a21
--- /dev/null
+++ b/apps/api/apps/api/pages/api/selected-calendars/[id]/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/selected-calendars/[id]/_patch.ts b/apps/api/apps/api/pages/api/selected-calendars/[id]/_patch.ts
new file mode 100644
index 0000000000..c2b526303d
--- /dev/null
+++ b/apps/api/apps/api/pages/api/selected-calendars/[id]/_patch.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/selected-calendars/[id]/index.ts b/apps/api/apps/api/pages/api/selected-calendars/[id]/index.ts
new file mode 100644
index 0000000000..727ad02843
--- /dev/null
+++ b/apps/api/apps/api/pages/api/selected-calendars/[id]/index.ts
@@ -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);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/selected-calendars/_get.ts b/apps/api/apps/api/pages/api/selected-calendars/_get.ts
new file mode 100644
index 0000000000..c5e2182adf
--- /dev/null
+++ b/apps/api/apps/api/pages/api/selected-calendars/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/selected-calendars/_post.ts b/apps/api/apps/api/pages/api/selected-calendars/_post.ts
new file mode 100644
index 0000000000..23b26a76e9
--- /dev/null
+++ b/apps/api/apps/api/pages/api/selected-calendars/_post.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/selected-calendars/index.ts b/apps/api/apps/api/pages/api/selected-calendars/index.ts
new file mode 100644
index 0000000000..2a15abfa5b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/selected-calendars/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/teams/[teamId]/_auth-middleware.ts b/apps/api/apps/api/pages/api/teams/[teamId]/_auth-middleware.ts
new file mode 100644
index 0000000000..bde11bb75c
--- /dev/null
+++ b/apps/api/apps/api/pages/api/teams/[teamId]/_auth-middleware.ts
@@ -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;
diff --git a/apps/api/apps/api/pages/api/teams/[teamId]/_delete.ts b/apps/api/apps/api/pages/api/teams/[teamId]/_delete.ts
new file mode 100644
index 0000000000..13c5c35370
--- /dev/null
+++ b/apps/api/apps/api/pages/api/teams/[teamId]/_delete.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/teams/[teamId]/_get.ts b/apps/api/apps/api/pages/api/teams/[teamId]/_get.ts
new file mode 100644
index 0000000000..cff0e987c9
--- /dev/null
+++ b/apps/api/apps/api/pages/api/teams/[teamId]/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/teams/[teamId]/_patch.ts b/apps/api/apps/api/pages/api/teams/[teamId]/_patch.ts
new file mode 100644
index 0000000000..93d1a3a46a
--- /dev/null
+++ b/apps/api/apps/api/pages/api/teams/[teamId]/_patch.ts
@@ -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 | 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);
diff --git a/apps/api/apps/api/pages/api/teams/[teamId]/availability/index.ts b/apps/api/apps/api/pages/api/teams/[teamId]/availability/index.ts
new file mode 100644
index 0000000000..95a9f13f9c
--- /dev/null
+++ b/apps/api/apps/api/pages/api/teams/[teamId]/availability/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/teams/[teamId]/event-types/_get.ts b/apps/api/apps/api/pages/api/teams/[teamId]/event-types/_get.ts
new file mode 100644
index 0000000000..38d1a6d425
--- /dev/null
+++ b/apps/api/apps/api/pages/api/teams/[teamId]/event-types/_get.ts
@@ -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);
diff --git a/apps/api/apps/api/pages/api/teams/[teamId]/event-types/index.ts b/apps/api/apps/api/pages/api/teams/[teamId]/event-types/index.ts
new file mode 100644
index 0000000000..c53e4b8ef3
--- /dev/null
+++ b/apps/api/apps/api/pages/api/teams/[teamId]/event-types/index.ts
@@ -0,0 +1,9 @@
+import { defaultHandler } from "@calcom/lib/server";
+
+import { withMiddleware } from "~/lib/helpers/withMiddleware";
+
+export default withMiddleware()(
+ defaultHandler({
+ GET: import("./_get"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/teams/[teamId]/index.ts b/apps/api/apps/api/pages/api/teams/[teamId]/index.ts
new file mode 100644
index 0000000000..727ad02843
--- /dev/null
+++ b/apps/api/apps/api/pages/api/teams/[teamId]/index.ts
@@ -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);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/teams/[teamId]/publish.ts b/apps/api/apps/api/pages/api/teams/[teamId]/publish.ts
new file mode 100644
index 0000000000..4cf45e12fd
--- /dev/null
+++ b/apps/api/apps/api/pages/api/teams/[teamId]/publish.ts
@@ -0,0 +1,44 @@
+import type { NextApiRequest, NextApiResponse } from "next";
+
+import { HttpError } from "@calcom/lib/http-error";
+import { defaultHandler, defaultResponder } from "@calcom/lib/server";
+import { MembershipRole } from "@calcom/prisma/enums";
+import { createContext } from "@calcom/trpc/server/createContext";
+import { publishHandler } from "@calcom/trpc/server/routers/viewer/teams/publish.handler";
+
+import { TRPCError } from "@trpc/server";
+import { getHTTPStatusCodeFromError } from "@trpc/server/http";
+
+import { withMiddleware } from "~/lib/helpers/withMiddleware";
+import { schemaQueryTeamId } from "~/lib/validations/shared/queryTeamId";
+
+import authMiddleware, { checkPermissions } from "./_auth-middleware";
+
+const patchHandler = async (req: NextApiRequest, res: NextApiResponse) => {
+ await checkPermissions(req, { in: [MembershipRole.OWNER, MembershipRole.ADMIN] });
+ /** @see https://trpc.io/docs/server-side-calls */
+ const ctx = await createContext({ req, res });
+ const user = ctx.user;
+ if (!user) {
+ throw new Error("Internal Error.");
+ }
+ try {
+ const { teamId } = schemaQueryTeamId.parse(req.query);
+ return await publishHandler({ input: { teamId }, ctx: { ...ctx, user } });
+ } catch (cause) {
+ if (cause instanceof TRPCError) {
+ const statusCode = getHTTPStatusCodeFromError(cause);
+ throw new HttpError({ statusCode, message: cause.message });
+ }
+ throw cause;
+ }
+};
+
+export default withMiddleware()(
+ defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {
+ await authMiddleware(req);
+ return defaultHandler({
+ PATCH: Promise.resolve({ default: defaultResponder(patchHandler) }),
+ })(req, res);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/teams/_get.ts b/apps/api/apps/api/pages/api/teams/_get.ts
new file mode 100644
index 0000000000..49af07ac8e
--- /dev/null
+++ b/apps/api/apps/api/pages/api/teams/_get.ts
@@ -0,0 +1,40 @@
+import type { Prisma } from "@prisma/client";
+import type { NextApiRequest } from "next";
+
+import { defaultResponder } from "@calcom/lib/server";
+
+import { schemaTeamsReadPublic } from "~/lib/validations/team";
+
+/**
+ * @swagger
+ * /teams:
+ * get:
+ * operationId: listTeams
+ * summary: Find all teams
+ * parameters:
+ * - 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: No teams were found
+ */
+async function getHandler(req: NextApiRequest) {
+ const { userId, prisma, isAdmin } = req;
+ const where: Prisma.TeamWhereInput = {};
+ // If user is not ADMIN, return only his data.
+ if (!isAdmin) where.members = { some: { userId } };
+ const data = await prisma.team.findMany({ where });
+ return { teams: schemaTeamsReadPublic.parse(data) };
+}
+
+export default defaultResponder(getHandler);
diff --git a/apps/api/apps/api/pages/api/teams/_post.ts b/apps/api/apps/api/pages/api/teams/_post.ts
new file mode 100644
index 0000000000..56e0820535
--- /dev/null
+++ b/apps/api/apps/api/pages/api/teams/_post.ts
@@ -0,0 +1,98 @@
+import type { NextApiRequest } from "next";
+
+import { IS_TEAM_BILLING_ENABLED } from "@calcom/lib/constants";
+import { HttpError } from "@calcom/lib/http-error";
+import { defaultResponder } from "@calcom/lib/server";
+import { MembershipRole } from "@calcom/prisma/enums";
+
+import { schemaMembershipPublic } from "~/lib/validations/membership";
+import { schemaTeamBodyParams, schemaTeamReadPublic } from "~/lib/validations/team";
+
+/**
+ * @swagger
+ * /teams:
+ * post:
+ * operationId: addTeam
+ * summary: Creates a new team
+ * 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:
+ * - name
+ * - slug
+ * 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 created
+ * 400:
+ * description: Bad request. Team body is invalid.
+ * 401:
+ * description: Authorization information is missing or invalid.
+ */
+async function postHandler(req: NextApiRequest) {
+ const { prisma, body, userId } = req;
+ const data = schemaTeamBodyParams.parse(body);
+
+ if (data.slug) {
+ const alreadyExist = await prisma.team.findFirst({
+ where: {
+ slug: data.slug,
+ },
+ });
+ if (alreadyExist) throw new HttpError({ statusCode: 409, message: "Team slug already exists" });
+ if (IS_TEAM_BILLING_ENABLED) {
+ // Setting slug in metadata, so it can be published later
+ data.metadata = {
+ requestedSlug: data.slug,
+ };
+ delete data.slug;
+ }
+ }
+
+ // TODO: Perhaps there is a better fix for this?
+ const cloneData: typeof data & {
+ metadata: NonNullable | undefined;
+ } = {
+ ...data,
+ metadata: data.metadata === null ? {} : data.metadata || undefined,
+ };
+ const team = await prisma.team.create({
+ data: {
+ ...cloneData,
+ createdAt: new Date(),
+ members: {
+ // We're also creating the relation membership of team ownership in this call.
+ create: { userId, role: MembershipRole.OWNER, accepted: true },
+ },
+ },
+ include: { members: true },
+ });
+ req.statusCode = 201;
+ // We are also returning the new ownership relation as owner besides team.
+ return {
+ team: schemaTeamReadPublic.parse(team),
+ owner: schemaMembershipPublic.parse(team.members[0]),
+ message: "Team created successfully, we also made you the owner of this team",
+ };
+}
+
+export default defaultResponder(postHandler);
diff --git a/apps/api/apps/api/pages/api/teams/index.ts b/apps/api/apps/api/pages/api/teams/index.ts
new file mode 100644
index 0000000000..2a15abfa5b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/teams/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/users/[userId]/_delete.ts b/apps/api/apps/api/pages/api/users/[userId]/_delete.ts
new file mode 100644
index 0000000000..44e8f0df0f
--- /dev/null
+++ b/apps/api/apps/api/pages/api/users/[userId]/_delete.ts
@@ -0,0 +1,51 @@
+import type { NextApiRequest } from "next";
+
+import { HttpError } from "@calcom/lib/http-error";
+import { defaultResponder } from "@calcom/lib/server";
+
+import { schemaQueryUserId } from "~/lib/validations/shared/queryUserId";
+
+/**
+ * @swagger
+ * /users/{userId}:
+ * delete:
+ * summary: Remove an existing user
+ * operationId: removeUserById
+ * parameters:
+ * - in: path
+ * name: userId
+ * example: 1
+ * schema:
+ * type: integer
+ * required: true
+ * description: ID of the user to delete
+ * - in: query
+ * name: apiKey
+ * schema:
+ * type: string
+ * required: true
+ * description: Your API key
+ * tags:
+ * - users
+ * responses:
+ * 201:
+ * description: OK, user removed successfuly
+ * 400:
+ * description: Bad request. User id is invalid.
+ * 401:
+ * description: Authorization information is missing or invalid.
+ */
+export async function deleteHandler(req: NextApiRequest) {
+ const { prisma, isAdmin } = req;
+ const query = schemaQueryUserId.parse(req.query);
+ // Here we only check for ownership of the user if the user is not admin, otherwise we let ADMIN's edit any user
+ if (!isAdmin && query.userId !== req.userId) throw new HttpError({ statusCode: 403, message: "Forbidden" });
+
+ const user = await prisma.user.findUnique({ where: { id: query.userId } });
+ if (!user) throw new HttpError({ statusCode: 404, message: "User not found" });
+
+ await prisma.user.delete({ where: { id: user.id } });
+ return { message: `User with id: ${user.id} deleted successfully` };
+}
+
+export default defaultResponder(deleteHandler);
diff --git a/apps/api/apps/api/pages/api/users/[userId]/_get.ts b/apps/api/apps/api/pages/api/users/[userId]/_get.ts
new file mode 100644
index 0000000000..5be3926ae0
--- /dev/null
+++ b/apps/api/apps/api/pages/api/users/[userId]/_get.ts
@@ -0,0 +1,50 @@
+import type { NextApiRequest } from "next";
+
+import { HttpError } from "@calcom/lib/http-error";
+import { defaultResponder } from "@calcom/lib/server";
+
+import { schemaQueryUserId } from "~/lib/validations/shared/queryUserId";
+import { schemaUserReadPublic } from "~/lib/validations/user";
+
+/**
+ * @swagger
+ * /users/{userId}:
+ * get:
+ * summary: Find a user, returns your user if regular user.
+ * operationId: getUserById
+ * parameters:
+ * - in: path
+ * name: userId
+ * example: 4
+ * schema:
+ * type: integer
+ * required: true
+ * description: ID of the user to get
+ * - in: query
+ * name: apiKey
+ * schema:
+ * type: string
+ * required: true
+ * description: Your API key
+ * tags:
+ * - users
+ * responses:
+ * 200:
+ * description: OK
+ * 401:
+ * description: Authorization information is missing or invalid.
+ * 404:
+ * description: User was not found
+ */
+export async function getHandler(req: NextApiRequest) {
+ const { prisma, isAdmin } = req;
+
+ const query = schemaQueryUserId.parse(req.query);
+ // Here we only check for ownership of the user if the user is not admin, otherwise we let ADMIN's edit any user
+ if (!isAdmin && query.userId !== req.userId) throw new HttpError({ statusCode: 403, message: "Forbidden" });
+ const data = await prisma.user.findUnique({ where: { id: query.userId } });
+ const user = schemaUserReadPublic.parse(data);
+ return { user };
+}
+
+export default defaultResponder(getHandler);
diff --git a/apps/api/apps/api/pages/api/users/[userId]/_patch.ts b/apps/api/apps/api/pages/api/users/[userId]/_patch.ts
new file mode 100644
index 0000000000..59d8b76f94
--- /dev/null
+++ b/apps/api/apps/api/pages/api/users/[userId]/_patch.ts
@@ -0,0 +1,121 @@
+import type { NextApiRequest } from "next";
+
+import { HttpError } from "@calcom/lib/http-error";
+import { defaultResponder } from "@calcom/lib/server";
+
+import { schemaQueryUserId } from "~/lib/validations/shared/queryUserId";
+import { schemaUserEditBodyParams, schemaUserReadPublic } from "~/lib/validations/user";
+
+/**
+ * @swagger
+ * /users/{userId}:
+ * patch:
+ * summary: Edit an existing user
+ * operationId: editUserById
+ * parameters:
+ * - in: path
+ * name: userId
+ * example: 4
+ * schema:
+ * type: integer
+ * required: true
+ * description: ID of the user to edit
+ * - in: query
+ * name: apiKey
+ * required: true
+ * schema:
+ * type: string
+ * description: Your API key
+ * 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
+ * description: Email that belongs to the user being edited
+ * username:
+ * type: string
+ * description: Username for the user being edited
+ * brandColor:
+ * description: The user's brand color
+ * type: string
+ * darkBrandColor:
+ * description: The user's brand color for dark mode
+ * type: string
+ * weekStart:
+ * description: Start of the week. Acceptable values are one of [SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
+ * type: string
+ * timeZone:
+ * description: The user's time zone
+ * type: string
+ * theme:
+ * description: Default theme for the user. Acceptable values are one of [DARK, LIGHT]
+ * type: string
+ * timeFormat:
+ * description: The user's time format. Acceptable values are one of [TWELVE, TWENTY_FOUR]
+ * type: string
+ * locale:
+ * description: The user's locale. Acceptable values are one of [EN, FR, IT, RU, ES, DE, PT, RO, NL, PT_BR, ES_419, KO, JA, PL, AR, IW, ZH_CH, ZH_TW, CS, SR, SV, VI]
+ * type: string
+ * examples:
+ * user:
+ * summary: An example of USER
+ * value:
+ * email: email@example.com
+ * username: johndoe
+ * weekStart: MONDAY
+ * brandColor: #555555
+ * darkBrandColor: #111111
+ * timeZone: EUROPE/PARIS
+ * theme: LIGHT
+ * timeFormat: TWELVE
+ * locale: FR
+ * tags:
+ * - users
+ * responses:
+ * 200:
+ * description: OK, user edited successfuly
+ * 400:
+ * description: Bad request. User body is invalid.
+ * 401:
+ * description: Authorization information is missing or invalid.
+ * 403:
+ * description: Insufficient permissions to access resource.
+ */
+export async function patchHandler(req: NextApiRequest) {
+ const { prisma, isAdmin } = req;
+ const query = schemaQueryUserId.parse(req.query);
+ // Here we only check for ownership of the user if the user is not admin, otherwise we let ADMIN's edit any user
+ if (!isAdmin && query.userId !== req.userId) throw new HttpError({ statusCode: 403, message: "Forbidden" });
+
+ const body = await schemaUserEditBodyParams.parseAsync(req.body);
+ // disable role changes unless admin.
+ if (!isAdmin && body.role) {
+ body.role = undefined;
+ }
+
+ const userSchedules = await prisma.schedule.findMany({
+ where: { userId: query.userId },
+ });
+ const userSchedulesIds = userSchedules.map((schedule) => schedule.id);
+ // @note: here we make sure user can only make as default his own scheudles
+ if (body.defaultScheduleId && !userSchedulesIds.includes(Number(body.defaultScheduleId))) {
+ throw new HttpError({
+ statusCode: 400,
+ message: "Bad request: Invalid default schedule id",
+ });
+ }
+ const data = await prisma.user.update({
+ where: { id: query.userId },
+ data: body,
+ });
+ const user = schemaUserReadPublic.parse(data);
+ return { user };
+}
+
+export default defaultResponder(patchHandler);
diff --git a/apps/api/apps/api/pages/api/users/[userId]/availability/index.ts b/apps/api/apps/api/pages/api/users/[userId]/availability/index.ts
new file mode 100644
index 0000000000..95a9f13f9c
--- /dev/null
+++ b/apps/api/apps/api/pages/api/users/[userId]/availability/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/users/[userId]/index.ts b/apps/api/apps/api/pages/api/users/[userId]/index.ts
new file mode 100644
index 0000000000..ef0f429b1e
--- /dev/null
+++ b/apps/api/apps/api/pages/api/users/[userId]/index.ts
@@ -0,0 +1,11 @@
+import { defaultHandler } from "@calcom/lib/server";
+
+import { withMiddleware } from "~/lib/helpers/withMiddleware";
+
+export default withMiddleware()(
+ defaultHandler({
+ GET: import("./_get"),
+ PATCH: import("./_patch"),
+ DELETE: import("./_delete"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/users/_get.ts b/apps/api/apps/api/pages/api/users/_get.ts
new file mode 100644
index 0000000000..59e09bdeb5
--- /dev/null
+++ b/apps/api/apps/api/pages/api/users/_get.ts
@@ -0,0 +1,50 @@
+import type { Prisma } from "@prisma/client";
+import type { NextApiRequest } from "next";
+
+import { defaultResponder } from "@calcom/lib/server";
+
+import { withMiddleware } from "~/lib/helpers/withMiddleware";
+import { schemaUsersReadPublic } from "~/lib/validations/user";
+
+/**
+ * @swagger
+ * /users:
+ * get:
+ * operationId: listUsers
+ * summary: Find all users.
+ * parameters:
+ * - in: query
+ * name: apiKey
+ * required: true
+ * schema:
+ * type: string
+ * description: Your API key
+ * tags:
+ * - users
+ * responses:
+ * 200:
+ * description: OK
+ * 401:
+ * description: Authorization information is missing or invalid.
+ * 404:
+ * description: No users were found
+ */
+export async function getHandler(req: NextApiRequest) {
+ const {
+ userId,
+ prisma,
+ isAdmin,
+ pagination: { take, skip },
+ } = req;
+ const where: Prisma.UserWhereInput = {};
+ // If user is not ADMIN, return only his data.
+ if (!isAdmin) where.id = userId;
+ const [total, data] = await prisma.$transaction([
+ prisma.user.count(),
+ prisma.user.findMany({ where, take, skip }),
+ ]);
+ const users = schemaUsersReadPublic.parse(data);
+ return { users, total };
+}
+
+export default withMiddleware("pagination")(defaultResponder(getHandler));
diff --git a/apps/api/apps/api/pages/api/users/_post.ts b/apps/api/apps/api/pages/api/users/_post.ts
new file mode 100644
index 0000000000..7c945399d0
--- /dev/null
+++ b/apps/api/apps/api/pages/api/users/_post.ts
@@ -0,0 +1,93 @@
+import type { NextApiRequest } from "next";
+
+import { HttpError } from "@calcom/lib/http-error";
+import { defaultResponder } from "@calcom/lib/server";
+
+import { schemaUserCreateBodyParams } from "~/lib/validations/user";
+
+/**
+ * @swagger
+ * /users:
+ * post:
+ * operationId: addUser
+ * summary: Creates a new user
+ * parameters:
+ * - in: query
+ * name: apiKey
+ * required: true
+ * schema:
+ * type: string
+ * description: Your API key
+ * requestBody:
+ * description: Create a new user
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * required:
+ * - email
+ * - username
+ * properties:
+ * email:
+ * type: string
+ * format: email
+ * description: Email that belongs to the user being edited
+ * username:
+ * type: string
+ * description: Username for the user being created
+ * brandColor:
+ * description: The new user's brand color
+ * type: string
+ * darkBrandColor:
+ * description: The new user's brand color for dark mode
+ * type: string
+ * weekStart:
+ * description: Start of the week. Acceptable values are one of [SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
+ * type: string
+ * timeZone:
+ * description: The new user's time zone. Eg- 'EUROPE/PARIS'
+ * type: string
+ * theme:
+ * description: Default theme for the new user. Acceptable values are one of [DARK, LIGHT]
+ * type: string
+ * timeFormat:
+ * description: The new user's time format. Acceptable values are one of [TWELVE, TWENTY_FOUR]
+ * type: string
+ * locale:
+ * description: The new user's locale. Acceptable values are one of [EN, FR, IT, RU, ES, DE, PT, RO, NL, PT_BR, ES_419, KO, JA, PL, AR, IW, ZH_CH, ZH_TW, CS, SR, SV, VI]
+ * type: string
+ * examples:
+ * user:
+ * summary: An example of USER
+ * value:
+ * email: 'email@example.com'
+ * username: 'johndoe'
+ * weekStart: 'MONDAY'
+ * brandColor: '#555555'
+ * darkBrandColor: '#111111'
+ * timeZone: 'EUROPE/PARIS'
+ * theme: 'LIGHT'
+ * timeFormat: 'TWELVE'
+ * locale: 'FR'
+ * tags:
+ * - users
+ * responses:
+ * 201:
+ * description: OK, user created
+ * 400:
+ * description: Bad request. user body is invalid.
+ * 401:
+ * description: Authorization information is missing or invalid.
+ */
+async function postHandler(req: NextApiRequest) {
+ const { prisma, isAdmin } = req;
+ // If user is not ADMIN, return unauthorized.
+ if (!isAdmin) throw new HttpError({ statusCode: 401, message: "You are not authorized" });
+ const data = await schemaUserCreateBodyParams.parseAsync(req.body);
+ const user = await prisma.user.create({ data });
+ req.statusCode = 201;
+ return { user };
+}
+
+export default defaultResponder(postHandler);
diff --git a/apps/api/apps/api/pages/api/users/index.ts b/apps/api/apps/api/pages/api/users/index.ts
new file mode 100644
index 0000000000..2a15abfa5b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/users/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/pages/api/webhooks/[id]/_auth-middleware.ts b/apps/api/apps/api/pages/api/webhooks/[id]/_auth-middleware.ts
new file mode 100644
index 0000000000..6f2eb04db5
--- /dev/null
+++ b/apps/api/apps/api/pages/api/webhooks/[id]/_auth-middleware.ts
@@ -0,0 +1,19 @@
+import type { NextApiRequest } from "next";
+
+import { HttpError } from "@calcom/lib/http-error";
+
+import { schemaQueryIdAsString } from "~/lib/validations/shared/queryIdString";
+
+async function authMiddleware(req: NextApiRequest) {
+ const { userId, isAdmin, prisma } = req;
+ const { id } = schemaQueryIdAsString.parse(req.query);
+ // Admins can just skip this check
+ if (isAdmin) return;
+ // Check if the current user can access the webhook
+ const webhook = await prisma.webhook.findFirst({
+ where: { id, appId: null, OR: [{ userId }, { eventType: { team: { members: { some: { userId } } } } }] },
+ });
+ if (!webhook) throw new HttpError({ statusCode: 403, message: "Forbidden" });
+}
+
+export default authMiddleware;
diff --git a/apps/api/apps/api/pages/api/webhooks/[id]/_delete.ts b/apps/api/apps/api/pages/api/webhooks/[id]/_delete.ts
new file mode 100644
index 0000000000..4750741338
--- /dev/null
+++ b/apps/api/apps/api/pages/api/webhooks/[id]/_delete.ts
@@ -0,0 +1,45 @@
+import type { NextApiRequest } from "next";
+
+import { defaultResponder } from "@calcom/lib/server";
+
+import { schemaQueryIdAsString } from "~/lib/validations/shared/queryIdString";
+
+/**
+ * @swagger
+ * /webhooks/{id}:
+ * delete:
+ * summary: Remove an existing hook
+ * operationId: removeWebhookById
+ * parameters:
+ * - in: path
+ * name: id
+ * schema:
+ * type: integer
+ * required: true
+ * description: Numeric ID of the hooks to delete
+ * - in: query
+ * name: apiKey
+ * required: true
+ * schema:
+ * type: string
+ * description: Your API key
+ * tags:
+ * - webhooks
+ * externalDocs:
+ * url: https://docs.cal.com/core-features/webhooks
+ * responses:
+ * 201:
+ * description: OK, hook removed successfully
+ * 400:
+ * description: Bad request. hook id is invalid.
+ * 401:
+ * description: Authorization information is missing or invalid.
+ */
+export async function deleteHandler(req: NextApiRequest) {
+ const { prisma, query } = req;
+ const { id } = schemaQueryIdAsString.parse(query);
+ await prisma.webhook.delete({ where: { id } });
+ return { message: `Schedule with id: ${id} deleted successfully` };
+}
+
+export default defaultResponder(deleteHandler);
diff --git a/apps/api/apps/api/pages/api/webhooks/[id]/_get.ts b/apps/api/apps/api/pages/api/webhooks/[id]/_get.ts
new file mode 100644
index 0000000000..3bde62987a
--- /dev/null
+++ b/apps/api/apps/api/pages/api/webhooks/[id]/_get.ts
@@ -0,0 +1,46 @@
+import type { NextApiRequest } from "next";
+
+import { defaultResponder } from "@calcom/lib/server";
+
+import { schemaQueryIdAsString } from "~/lib/validations/shared/queryIdString";
+import { schemaWebhookReadPublic } from "~/lib/validations/webhook";
+
+/**
+ * @swagger
+ * /webhooks/{id}:
+ * get:
+ * summary: Find a webhook
+ * operationId: getWebhookById
+ * parameters:
+ * - in: path
+ * name: id
+ * schema:
+ * type: integer
+ * required: true
+ * description: Numeric ID of the webhook to get
+ * - in: query
+ * name: apiKey
+ * required: true
+ * schema:
+ * type: string
+ * description: Your API key
+ * tags:
+ * - webhooks
+ * externalDocs:
+ * url: https://docs.cal.com/core-features/webhooks
+ * responses:
+ * 200:
+ * description: OK
+ * 401:
+ * description: Authorization information is missing or invalid.
+ * 404:
+ * description: Webhook was not found
+ */
+export async function getHandler(req: NextApiRequest) {
+ const { prisma, query } = req;
+ const { id } = schemaQueryIdAsString.parse(query);
+ const data = await prisma.webhook.findUniqueOrThrow({ where: { id } });
+ return { webhook: schemaWebhookReadPublic.parse(data) };
+}
+
+export default defaultResponder(getHandler);
diff --git a/apps/api/apps/api/pages/api/webhooks/[id]/_patch.ts b/apps/api/apps/api/pages/api/webhooks/[id]/_patch.ts
new file mode 100644
index 0000000000..35c2810f39
--- /dev/null
+++ b/apps/api/apps/api/pages/api/webhooks/[id]/_patch.ts
@@ -0,0 +1,91 @@
+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 { schemaQueryIdAsString } from "~/lib/validations/shared/queryIdString";
+import { schemaWebhookEditBodyParams, schemaWebhookReadPublic } from "~/lib/validations/webhook";
+
+/**
+ * @swagger
+ * /webhooks/{id}:
+ * patch:
+ * summary: Edit an existing webhook
+ * operationId: editWebhookById
+ * parameters:
+ * - in: path
+ * name: id
+ * schema:
+ * type: integer
+ * required: true
+ * description: Numeric ID of the webhook to edit
+ * - in: query
+ * name: apiKey
+ * required: true
+ * schema:
+ * type: string
+ * description: Your API key
+ * requestBody:
+ * description: Edit an existing webhook
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * subscriberUrl:
+ * type: string
+ * format: uri
+ * description: The URL to subscribe to this webhook
+ * eventTriggers:
+ * type: string
+ * enum: [BOOKING_CREATED, BOOKING_RESCHEDULED, BOOKING_CANCELLED, MEETING_ENDED]
+ * description: The events which should trigger this webhook call
+ * active:
+ * type: boolean
+ * description: Whether the webhook is active and should trigger on associated trigger events
+ * payloadTemplate:
+ * type: string
+ * description: The template of the webhook's payload
+ * eventTypeId:
+ * type: number
+ * description: The event type ID if this webhook should be associated with only that event type
+ * tags:
+ * - webhooks
+ * externalDocs:
+ * url: https://docs.cal.com/core-features/webhooks
+ * responses:
+ * 201:
+ * description: OK, webhook edited successfully
+ * 400:
+ * description: Bad request. Webhook body is invalid.
+ * 401:
+ * description: Authorization information is missing or invalid.
+ */
+export async function patchHandler(req: NextApiRequest) {
+ const { prisma, query, userId, isAdmin } = req;
+ const { id } = schemaQueryIdAsString.parse(query);
+ const { eventTypeId, userId: bodyUserId, ...data } = schemaWebhookEditBodyParams.parse(req.body);
+ const args: Prisma.WebhookUpdateArgs = { where: { id }, data };
+
+ if (eventTypeId) {
+ const where: Prisma.EventTypeWhereInput = { id: eventTypeId };
+ if (!isAdmin) where.userId = userId;
+ await prisma.eventType.findFirstOrThrow({ where });
+ args.data.eventTypeId = eventTypeId;
+ }
+
+ 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.webhook.update(args);
+ return { webhook: schemaWebhookReadPublic.parse(result) };
+}
+
+export default defaultResponder(patchHandler);
diff --git a/apps/api/apps/api/pages/api/webhooks/[id]/index.ts b/apps/api/apps/api/pages/api/webhooks/[id]/index.ts
new file mode 100644
index 0000000000..727ad02843
--- /dev/null
+++ b/apps/api/apps/api/pages/api/webhooks/[id]/index.ts
@@ -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);
+ })
+);
diff --git a/apps/api/apps/api/pages/api/webhooks/_get.ts b/apps/api/apps/api/pages/api/webhooks/_get.ts
new file mode 100644
index 0000000000..8708c303e8
--- /dev/null
+++ b/apps/api/apps/api/pages/api/webhooks/_get.ts
@@ -0,0 +1,54 @@
+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 { schemaQuerySingleOrMultipleUserIds } from "~/lib/validations/shared/queryUserId";
+import { schemaWebhookReadPublic } from "~/lib/validations/webhook";
+
+/**
+ * @swagger
+ * /webhooks:
+ * get:
+ * summary: Find all webhooks
+ * operationId: listWebhooks
+ * parameters:
+ * - in: query
+ * name: apiKey
+ * required: true
+ * schema:
+ * type: string
+ * description: Your API key
+ * tags:
+ * - webhooks
+ * externalDocs:
+ * url: https://docs.cal.com/core-features/webhooks
+ * responses:
+ * 200:
+ * description: OK
+ * 401:
+ * description: Authorization information is missing or invalid.
+ * 404:
+ * description: No webhooks were found
+ */
+async function getHandler(req: NextApiRequest) {
+ const { userId, isAdmin, prisma } = req;
+ const args: Prisma.WebhookFindManyArgs = isAdmin
+ ? {}
+ : { where: { OR: [{ eventType: { userId } }, { 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 = { OR: [{ eventType: { userId: { in: userIds } } }, { userId: { in: userIds } }] };
+ if (Array.isArray(query.userId)) args.orderBy = { userId: "asc", eventType: { userId: "asc" } };
+ }
+
+ const data = await prisma.webhook.findMany(args);
+ return { webhooks: data.map((v) => schemaWebhookReadPublic.parse(v)) };
+}
+
+export default defaultResponder(getHandler);
diff --git a/apps/api/apps/api/pages/api/webhooks/_post.ts b/apps/api/apps/api/pages/api/webhooks/_post.ts
new file mode 100644
index 0000000000..2a99c903e8
--- /dev/null
+++ b/apps/api/apps/api/pages/api/webhooks/_post.ts
@@ -0,0 +1,95 @@
+import type { Prisma } from "@prisma/client";
+import type { NextApiRequest } from "next";
+import { v4 as uuidv4 } from "uuid";
+
+import { HttpError } from "@calcom/lib/http-error";
+import { defaultResponder } from "@calcom/lib/server";
+
+import { schemaWebhookCreateBodyParams, schemaWebhookReadPublic } from "~/lib/validations/webhook";
+
+/**
+ * @swagger
+ * /webhooks:
+ * post:
+ * summary: Creates a new webhook
+ * operationId: addWebhook
+ * parameters:
+ * - in: query
+ * name: apiKey
+ * required: true
+ * schema:
+ * type: string
+ * description: Your API key
+ * requestBody:
+ * description: Create a new webhook
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * required:
+ * - subscriberUrl
+ * - eventTriggers
+ * - active
+ * properties:
+ * subscriberUrl:
+ * type: string
+ * format: uri
+ * description: The URL to subscribe to this webhook
+ * eventTriggers:
+ * type: string
+ * enum: [BOOKING_CREATED, BOOKING_RESCHEDULED, BOOKING_CANCELLED, MEETING_ENDED]
+ * description: The events which should trigger this webhook call
+ * active:
+ * type: boolean
+ * description: Whether the webhook is active and should trigger on associated trigger events
+ * payloadTemplate:
+ * type: string
+ * description: The template of the webhook's payload
+ * eventTypeId:
+ * type: number
+ * description: The event type ID if this webhook should be associated with only that event type
+ * tags:
+ * - webhooks
+ * externalDocs:
+ * url: https://docs.cal.com/core-features/webhooks
+ * responses:
+ * 201:
+ * description: OK, webhook created
+ * 400:
+ * description: Bad request. webhook body is invalid.
+ * 401:
+ * description: Authorization information is missing or invalid.
+ */
+async function postHandler(req: NextApiRequest) {
+ const { userId, isAdmin, prisma } = req;
+ const { eventTypeId, userId: bodyUserId, ...body } = schemaWebhookCreateBodyParams.parse(req.body);
+ const args: Prisma.WebhookCreateArgs = { data: { id: uuidv4(), ...body } };
+
+ // If no event type, we assume is for the current user. If admin we run more checks below...
+ if (!eventTypeId) args.data.userId = userId;
+
+ if (eventTypeId) {
+ const where: Prisma.EventTypeWhereInput = { id: eventTypeId };
+ if (!isAdmin) where.userId = userId;
+ await prisma.eventType.findFirstOrThrow({ where });
+ args.data.eventTypeId = eventTypeId;
+ }
+
+ 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.webhook.create(args);
+
+ return {
+ webhook: schemaWebhookReadPublic.parse(data),
+ message: "Webhook created successfully",
+ };
+}
+
+export default defaultResponder(postHandler);
diff --git a/apps/api/apps/api/pages/api/webhooks/index.ts b/apps/api/apps/api/pages/api/webhooks/index.ts
new file mode 100644
index 0000000000..2a15abfa5b
--- /dev/null
+++ b/apps/api/apps/api/pages/api/webhooks/index.ts
@@ -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"),
+ })
+);
diff --git a/apps/api/apps/api/scripts/vercel-deploy.sh b/apps/api/apps/api/scripts/vercel-deploy.sh
new file mode 100755
index 0000000000..689616931c
--- /dev/null
+++ b/apps/api/apps/api/scripts/vercel-deploy.sh
@@ -0,0 +1,66 @@
+# github submodule repo addresses without https:// prefix
+BRANCH_TO_CLONE=""
+SUBMODULE_GITHUB=github.com/calcom/api
+SUBMODULE_PATH=apps/api
+COMMIT=$VERCEL_GIT_COMMIT_SHA
+
+if [ "$VERCEL_GIT_COMMIT_SHA" == "" ]; then
+ echo "Error: VERCEL_GIT_COMMIT_SHA is empty"
+ exit 0
+fi
+
+# github access token is necessary
+# add it to Environment Variables on Vercel
+if [ "$GITHUB_ACCESS_TOKEN" == "" ]; then
+ echo "Error: GITHUB_ACCESS_TOKEN is empty"
+ exit 0
+fi
+
+# We add an exception to test on staging
+if [ "$VERCEL_GIT_COMMIT_REF" == "production" ]; then
+ BRANCH_TO_CLONE="-b $VERCEL_GIT_COMMIT_REF"
+fi
+if [ "$VERCEL_GIT_COMMIT_REF" == "staging" ]; then
+ BRANCH_TO_CLONE="-b $VERCEL_GIT_COMMIT_REF"
+fi
+
+# stop execution on error - don't let it build if something goes wrong
+set -e
+
+git config --global init.defaultBranch main
+git config --global advice.detachedHead false
+
+# set up an empty temporary work directory
+rm -rf ..?* .[!.]* * || true
+
+# checkout the current commit
+git clone $BRANCH_TO_CLONE https://$GITHUB_ACCESS_TOKEN@github.com/calcom/cal.com.git .
+
+echo "Cloned"
+
+# Ensure the submodule directory exists
+mkdir -p $SUBMODULE_PATH
+
+# set up an empty temporary work directory
+rm -rf tmp || true # remove the tmp folder if exists
+mkdir tmp # create the tmp folder
+cd tmp # go into the tmp folder
+
+# checkout the current submodule commit
+git init # initialise empty repo
+git remote add $SUBMODULE_PATH https://$GITHUB_ACCESS_TOKEN@$SUBMODULE_GITHUB # add origin of the submodule
+git fetch --depth=1 $SUBMODULE_PATH $COMMIT # fetch only the required version
+git checkout $COMMIT # checkout on the right commit
+
+# move the submodule from tmp to the submodule path
+cd .. # go folder up
+rm -rf tmp/.git # remove .git
+mv tmp/* $SUBMODULE_PATH/ # move the submodule to the submodule path
+
+# clean up
+rm -rf tmp # remove the tmp folder
+
+git diff --quiet HEAD^ HEAD ':!/apps/docs/*' ':!/apps/website/*' ':!/apps/web/*' ':!/apps/swagger/*' ':!/apps/console/*'
+
+echo "✅ - Build can proceed"
+exit 1
diff --git a/apps/api/apps/api/test/README.md b/apps/api/apps/api/test/README.md
new file mode 100644
index 0000000000..938d54f0be
--- /dev/null
+++ b/apps/api/apps/api/test/README.md
@@ -0,0 +1,12 @@
+# Unit and Integration Tests
+
+Make sure you have copied .env.test.example to .env.test
+
+You can run all jest tests as
+
+`yarn test`
+
+You can run tests matching specific description by following command
+`yarn test -t _post`
+
+Tip: Use `--watchAll` flag to run tests on every change
diff --git a/apps/api/apps/api/test/docker-compose.yml b/apps/api/apps/api/test/docker-compose.yml
new file mode 100644
index 0000000000..769adab097
--- /dev/null
+++ b/apps/api/apps/api/test/docker-compose.yml
@@ -0,0 +1,15 @@
+# Set the version of docker compose to use
+version: '3.9'
+
+# The containers that compose the project
+services:
+ db:
+ image: postgres:13
+ restart: always
+ container_name: integration-tests-prisma
+ ports:
+ - '5433:5432'
+ environment:
+ POSTGRES_USER: prisma
+ POSTGRES_PASSWORD: prisma
+ POSTGRES_DB: tests
\ No newline at end of file
diff --git a/apps/api/apps/api/test/jest-resolver.js b/apps/api/apps/api/test/jest-resolver.js
new file mode 100644
index 0000000000..d5fb532a29
--- /dev/null
+++ b/apps/api/apps/api/test/jest-resolver.js
@@ -0,0 +1,15 @@
+module.exports = (path, options) => {
+ // Call the defaultResolver, so we leverage its cache, error handling, etc.
+ return options.defaultResolver(path, {
+ ...options,
+ // Use packageFilter to process parsed `package.json` before the resolution (see https://www.npmjs.com/package/resolve#resolveid-opts-cb)
+ packageFilter: (pkg) => {
+ // See https://github.com/microsoft/accessibility-insights-web/blob/40416a4ae6b91baf43102f58e069eff787de4de2/src/tests/common/resolver.js
+ if (pkg.name === "uuid" || pkg.name === "nanoid") {
+ delete pkg["exports"];
+ delete pkg["module"];
+ }
+ return pkg;
+ },
+ });
+};
diff --git a/apps/api/apps/api/test/jest-setup.js b/apps/api/apps/api/test/jest-setup.js
new file mode 100644
index 0000000000..fa5c44868d
--- /dev/null
+++ b/apps/api/apps/api/test/jest-setup.js
@@ -0,0 +1,6 @@
+// This is a workaround for https://github.com/jsdom/jsdom/issues/2524#issuecomment-902027138
+
+// See https://github.com/microsoft/accessibility-insights-web/blob/40416a4ae6b91baf43102f58e069eff787de4de2/src/tests/unit/jest-setup.ts
+const { TextEncoder, TextDecoder } = require("util");
+global.TextEncoder = TextEncoder;
+global.TextDecoder = TextDecoder;
diff --git a/apps/api/apps/api/test/lib/bookings/_post.test.ts b/apps/api/apps/api/test/lib/bookings/_post.test.ts
new file mode 100644
index 0000000000..95bf7a73d5
--- /dev/null
+++ b/apps/api/apps/api/test/lib/bookings/_post.test.ts
@@ -0,0 +1,264 @@
+import type { Request, Response } from "express";
+import type { NextApiRequest, NextApiResponse } from "next";
+import { createMocks } from "node-mocks-http";
+
+import dayjs from "@calcom/dayjs";
+import sendPayload from "@calcom/features/webhooks/lib/sendPayload";
+import { buildBooking, buildEventType, buildWebhook } from "@calcom/lib/test/builder";
+import prisma from "@calcom/prisma";
+
+import { prismaMock } from "../../../../../tests/config/singleton";
+import handler from "../../../pages/api/bookings/_post";
+
+type CustomNextApiRequest = NextApiRequest & Request;
+type CustomNextApiResponse = NextApiResponse & Response;
+jest.mock("@calcom/features/webhooks/lib/sendPayload");
+jest.mock("@calcom/lib/server/i18n", () => {
+ return {
+ getTranslation: (key: string) => key,
+ };
+});
+
+describe("POST /api/bookings", () => {
+ describe("Errors", () => {
+ test("Missing required data", async () => {
+ const { req, res } = createMocks({
+ method: "POST",
+ body: {},
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(400);
+ expect(JSON.parse(res._getData())).toEqual(
+ expect.objectContaining({
+ message:
+ "invalid_type in 'eventTypeId': Required; invalid_type in 'title': Required; invalid_type in 'startTime': Required; invalid_type in 'startTime': Required; invalid_type in 'endTime': Required; invalid_type in 'endTime': Required",
+ })
+ );
+ });
+
+ test("Invalid eventTypeId", async () => {
+ const { req, res } = createMocks({
+ method: "POST",
+ body: {
+ title: "test",
+ eventTypeId: 2,
+ startTime: dayjs().toDate(),
+ endTime: dayjs().add(1, "day").toDate(),
+ },
+ prisma,
+ });
+
+ prismaMock.eventType.findUnique.mockResolvedValue(null);
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(400);
+ expect(JSON.parse(res._getData())).toEqual(
+ expect.objectContaining({
+ message:
+ "'invalid_type' in 'email': Required; 'invalid_type' in 'end': Required; 'invalid_type' in 'location': Required; 'invalid_type' in 'name': Required; 'invalid_type' in 'start': Required; 'invalid_type' in 'timeZone': Required; 'invalid_type' in 'language': Required; 'invalid_type' in 'customInputs': Required; 'invalid_type' in 'metadata': Required",
+ })
+ );
+ });
+
+ test("Missing recurringCount", async () => {
+ const { req, res } = createMocks({
+ method: "POST",
+ body: {
+ title: "test",
+ eventTypeId: 2,
+ startTime: dayjs().toDate(),
+ endTime: dayjs().add(1, "day").toDate(),
+ },
+ prisma,
+ });
+
+ prismaMock.eventType.findUnique.mockResolvedValue(
+ buildEventType({ recurringEvent: { freq: 2, count: 12, interval: 1 } })
+ );
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(400);
+ expect(JSON.parse(res._getData())).toEqual(
+ expect.objectContaining({
+ message:
+ "'invalid_type' in 'email': Required; 'invalid_type' in 'end': Required; 'invalid_type' in 'location': Required; 'invalid_type' in 'name': Required; 'invalid_type' in 'start': Required; 'invalid_type' in 'timeZone': Required; 'invalid_type' in 'language': Required; 'invalid_type' in 'customInputs': Required; 'invalid_type' in 'metadata': Required",
+ })
+ );
+ });
+
+ test("Invalid recurringCount", async () => {
+ const { req, res } = createMocks({
+ method: "POST",
+ body: {
+ title: "test",
+ eventTypeId: 2,
+ startTime: dayjs().toDate(),
+ endTime: dayjs().add(1, "day").toDate(),
+ recurringCount: 15,
+ },
+ prisma,
+ });
+
+ prismaMock.eventType.findUnique.mockResolvedValue(
+ buildEventType({ recurringEvent: { freq: 2, count: 12, interval: 1 } })
+ );
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(400);
+ expect(JSON.parse(res._getData())).toEqual(
+ expect.objectContaining({
+ message:
+ "'invalid_type' in 'email': Required; 'invalid_type' in 'end': Required; 'invalid_type' in 'location': Required; 'invalid_type' in 'name': Required; 'invalid_type' in 'start': Required; 'invalid_type' in 'timeZone': Required; 'invalid_type' in 'language': Required; 'invalid_type' in 'customInputs': Required; 'invalid_type' in 'metadata': Required",
+ })
+ );
+ });
+
+ test("No available users", async () => {
+ const { req, res } = createMocks({
+ method: "POST",
+ body: {
+ name: "test",
+ start: dayjs().format(),
+ end: dayjs().add(1, "day").format(),
+ eventTypeId: 2,
+ email: "test@example.com",
+ location: "Cal.com Video",
+ timeZone: "America/Montevideo",
+ language: "en",
+ customInputs: [],
+ metadata: {},
+ userId: 4,
+ },
+ prisma,
+ });
+
+ prismaMock.eventType.findUniqueOrThrow.mockResolvedValue(buildEventType());
+
+ await handler(req, res);
+ console.log({ statusCode: res._getStatusCode(), data: JSON.parse(res._getData()) });
+
+ expect(res._getStatusCode()).toBe(500);
+ expect(JSON.parse(res._getData())).toEqual(
+ expect.objectContaining({
+ message: "No available users found.",
+ })
+ );
+ });
+ });
+
+ xdescribe("Success", () => {
+ describe("Regular event-type", () => {
+ test("Creates one single booking", async () => {
+ const { req, res } = createMocks({
+ method: "POST",
+ body: {
+ name: "test",
+ start: dayjs().format(),
+ end: dayjs().add(1, "day").format(),
+ eventTypeId: 2,
+ email: "test@example.com",
+ location: "Cal.com Video",
+ timeZone: "America/Montevideo",
+ language: "en",
+ customInputs: [],
+ metadata: {},
+ userId: 4,
+ },
+ prisma,
+ });
+
+ prismaMock.eventType.findUniqueOrThrow.mockResolvedValue(buildEventType());
+ prismaMock.booking.findMany.mockResolvedValue([]);
+
+ await handler(req, res);
+ console.log({ statusCode: res._getStatusCode(), data: JSON.parse(res._getData()) });
+
+ expect(prismaMock.booking.create).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("Recurring event-type", () => {
+ test("Creates multiple bookings", async () => {
+ const { req, res } = createMocks({
+ method: "POST",
+ body: {
+ title: "test",
+ eventTypeId: 2,
+ startTime: dayjs().toDate(),
+ endTime: dayjs().add(1, "day").toDate(),
+ recurringCount: 12,
+ },
+ prisma,
+ });
+
+ prismaMock.eventType.findUnique.mockResolvedValue(
+ buildEventType({ recurringEvent: { freq: 2, count: 12, interval: 1 } })
+ );
+
+ Array.from(Array(12).keys()).map(async () => {
+ prismaMock.booking.create.mockResolvedValue(buildBooking());
+ });
+
+ prismaMock.webhook.findMany.mockResolvedValue([]);
+
+ await handler(req, res);
+ const data = JSON.parse(res._getData());
+
+ expect(prismaMock.booking.create).toHaveBeenCalledTimes(12);
+ expect(res._getStatusCode()).toBe(201);
+ expect(data.message).toEqual("Bookings created successfully.");
+ expect(data.bookings.length).toEqual(12);
+ });
+ });
+ test("Notifies multiple bookings", async () => {
+ const { req, res } = createMocks({
+ method: "POST",
+ body: {
+ title: "test",
+ eventTypeId: 2,
+ startTime: dayjs().toDate(),
+ endTime: dayjs().add(1, "day").toDate(),
+ recurringCount: 12,
+ },
+ prisma,
+ });
+
+ prismaMock.eventType.findUnique.mockResolvedValue(
+ buildEventType({ recurringEvent: { freq: 2, count: 12, interval: 1 } })
+ );
+
+ const createdAt = new Date();
+ Array.from(Array(12).keys()).map(async () => {
+ prismaMock.booking.create.mockResolvedValue(buildBooking({ createdAt }));
+ });
+
+ const mockedWebhooks = [
+ buildWebhook({
+ subscriberUrl: "http://mockedURL1.com",
+ createdAt,
+ eventTypeId: 1,
+ secret: "secret1",
+ }),
+ buildWebhook({
+ subscriberUrl: "http://mockedURL2.com",
+ createdAt,
+ eventTypeId: 2,
+ secret: "secret2",
+ }),
+ ];
+ prismaMock.webhook.findMany.mockResolvedValue(mockedWebhooks);
+
+ await handler(req, res);
+ const data = JSON.parse(res._getData());
+
+ expect(sendPayload).toHaveBeenCalledTimes(24);
+ expect(data.message).toEqual("Bookings created successfully.");
+ expect(data.bookings.length).toEqual(12);
+ });
+ });
+});
diff --git a/apps/api/apps/api/tsconfig.json b/apps/api/apps/api/tsconfig.json
new file mode 100644
index 0000000000..c6b3666313
--- /dev/null
+++ b/apps/api/apps/api/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "extends": "@calcom/tsconfig/nextjs.json",
+ "compilerOptions": {
+ "strict": true,
+ "jsx": "preserve",
+ "baseUrl": ".",
+ "paths": {
+ "~/*": ["*"],
+ "@prisma/client/*": ["@calcom/prisma/client/*"]
+ }
+ },
+ "include": [
+ "next-env.d.ts",
+ "**/*.ts",
+ "**/*.tsx",
+ "../../packages/types/*.d.ts",
+ "../../packages/types/next-auth.d.ts"
+ ],
+ "exclude": ["node_modules", "templates", "auth"]
+}