Compare commits

..
Author SHA1 Message Date
Alex van Andel da67be475f chore: release v5.8.2
Post release / release (push) Canceled after 0s
2025-10-22 14:20:43 +01:00
684 changed files with 3204 additions and 17776 deletions
-36
View File
@@ -1,36 +0,0 @@
# Dependencies
node_modules
**/node_modules
# Build outputs
.next
**/.next
dist
**/dist
build
**/build
# Git
.git
.github
# Testing
coverage
**/coverage
test-results
**/test-results
.turbo
**/.turbo
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# OS
.DS_Store
Thumbs.db
# Examples and docs
docs
-3
View File
@@ -486,6 +486,3 @@ CALCOM_SERVICE_ACCOUNT_ENCRYPTION_KEY=
SALESFORCE_GRAPHQL_DELAY_MS=500 SALESFORCE_GRAPHQL_DELAY_MS=500
SALESFORCE_GRAPHQL_MAX_DELAY_MS=2000 SALESFORCE_GRAPHQL_MAX_DELAY_MS=2000
SALESFORCE_GRAPHQL_MAX_RETRIES=3 SALESFORCE_GRAPHQL_MAX_RETRIES=3
# Force Node.js to use UTC as process timezone
TZ=UTC
+1 -1
View File
@@ -26,7 +26,7 @@ runs:
with: with:
path: ${{ inputs.path }} path: ${{ inputs.path }}
key: ${{ runner.os }}-${{ env.cache-name }}-${{ inputs.path }}-${{ env.key-1 }}-${{ env.key-2 }}-${{ env.key-3 }} key: ${{ runner.os }}-${{ env.cache-name }}-${{ inputs.path }}-${{ env.key-1 }}-${{ env.key-2 }}-${{ env.key-3 }}
- run: USE_POOL=true yarn db-seed - run: echo ${{ env.E2E_TEST_CALCOM_QA_GCAL_CREDENTIALS }} && yarn db-seed
if: steps.cache-db.outputs.cache-hit != 'true' if: steps.cache-db.outputs.cache-hit != 'true'
shell: bash shell: bash
- name: Postgres Dump Backup - name: Postgres Dump Backup
@@ -1,182 +0,0 @@
name: "Docker Build and Test"
description: "Reusable action to build and test Docker images for Cal.com"
inputs:
platform:
description: "Target platform (linux/amd64 or arm64)"
required: true
platform-suffix:
description: "Suffix to add to image tags (e.g., -arm)"
required: false
default: ""
dockerhub-username:
description: "Docker Hub username"
required: true
dockerhub-token:
description: "Docker Hub token"
required: true
github-token:
description: "GitHub token for GHCR"
required: true
postgres-user:
description: "PostgreSQL user"
required: true
postgres-password:
description: "PostgreSQL password"
required: true
postgres-db:
description: "PostgreSQL database name"
required: true
database-host:
description: "Database host"
required: true
push-image:
description: "Whether to push the built image"
required: false
default: "false"
runs:
using: "composite"
steps:
- name: Log in to the Docker Hub registry
uses: docker/login-action@v3
with:
username: ${{ inputs.dockerhub-username }}
password: ${{ inputs.dockerhub-token }}
logout: true
- name: Log in to the Github Container registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ inputs.github-token }}
- name: Docker meta
id: meta
uses: docker/metadata-action@v5
with:
images: |
docker.io/calendso/calendso
docker.io/calcom/cal.com
ghcr.io/calcom/cal.com
flavor: |
latest=${{ !github.event.release.prerelease }}
suffix=${{ inputs.platform-suffix }}
- name: Copy env
shell: bash
run: |
grep -o '^[^#]*' .env.example > .env
cat .env >> $GITHUB_ENV
echo "DATABASE_HOST=localhost:5432" >> $GITHUB_ENV
eval $(sed -e '/^#/d' -e 's/^/export /' -e 's/$/;/' .env) ;
- name: Start database
shell: bash
run: |
docker compose up -d database
- name: Show database logs and container status
shell: bash
run: |
echo "--- Container Status ---"
docker compose ps database
echo "--- Container Logs ---"
docker compose logs database
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
driver-opts: |
network=container:database
buildkitd-flags: |
--allow-insecure-entitlement security.insecure --allow-insecure-entitlement network.host
- name: Build image
id: docker_build
uses: docker/build-push-action@v6
with:
context: ./
file: ./Dockerfile
load: true
push: false
platforms: ${{ inputs.platform }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
NEXT_PUBLIC_WEBAPP_URL=http://localhost:3000
NEXT_PUBLIC_API_V2_URL=http://localhost:5555/api/v2
NEXT_PUBLIC_LICENSE_CONSENT=agree
DATABASE_URL=postgresql://${{ inputs.postgres-user }}:${{ inputs.postgres-password }}@${{ inputs.database-host }}/${{ inputs.postgres-db }}
DATABASE_DIRECT_URL=postgresql://${{ inputs.postgres-user }}:${{ inputs.postgres-password }}@${{ inputs.database-host }}/${{ inputs.postgres-db }}
- name: Test runtime
shell: bash
run: |
tags="${{ steps.meta.outputs.tags }}"
IFS=',' read -ra ADDR <<< "$tags"
tag=${ADDR[0]}
docker run --rm --network stack \
-p 3000:3000 \
-e DATABASE_URL=postgresql://${{ inputs.postgres-user }}:${{ inputs.postgres-password }}@database/${{ inputs.postgres-db }} \
-e DATABASE_DIRECT_URL=postgresql://${{ inputs.postgres-user }}:${{ inputs.postgres-password }}@database/${{ inputs.postgres-db }} \
-e NEXTAUTH_SECRET=${{ env.NEXTAUTH_SECRET }} \
-e CALENDSO_ENCRYPTION_KEY=${{ env.CALENDSO_ENCRYPTION_KEY }} \
$tag &
server_pid=$!
echo "Waiting for the server to start..."
sleep 120
echo http://localhost:3000/auth/login
for i in {1..60}; do
echo "Checking server health ($i/60)..."
response=$(curl -o /dev/null -s -w "%{http_code}" http://localhost:3000/auth/login)
echo "HTTP Status Code: $response"
if [[ "$response" == "200" ]] || [[ "$response" == "307" ]]; then
echo "Server is healthy"
kill $server_pid
exit 0
fi
sleep 1
done
echo "Server health check failed"
kill $server_pid
exit 1
env:
NEXTAUTH_SECRET: "EI4qqDpcfdvf4A+0aQEEx8JjHxHSy4uWiZw/F32K+pA="
CALENDSO_ENCRYPTION_KEY: "0zfLtY99wjeLnsM7qsa8xsT+Q0oSgnOL"
- name: Push image
id: docker_push
uses: docker/build-push-action@v6
if: ${{ inputs.push-image == 'true' && !github.event.release.prerelease }}
with:
context: ./
file: ./Dockerfile
push: true
platforms: ${{ inputs.platform }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
NEXT_PUBLIC_WEBAPP_URL=http://localhost:3000
NEXT_PUBLIC_API_V2_URL=http://localhost:5555/api/v2
NEXT_PUBLIC_LICENSE_CONSENT=agree
DATABASE_URL=postgresql://${{ inputs.postgres-user }}:${{ inputs.postgres-password }}@${{ inputs.database-host }}/${{ inputs.postgres-db }}
DATABASE_DIRECT_URL=postgresql://${{ inputs.postgres-user }}:${{ inputs.postgres-password }}@${{ inputs.database-host }}/${{ inputs.postgres-db }}
- name: Image digest
shell: bash
run: echo ${{ steps.docker_build.outputs.digest }}
- name: Cleanup
shell: bash
if: always()
run: |
docker compose down
@@ -56,8 +56,8 @@ jobs:
if: steps.cache-api-v2-build.outputs.cache-hit != 'true' if: steps.cache-api-v2-build.outputs.cache-hit != 'true'
run: | run: |
export NODE_OPTIONS="--max_old_space_size=8192" export NODE_OPTIONS="--max_old_space_size=8192"
yarn workspace @calcom/api-v2 run generate-schemas && yarn workspace @calcom/api-v2 run generate-schemas
rm -rf apps/api/v2/node_modules && rm -rf apps/api/v2/node_modules
yarn install && yarn install
yarn workspace @calcom/api-v2 run build yarn workspace @calcom/api-v2 run build
shell: bash shell: bash
+8 -15
View File
@@ -6,31 +6,23 @@ on:
- main - main
concurrency: ${{ github.workflow }}-${{ github.ref }} concurrency: ${{ github.workflow }}-${{ github.ref }}
permissions: permissions: {} # remove permissions and set explicitly under "permissions:" below
id-token: write # for NPM provenance - developers can verify where and how it was built
contents: write # to create release by changesets/action below
pull-requests: write # to create pull request by changesets/action below
jobs: jobs:
release: release:
if: github.repository == 'calcom/cal.com' # prevent this action from running on forks if: github.repository == 'calcom/cal.com' # prevent this action from running on forks
permissions:
id-token: write # for NPM provenance - developers can verify where and how it was built
contents: write # to create release by changesets/action below
pull-requests: write # to create pull request by changesets/action below
name: Release name: Release
runs-on: ubuntu-latest runs-on: buildjet-4vcpu-ubuntu-2204
steps: steps:
- name: Checkout Repo - name: Checkout Repo
uses: actions/checkout@v4 uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Setup Node and registry for OIDC
uses: actions/setup-node@v4
with:
node-version: "20.17.0"
registry-url: "https://registry.npmjs.org"
always-auth: false
- name: Setup node, yarn and install dependencies - name: Setup node, yarn and install dependencies
uses: ./.github/actions/yarn-install uses: ./.github/actions/yarn-install
- name: Install npm at version supporting OIDC
run: npm install -g npm@11.5.1
- name: Create Release Pull Request or Publish to npm - name: Create Release Pull Request or Publish to npm
id: changesets id: changesets
uses: changesets/action@v1 uses: changesets/action@v1
@@ -41,7 +33,8 @@ jobs:
title: "chore: version packages" # PR title title: "chore: version packages" # PR title
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_CONFIG_PROVENANCE: "true" NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
VITE_BOOKER_EMBED_OAUTH_CLIENT_ID: ${{ secrets.VITE_BOOKER_EMBED_OAUTH_CLIENT_ID }} VITE_BOOKER_EMBED_OAUTH_CLIENT_ID: ${{ secrets.VITE_BOOKER_EMBED_OAUTH_CLIENT_ID }}
VITE_BOOKER_EMBED_API_URL: ${{ secrets.VITE_BOOKER_EMBED_API_URL }} VITE_BOOKER_EMBED_API_URL: ${{ secrets.VITE_BOOKER_EMBED_API_URL }}
NEXT_PUBLIC_WEBAPP_URL: ${{ secrets.NEXT_PUBLIC_WEBAPP_URL }} NEXT_PUBLIC_WEBAPP_URL: ${{ secrets.NEXT_PUBLIC_WEBAPP_URL }}
+4 -4
View File
@@ -20,8 +20,8 @@ jobs:
days-before-close: -1 days-before-close: -1
days-before-issue-stale: 60 days-before-issue-stale: 60
days-before-issue-close: -1 days-before-issue-close: -1
days-before-pr-stale: 7 days-before-pr-stale: 14
days-before-pr-close: 14 days-before-pr-close: -1
stale-pr-message: "This PR has been marked as stale due to inactivity. If you're still working on it or need any help, please let us know or update the PR to keep it active." stale-pr-message: "This PR is being marked as stale due to inactivity."
close-pr-message: "This PR has been closed due to inactivity. Please feel free to reopen it if you'd like to continue the work." close-pr-message: "This PR is being closed due to inactivity. Please reopen if work is intended to be continued."
operations-per-run: 100 operations-per-run: 100
@@ -16,6 +16,7 @@ env:
CALENDSO_ENCRYPTION_KEY: ${{ secrets.CI_CALENDSO_ENCRYPTION_KEY }} CALENDSO_ENCRYPTION_KEY: ${{ secrets.CI_CALENDSO_ENCRYPTION_KEY }}
DAILY_API_KEY: ${{ secrets.CI_DAILY_API_KEY }} DAILY_API_KEY: ${{ secrets.CI_DAILY_API_KEY }}
DATABASE_URL: ${{ secrets.CI_DATABASE_URL }} DATABASE_URL: ${{ secrets.CI_DATABASE_URL }}
DATABASE_DIRECT_URL: ${{ secrets.CI_DATABASE_URL }}
E2E_TEST_APPLE_CALENDAR_EMAIL: ${{ secrets.E2E_TEST_APPLE_CALENDAR_EMAIL }} E2E_TEST_APPLE_CALENDAR_EMAIL: ${{ secrets.E2E_TEST_APPLE_CALENDAR_EMAIL }}
E2E_TEST_APPLE_CALENDAR_PASSWORD: ${{ secrets.E2E_TEST_APPLE_CALENDAR_PASSWORD }} E2E_TEST_APPLE_CALENDAR_PASSWORD: ${{ secrets.E2E_TEST_APPLE_CALENDAR_PASSWORD }}
E2E_TEST_MAILHOG_ENABLED: ${{ vars.E2E_TEST_MAILHOG_ENABLED }} E2E_TEST_MAILHOG_ENABLED: ${{ vars.E2E_TEST_MAILHOG_ENABLED }}
@@ -10,6 +10,7 @@ env:
CALENDSO_ENCRYPTION_KEY: ${{ secrets.CI_CALENDSO_ENCRYPTION_KEY }} CALENDSO_ENCRYPTION_KEY: ${{ secrets.CI_CALENDSO_ENCRYPTION_KEY }}
DAILY_API_KEY: ${{ secrets.CI_DAILY_API_KEY }} DAILY_API_KEY: ${{ secrets.CI_DAILY_API_KEY }}
DATABASE_URL: ${{ secrets.CI_DATABASE_URL }} DATABASE_URL: ${{ secrets.CI_DATABASE_URL }}
DATABASE_DIRECT_URL: ${{ secrets.CI_DATABASE_URL }}
E2E_TEST_APPLE_CALENDAR_EMAIL: ${{ secrets.E2E_TEST_APPLE_CALENDAR_EMAIL }} E2E_TEST_APPLE_CALENDAR_EMAIL: ${{ secrets.E2E_TEST_APPLE_CALENDAR_EMAIL }}
E2E_TEST_APPLE_CALENDAR_PASSWORD: ${{ secrets.E2E_TEST_APPLE_CALENDAR_PASSWORD }} E2E_TEST_APPLE_CALENDAR_PASSWORD: ${{ secrets.E2E_TEST_APPLE_CALENDAR_PASSWORD }}
GOOGLE_API_CREDENTIALS: ${{ secrets.CI_GOOGLE_API_CREDENTIALS }} GOOGLE_API_CREDENTIALS: ${{ secrets.CI_GOOGLE_API_CREDENTIALS }}
@@ -35,6 +36,7 @@ env:
NEXT_PUBLIC_API_V2_ROOT_URL: ${{ secrets.CI_NEXT_PUBLIC_API_V2_ROOT_URL }} NEXT_PUBLIC_API_V2_ROOT_URL: ${{ secrets.CI_NEXT_PUBLIC_API_V2_ROOT_URL }}
NEXT_PUBLIC_ORG_SELF_SERVE_ENABLED: ${{ vars.CI_NEXT_PUBLIC_ORG_SELF_SERVE_ENABLED }} NEXT_PUBLIC_ORG_SELF_SERVE_ENABLED: ${{ vars.CI_NEXT_PUBLIC_ORG_SELF_SERVE_ENABLED }}
jobs: jobs:
build: build:
name: Build Web App name: Build Web App
+29 -91
View File
@@ -1,15 +1,10 @@
name: "Release Docker" name: "Release Docker"
env: on: # yamllint disable-line rule:truthy
POSTGRES_USER: "unicorn_user" release:
POSTGRES_PASSWORD: "magical_password" types:
POSTGRES_DB: "calendso" - created
DATABASE_HOST: "database:5432" - published
on:
push:
tags:
- "v*"
# in case manual trigger is needed # in case manual trigger is needed
workflow_dispatch: workflow_dispatch:
inputs: inputs:
@@ -17,9 +12,11 @@ on:
description: "v{Major}.{Minor}.{Patch}" description: "v{Major}.{Minor}.{Patch}"
jobs: jobs:
release-amd64: release:
name: "Release AMD64" name: "Remote Release"
runs-on: buildjet-4vcpu-ubuntu-2204
runs-on: "ubuntu-latest"
steps: steps:
- name: checkout - name: checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -27,84 +24,25 @@ jobs:
- name: "Determine tag" - name: "Determine tag"
run: 'echo "RELEASE_TAG=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV' run: 'echo "RELEASE_TAG=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV'
- name: Build and test Docker image - name: "Run remote release workflow"
uses: ./.github/actions/docker-build-and-test uses: "actions/github-script@v6"
with: with:
platform: "linux/amd64" # Requires a personal access token with Actions Read and write permissions on calcom/docker.
platform-suffix: "" github-token: "${{ secrets.DOCKER_REPO_ACCESS_TOKEN }}"
dockerhub-username: ${{ secrets.DOCKERHUB_USERNAME }} script: |
dockerhub-token: ${{ secrets.DOCKERHUB_TOKEN }} try {
github-token: ${{ secrets.GITHUB_TOKEN }} const response = await github.rest.actions.createWorkflowDispatch({
postgres-user: ${{ env.POSTGRES_USER }} owner: context.repo.owner,
postgres-password: ${{ env.POSTGRES_PASSWORD }} repo: 'docker',
postgres-db: ${{ env.POSTGRES_DB }} workflow_id: 'create-release.yaml',
database-host: ${{ env.DATABASE_HOST }} ref: 'main',
push-image: "true" inputs: {
"RELEASE_TAG": process.env.RELEASE_TAG
},
});
- name: Notify Slack on Success console.log(response);
if: success() } catch (error) {
uses: slackapi/slack-github-action@v1.24.0 console.error(error);
with: core.setFailed(error.message);
payload: |
{
"text": ":large_green_circle: Workflow *${{ github.workflow }}* (AMD64) succeeded in job *${{ github.job }}*.\nSee: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
} }
env:
SLACK_WEBHOOK_URL: ${{ secrets.CI_SLACK_WEBHOOK_URL }}
- name: Notify Slack on Failure
if: failure()
uses: slackapi/slack-github-action@v1.24.0
with:
payload: |
{
"text": ":red_circle: Workflow *${{ github.workflow }}* (AMD64) failed in job *${{ github.job }}*.\nSee: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.CI_SLACK_WEBHOOK_URL }}
release-arm:
name: "Release ARM"
runs-on: ubuntu-24.04-arm
steps:
- name: checkout
uses: actions/checkout@v4
- name: "Determine tag"
run: 'echo "RELEASE_TAG=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV'
- name: Build and test Docker image
uses: ./.github/actions/docker-build-and-test
with:
platform: "arm64"
platform-suffix: "-arm"
dockerhub-username: ${{ secrets.DOCKERHUB_USERNAME }}
dockerhub-token: ${{ secrets.DOCKERHUB_TOKEN }}
github-token: ${{ secrets.GITHUB_TOKEN }}
postgres-user: ${{ env.POSTGRES_USER }}
postgres-password: ${{ env.POSTGRES_PASSWORD }}
postgres-db: ${{ env.POSTGRES_DB }}
database-host: ${{ env.DATABASE_HOST }}
push-image: "true"
- name: Notify Slack on Success
if: success()
uses: slackapi/slack-github-action@v1.24.0
with:
payload: |
{
"text": ":large_green_circle: Workflow *${{ github.workflow }}* (ARM) succeeded in job *${{ github.job }}*.\nSee: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.CI_SLACK_WEBHOOK_URL }}
- name: Notify Slack on Failure
if: failure()
uses: slackapi/slack-github-action@v1.24.0
with:
payload: |
{
"text": ":red_circle: Workflow *${{ github.workflow }}* (ARM) failed in job *${{ github.job }}*.\nSee: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.CI_SLACK_WEBHOOK_URL }}
-3
View File
@@ -67,9 +67,6 @@ tsconfig.tsbuildinfo
# Prisma generated files # Prisma generated files
packages/prisma/client/* packages/prisma/client/*
!packages/prisma/client/index.ts
apps/api/v2/generated/prisma/*
packages/prisma/generated/prisma/*
packages/prisma/zod/**/*.ts packages/prisma/zod/**/*.ts
packages/prisma/enums packages/prisma/enums
View File
View File
View File
View File
View File
-2
View File
@@ -1,2 +0,0 @@
undecided:
- calcom-monorepo
-91
View File
@@ -1,91 +0,0 @@
FROM --platform=$BUILDPLATFORM node:20 AS builder
WORKDIR /calcom
## If we want to read any ENV variable from .env file, we need to first accept and pass it as an argument to the Dockerfile
ARG NEXT_PUBLIC_LICENSE_CONSENT
ARG NEXT_PUBLIC_WEBSITE_TERMS_URL
ARG NEXT_PUBLIC_WEBSITE_PRIVACY_POLICY_URL
ARG CALCOM_TELEMETRY_DISABLED
ARG DATABASE_URL
ARG NEXTAUTH_SECRET=secret
ARG CALENDSO_ENCRYPTION_KEY=secret
ARG MAX_OLD_SPACE_SIZE=4096
ARG NEXT_PUBLIC_API_V2_URL
ARG CSP_POLICY
## We need these variables as required by Next.js build to create rewrites
ARG NEXT_PUBLIC_SINGLE_ORG_SLUG
ARG ORGANIZATIONS_ENABLED
ENV NEXT_PUBLIC_WEBAPP_URL=http://NEXT_PUBLIC_WEBAPP_URL_PLACEHOLDER \
NEXT_PUBLIC_API_V2_URL=$NEXT_PUBLIC_API_V2_URL \
NEXT_PUBLIC_LICENSE_CONSENT=$NEXT_PUBLIC_LICENSE_CONSENT \
NEXT_PUBLIC_WEBSITE_TERMS_URL=$NEXT_PUBLIC_WEBSITE_TERMS_URL \
NEXT_PUBLIC_WEBSITE_PRIVACY_POLICY_URL=$NEXT_PUBLIC_WEBSITE_PRIVACY_POLICY_URL \
CALCOM_TELEMETRY_DISABLED=$CALCOM_TELEMETRY_DISABLED \
DATABASE_URL=$DATABASE_URL \
DATABASE_DIRECT_URL=$DATABASE_URL \
NEXTAUTH_SECRET=${NEXTAUTH_SECRET} \
CALENDSO_ENCRYPTION_KEY=${CALENDSO_ENCRYPTION_KEY} \
NEXT_PUBLIC_SINGLE_ORG_SLUG=$NEXT_PUBLIC_SINGLE_ORG_SLUG \
ORGANIZATIONS_ENABLED=$ORGANIZATIONS_ENABLED \
NODE_OPTIONS=--max-old-space-size=${MAX_OLD_SPACE_SIZE} \
BUILD_STANDALONE=true \
CSP_POLICY=$CSP_POLICY
COPY package.json yarn.lock .yarnrc.yml playwright.config.ts turbo.json i18n.json ./
COPY .yarn ./.yarn
COPY apps/web ./apps/web
COPY apps/api/v2 ./apps/api/v2
COPY packages ./packages
COPY tests ./tests
RUN yarn config set httpTimeout 1200000
RUN npx turbo prune --scope=@calcom/web --scope=@calcom/trpc --docker
RUN yarn install
# Build and make embed servable from web/public/embed folder
RUN yarn workspace @calcom/trpc run build
RUN yarn --cwd packages/embeds/embed-core workspace @calcom/embed-core run build
RUN yarn --cwd apps/web workspace @calcom/web run build
RUN rm -rf node_modules/.cache .yarn/cache apps/web/.next/cache
FROM node:20 AS builder-two
WORKDIR /calcom
ARG NEXT_PUBLIC_WEBAPP_URL=http://localhost:3000
ENV NODE_ENV=production
COPY package.json .yarnrc.yml turbo.json i18n.json ./
COPY .yarn ./.yarn
COPY --from=builder /calcom/yarn.lock ./yarn.lock
COPY --from=builder /calcom/node_modules ./node_modules
COPY --from=builder /calcom/packages ./packages
COPY --from=builder /calcom/apps/web ./apps/web
COPY --from=builder /calcom/packages/prisma/schema.prisma ./prisma/schema.prisma
COPY scripts scripts
RUN chmod +x scripts/*
# Save value used during this build stage. If NEXT_PUBLIC_WEBAPP_URL and BUILT_NEXT_PUBLIC_WEBAPP_URL differ at
# run-time, then start.sh will find/replace static values again.
ENV NEXT_PUBLIC_WEBAPP_URL=$NEXT_PUBLIC_WEBAPP_URL \
BUILT_NEXT_PUBLIC_WEBAPP_URL=$NEXT_PUBLIC_WEBAPP_URL
RUN scripts/replace-placeholder.sh http://NEXT_PUBLIC_WEBAPP_URL_PLACEHOLDER ${NEXT_PUBLIC_WEBAPP_URL}
FROM node:20 AS runner
WORKDIR /calcom
COPY --from=builder-two /calcom ./
ARG NEXT_PUBLIC_WEBAPP_URL=http://localhost:3000
ENV NEXT_PUBLIC_WEBAPP_URL=$NEXT_PUBLIC_WEBAPP_URL \
BUILT_NEXT_PUBLIC_WEBAPP_URL=$NEXT_PUBLIC_WEBAPP_URL
ENV NODE_ENV=production
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=30s --retries=5 \
CMD wget --spider http://localhost:3000 || exit 1
CMD ["/calcom/scripts/start.sh"]
+7 -262
View File
@@ -4,7 +4,7 @@
<img src="https://user-images.githubusercontent.com/8019099/210054112-5955e812-a76e-4160-9ddd-58f2c72f1cce.png" alt="Logo"> <img src="https://user-images.githubusercontent.com/8019099/210054112-5955e812-a76e-4160-9ddd-58f2c72f1cce.png" alt="Logo">
</a> </a>
<h3 align="center">Cal.com</h3> <h3 align="center">Cal.com (formerly Calendso)</h3>
<p align="center"> <p align="center">
The open-source Calendly successor. The open-source Calendly successor.
@@ -175,7 +175,6 @@ yarn dx
``` ```
#### Development tip #### Development tip
1. Add `export NODE_OPTIONS=“--max-old-space-size=16384”` to your shell script to increase the memory limit for the node process. Alternatively, you can run this in your terminal before running the app. Replace 16384 with the amount of RAM you want to allocate to the node process. 1. Add `export NODE_OPTIONS=“--max-old-space-size=16384”` to your shell script to increase the memory limit for the node process. Alternatively, you can run this in your terminal before running the app. Replace 16384 with the amount of RAM you want to allocate to the node process.
2. Add `NEXT_PUBLIC_LOGGER_LEVEL={level}` to your .env file to control the logging verbosity for all tRPC queries and mutations.\ 2. Add `NEXT_PUBLIC_LOGGER_LEVEL={level}` to your .env file to control the logging verbosity for all tRPC queries and mutations.\
@@ -376,268 +375,15 @@ Executable doesn't exist at /Users/alice/Library/Caches/ms-playwright/chromium-1
### Docker ### Docker
**Official support**: Our team will begin to officially support the Dockerfile and docker-compose resources in this The Docker configuration for Cal.com is an effort powered by people within the community.
repository.
**Important**: Cal.com will **not** be supporting installations that use these Docker resources. While we provide and maintain the Docker configurations, support for Docker-based installations is the responsibility of the user. If you want to contribute to the Docker repository, [reply here](https://github.com/calcom/docker/discussions/32).
This image can be found on DockerHub at [https://hub.docker.com/r/calcom/cal.com](https://hub.docker.com/r/calcom/cal.com). The Docker configuration can be found [in our docker repository](https://github.com/calcom/docker).
**Note for ARM Users**: Use the {version}-arm suffix for pulling images. Example: `docker pull calcom/cal.com:v5.6.19-arm`. Issues with Docker? Find your answer or open a new discussion [here](https://github.com/calcom/docker/discussions) to ask the community.
#### Requirements Cal.com, Inc. does not provide official support for Docker, but we will accept fixes and documentation. Use at your own risk.
Make sure you have `docker` & `docker compose` installed on the server / system. Both are installed by most docker utilities, including Docker Desktop and Rancher Desktop.
Note: `docker compose` without the hyphen is now the primary method of using docker-compose, per the Docker documentation.
#### (Most users) Running Cal.com with Docker Compose
If you are evaluating Cal.com or running with minimal to no modifications, this option is for you.
1. Clone calcom/cal.com
```bash
git clone --recursive https://github.com/calcom/cal.com.git
```
2. Change into the directory
```bash
cd cal.com
```
3. Prepare your configuration: Rename `.env.example` to `.env` and then update `.env`
```bash
cp .env.example .env
```
Most configurations can be left as-is, but for configuration options see [Important Run-time variables](#important-run-time-variables) below.
**Push Notifications (VAPID Keys)**
If you see an error like:
```
Error: No key set vapidDetails.publicKey
```
This means your environment variables for Web Push are missing.
You must generate and set `NEXT_PUBLIC_VAPID_PUBLIC_KEY` and `VAPID_PRIVATE_KEY`.
Generate them with:
```bash
npx web-push generate-vapid-keys
```
Then update your `.env` file:
```env
NEXT_PUBLIC_VAPID_PUBLIC_KEY=your_public_key_here
VAPID_PRIVATE_KEY=your_private_key_here
```
Do **not** commit real keys to `.env.example` — only placeholders.
Update the appropriate values in your .env file, then proceed.
4. (optional) Pre-Pull the images by running the following command:
```bash
docker compose pull
```
This will use the default image locations as specified by `image:` in the docker-compose.yaml file.
Note: To aid with support, by default Scarf.sh is used as registry proxy for download metrics.
5. Start Cal.com via docker compose
(Most basic users, and for First Run) To run the complete stack, which includes a local Postgres database, Cal.com web app, and Prisma Studio:
```bash
docker compose up -d
```
To run Cal.com web app and Prisma Studio against a remote database, ensure that DATABASE_URL is configured for an available database and run:
```bash
docker compose up -d calcom studio
```
To run only the Cal.com web app, ensure that DATABASE_URL is configured for an available database and run:
```bash
docker compose up -d calcom
```
**Note: to run in attached mode for debugging, remove `-d` from your desired run command.**
6. Open a browser to [http://localhost:3000](http://localhost:3000), or your defined NEXT_PUBLIC_WEBAPP_URL. The first time you run Cal.com, a setup wizard will initialize. Define your first user, and you're ready to go!
#### Updating Cal.com
1. Stop the Cal.com stack
```bash
docker compose down
```
2. Pull the latest changes
```bash
docker compose pull
```
3. Update env vars as necessary.
4. Re-start the Cal.com stack
```bash
docker compose up -d
```
#### (Advanced users) Build and Run Cal.com
1. Clone calcom/docker.
```bash
git clone https://github.com/calcom/cal.com.git calcom-docker
```
2. Change into the directory
```bash
cd calcom-docker
```
3. Update the calcom submodule. This project depends on the Cal.com source code, which is included here as a Git submodule. To make sure you get everything you need, update the submodule with the command below.
```bash
git submodule update --remote --init
```
Note: DO NOT use recursive submodule update, otherwise you will receive a git authentication error.
4. Rename `.env.example` to `.env` and then update `.env`
For configuration options see [Build-time variables](#build-time-variables) below. Update the appropriate values in your .env file, then proceed.
5. Build the Cal.com docker image:
Note: Due to application configuration requirements, an available database is currently required during the build process.
a) If hosting elsewhere, configure the `DATABASE_URL` in the .env file, and skip the next step
b) If a local or temporary database is required, start a local database via docker compose.
```bash
docker compose up -d database
```
6. Build Cal.com via docker compose (DOCKER_BUILDKIT=0 must be provided to allow a network bridge to be used at build time. This requirement will be removed in the future)
```bash
DOCKER_BUILDKIT=0 docker compose build calcom
```
7. Start Cal.com via docker compose
(Most basic users, and for First Run) To run the complete stack, which includes a local Postgres database, Cal.com web app, and Prisma Studio:
```bash
docker compose up -d
```
To run Cal.com web app and Prisma Studio against a remote database, ensure that DATABASE_URL is configured for an available database and run:
```bash
docker compose up -d calcom studio
```
To run only the Cal.com web app, ensure that DATABASE_URL is configured for an available database and run:
```bash
docker compose up -d calcom
```
**Note: to run in attached mode for debugging, remove `-d` from your desired run command.**
8. Open a browser to [http://localhost:3000](http://localhost:3000), or your defined NEXT_PUBLIC_WEBAPP_URL. The first time you run Cal.com, a setup wizard will initialize. Define your first user, and you're ready to go!
#### Configuration
##### Important Run-time variables
These variables must also be provided at runtime
| Variable | Description | Required | Default |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------- |
| DATABASE_URL | database url with credentials - if using a connection pooler, this setting should point there | required | `postgresql://unicorn_user:magical_password@database:5432/calendso` |
| CALCOM_LICENSE_KEY | Enterprise License Key | optional | |
| NEXT_PUBLIC_WEBAPP_URL | Base URL of the site. NOTE: if this value differs from the value used at build-time, there will be a slight delay during container start (to update the statically built files). | optional | `http://localhost:3000` |
| NEXTAUTH_URL | Location of the auth server. By default, this is the Cal.com docker instance itself. | optional | `{NEXT_PUBLIC_WEBAPP_URL}/api/auth` |
| NEXTAUTH_SECRET | must match build variable | required | `secret` |
| CALENDSO_ENCRYPTION_KEY | must match build variable | required | `secret` |
##### Build-time variables
If building the image yourself, these variables must be provided at the time of the docker build, and can be provided by updating the .env file. Currently, if you require changes to these variables, you must follow the instructions to build and publish your own image.
Updating these variables is not required for evaluation, but is required for running in production. Instructions for generating variables can be found in the [Cal.com instructions](https://github.com/calcom/cal.com)
| Variable | Description | Required | Default |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -------- | ------------------------------------------------------------------- |
| DATABASE_URL | database url with credentials - if using a connection pooler, this setting should point there | required | `postgresql://unicorn_user:magical_password@database:5432/calendso` |
| MAX_OLD_SPACE_SIZE | Needed for Nodejs/NPM build options | required | 4096 |
| NEXT_PUBLIC_LICENSE_CONSENT | license consent - true/false | required | |
| NEXTAUTH_SECRET | Cookie encryption key | required | `secret` |
| CALENDSO_ENCRYPTION_KEY | Authentication encryption key | required | `secret` |
| NEXT_PUBLIC_WEBAPP_URL | Base URL injected into static files | optional | `http://localhost:3000` |
| NEXT_PUBLIC_WEBSITE_TERMS_URL | custom URL for terms and conditions website | optional | `https://cal.com/terms` |
| NEXT_PUBLIC_WEBSITE_PRIVACY_POLICY_URL | custom URL for privacy policy website | optional | `https://cal.com/privacy` |
| NEXT_PUBLIC_API_V2_URL | URL for the v2 API, only required for custom integrations or custom booking experiences using [Cal.com Platform](https://cal.com/platform) | optional | |
| CALCOM_TELEMETRY_DISABLED | Allow Cal.com to collect anonymous usage data (set to `1` to disable) | optional | |
| NEXT_PUBLIC_SINGLE_ORG_SLUG | Required if ORGANIZATIONS_ENABLED is true | optional | |
| ORGANIZATIONS_ENABLED | Used for Enterprise or Organizations plan | optional | |
#### Troubleshooting
##### SSL edge termination
If running behind a load balancer which handles SSL certificates, you will need to add the environmental variable `NODE_TLS_REJECT_UNAUTHORIZED=0` to prevent requests from being rejected. Only do this if you know what you are doing and trust the services/load-balancers directing traffic to your service.
##### Failed to commit changes: Invalid 'prisma.user.create()'
Certain versions may have trouble creating a user if the field `metadata` is empty. Using an empty json object `{}` as the field value should resolve this issue. Also, the `id` field will autoincrement, so you may also try leaving the value of `id` as empty.
##### CLIENT_FETCH_ERROR
If you experience this error, it may be the way the default Auth callback in the server is using the WEBAPP_URL as a base url. The container does not necessarily have access to the same DNS as your local machine, and therefor needs to be configured to resolve to itself. You may be able to correct this by configuring `NEXTAUTH_URL=http://localhost:3000/api/auth`, to help the backend loop back to itself.
```
docker-calcom-1 | @calcom/web:start: [next-auth][error][CLIENT_FETCH_ERROR]
docker-calcom-1 | @calcom/web:start: https://next-auth.js.org/errors#client_fetch_error request to http://testing.localhost:3000/api/auth/session failed, reason: getaddrinfo ENOTFOUND testing.localhost {
docker-calcom-1 | @calcom/web:start: error: {
docker-calcom-1 | @calcom/web:start: message: 'request to http://testing.localhost:3000/api/auth/session failed, reason: getaddrinfo ENOTFOUND testing.localhost',
docker-calcom-1 | @calcom/web:start: stack: 'FetchError: request to http://testing.localhost:3000/api/auth/session failed, reason: getaddrinfo ENOTFOUND testing.localhost\n' +
docker-calcom-1 | @calcom/web:start: ' at ClientRequest.<anonymous> (/calcom/node_modules/next/dist/compiled/node-fetch/index.js:1:65756)\n' +
docker-calcom-1 | @calcom/web:start: ' at ClientRequest.emit (node:events:513:28)\n' +
docker-calcom-1 | @calcom/web:start: ' at ClientRequest.emit (node:domain:489:12)\n' +
docker-calcom-1 | @calcom/web:start: ' at Socket.socketErrorListener (node:_http_client:494:9)\n' +
docker-calcom-1 | @calcom/web:start: ' at Socket.emit (node:events:513:28)\n' +
docker-calcom-1 | @calcom/web:start: ' at Socket.emit (node:domain:489:12)\n' +
docker-calcom-1 | @calcom/web:start: ' at emitErrorNT (node:internal/streams/destroy:157:8)\n' +
docker-calcom-1 | @calcom/web:start: ' at emitErrorCloseNT (node:internal/streams/destroy:122:3)\n' +
docker-calcom-1 | @calcom/web:start: ' at processTicksAndRejections (node:internal/process/task_queues:83:21)',
docker-calcom-1 | @calcom/web:start: name: 'FetchError'
docker-calcom-1 | @calcom/web:start: },
docker-calcom-1 | @calcom/web:start: url: 'http://testing.localhost:3000/api/auth/session',
docker-calcom-1 | @calcom/web:start: message: 'request to http://testing.localhost:3000/api/auth/session failed, reason: getaddrinfo ENOTFOUND testing.localhost'
docker-calcom-1 | @calcom/web:start: }
```
<img referrerpolicy="no-referrer-when-downgrade" src="https://static.scarf.sh/a.png?x-pxid=81cda9f7-a102-453b-ac01-51c35650bd70" />
### Railway ### Railway
@@ -751,9 +497,9 @@ Don't code but still want to contribute? Join our [Discussions](https://github.c
- Set CSP_POLICY="non-strict" env variable, which enables [Strict CSP](https://web.dev/strict-csp/) except for unsafe-inline in style-src . If you have some custom changes in your instance, you might have to make some code change to make your instance CSP compatible. Right now it enables strict CSP only on login page and on other SSR pages it is enabled in Report only mode to detect possible issues. On, SSG pages it is still not supported. - Set CSP_POLICY="non-strict" env variable, which enables [Strict CSP](https://web.dev/strict-csp/) except for unsafe-inline in style-src . If you have some custom changes in your instance, you might have to make some code change to make your instance CSP compatible. Right now it enables strict CSP only on login page and on other SSR pages it is enabled in Report only mode to detect possible issues. On, SSG pages it is still not supported.
## Single Org Mode ## Single Org Mode
Refer to docs [here](./docs/self-hosting/guides/organization/single-organization-setup) for a detailed documentation with screenshots. Refer to docs [here](./docs/self-hosting/guides/organization/single-organization-setup) for a detailed documentation with screenshots.
## Integrations ## Integrations
### Obtaining the Google API Credentials ### Obtaining the Google API Credentials
@@ -909,7 +655,6 @@ following
We use changesets to generate changelogs and publish public packages (packages with `private: true` are ignored). We use changesets to generate changelogs and publish public packages (packages with `private: true` are ignored).
An example of good readme is [atoms readme](https://github.com/calcom/cal.com/blob/main/packages/platform/atoms/README.md). Every public package must: An example of good readme is [atoms readme](https://github.com/calcom/cal.com/blob/main/packages/platform/atoms/README.md). Every public package must:
1. Follow semantic versioning when using changesets. 1. Follow semantic versioning when using changesets.
2. Mark breaking changes using `❗️Breaking change` 2. Mark breaking changes using `❗️Breaking change`
@@ -27,7 +27,7 @@ const getAllAdminMemberships = async (userId: number) => {
where: { where: {
userId: userId, userId: userId,
accepted: true, accepted: true,
role: { in: [MembershipRole.OWNER, MembershipRole.ADMIN] }, OR: [{ role: MembershipRole.OWNER }, { role: MembershipRole.ADMIN }],
}, },
select: { select: {
team: { team: {
@@ -56,19 +56,16 @@ export const getAccessibleUsers = async ({
memberUserIds, memberUserIds,
adminUserId, adminUserId,
}: AccessibleUsersType): Promise<number[]> => { }: AccessibleUsersType): Promise<number[]> => {
const orConditions = [];
if (memberUserIds.length > 0) {
orConditions.push({ userId: { in: memberUserIds } });
}
orConditions.push({ userId: adminUserId, role: { in: [MembershipRole.OWNER, MembershipRole.ADMIN] } });
const memberships = await prisma.membership.findMany({ const memberships = await prisma.membership.findMany({
where: { where: {
team: { team: {
isOrganization: true, isOrganization: true,
}, },
accepted: true, accepted: true,
OR: orConditions, OR: [
{ userId: { in: memberUserIds } },
{ userId: adminUserId, role: { in: [MembershipRole.OWNER, MembershipRole.ADMIN] } },
],
}, },
select: { select: {
userId: true, userId: true,
@@ -12,7 +12,7 @@ async function authMiddleware(req: NextApiRequest) {
if (isSystemWideAdmin) return; if (isSystemWideAdmin) return;
// Find all references where the user has bookings // Find all references where the user has bookings
const bookingReference = await prisma.bookingReference.findFirst({ const bookingReference = await prisma.bookingReference.findFirst({
where: { id, booking: { userId }, deleted: null }, where: { id, booking: { userId } },
}); });
if (!bookingReference) throw new HttpError({ statusCode: 403, message: "Forbidden" }); if (!bookingReference) throw new HttpError({ statusCode: 403, message: "Forbidden" });
} }
@@ -37,7 +37,7 @@ import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransform
export async function deleteHandler(req: NextApiRequest) { export async function deleteHandler(req: NextApiRequest) {
const { query } = req; const { query } = req;
const { id } = schemaQueryIdParseInt.parse(query); const { id } = schemaQueryIdParseInt.parse(query);
await prisma.bookingReference.update({ where: { id }, data: { deleted: true } }); await prisma.bookingReference.delete({ where: { id } });
return { message: `BookingReference with id: ${id} deleted` }; return { message: `BookingReference with id: ${id} deleted` };
} }
@@ -38,7 +38,7 @@ import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransform
export async function getHandler(req: NextApiRequest) { export async function getHandler(req: NextApiRequest) {
const { query } = req; const { query } = req;
const { id } = schemaQueryIdParseInt.parse(query); const { id } = schemaQueryIdParseInt.parse(query);
const booking_reference = await prisma.bookingReference.findUniqueOrThrow({ where: { id, deleted: null } }); const booking_reference = await prisma.bookingReference.findUniqueOrThrow({ where: { id } });
return { booking_reference: schemaBookingReferenceReadPublic.parse(booking_reference) }; return { booking_reference: schemaBookingReferenceReadPublic.parse(booking_reference) };
} }
@@ -29,13 +29,13 @@ import { schemaBookingReferenceReadPublic } from "~/lib/validations/booking-refe
* 404: * 404:
* description: No booking references were found * description: No booking references were found
*/ */
export async function handler(req: NextApiRequest) { async function getHandler(req: NextApiRequest) {
const { userId, isSystemWideAdmin } = req; const { userId, isSystemWideAdmin } = req;
const args: Prisma.BookingReferenceFindManyArgs = isSystemWideAdmin const args: Prisma.BookingReferenceFindManyArgs = isSystemWideAdmin
? { where: { deleted: null } } ? {}
: { where: { booking: { userId }, deleted: null } }; : { where: { booking: { userId } } };
const data = await prisma.bookingReference.findMany(args); const data = await prisma.bookingReference.findMany(args);
return { booking_references: data.map((br) => schemaBookingReferenceReadPublic.parse(br)) }; return { booking_references: data.map((br) => schemaBookingReferenceReadPublic.parse(br)) };
} }
export default defaultResponder(handler); export default defaultResponder(getHandler);
+2 -2
View File
@@ -3,8 +3,8 @@ import utc from "dayjs/plugin/utc";
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import dayjs from "@calcom/dayjs"; import dayjs from "@calcom/dayjs";
import { getAvailableSlotsService } from "@calcom/features/di/containers/AvailableSlots";
import { isSupportedTimeZone } from "@calcom/lib/dayjs"; import { isSupportedTimeZone } from "@calcom/lib/dayjs";
import { getAvailableSlotsService } from "@calcom/features/di/containers/AvailableSlots";
import { HttpError } from "@calcom/lib/http-error"; import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server/defaultResponder"; import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import { createContext } from "@calcom/trpc/server/createContext"; import { createContext } from "@calcom/trpc/server/createContext";
@@ -48,7 +48,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
: availableSlots.slots; : availableSlots.slots;
return { slots: slotsInProvidedTimeZone }; return { slots: slotsInProvidedTimeZone };
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (cause) { } catch (cause) {
if (cause instanceof TRPCError) { if (cause instanceof TRPCError) {
const statusCode = getHTTPStatusCodeFromError(cause); const statusCode = getHTTPStatusCodeFromError(cause);
@@ -1,486 +0,0 @@
import type { Request, Response } from "express";
import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http";
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import prisma from "@calcom/prisma";
import type { Booking, Credential, EventType, User } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
import { patchHandler } from "../../pages/api/booking-references/[id]/_patch";
import { handler } from "../../pages/api/booking-references/_get";
type CustomNextApiRequest = NextApiRequest & Request;
type CustomNextApiResponse = NextApiResponse & Response;
describe("GET /api/booking-references - Soft-delete filtering", () => {
let testUser: User;
let testCredential: Credential;
let testEventType: EventType;
let testBooking: Booking;
const createdBookingReferenceIds: number[] = [];
beforeAll(async () => {
testUser = await prisma.user.create({
data: {
email: "api-bookingreference-test@example.com",
username: "api-bookingreference-test",
},
});
testCredential = await prisma.credential.create({
data: {
type: "google_calendar",
key: {},
userId: testUser.id,
},
});
testEventType = await prisma.eventType.create({
data: {
title: "Test Event Type",
slug: "api-test-event-type",
length: 30,
userId: testUser.id,
},
});
testBooking = await prisma.booking.create({
data: {
uid: "api-test-booking-uid",
title: "API Test Booking",
startTime: new Date(Date.now() + 86400000),
endTime: new Date(Date.now() + 90000000),
userId: testUser.id,
eventTypeId: testEventType.id,
status: BookingStatus.ACCEPTED,
},
});
});
afterAll(async () => {
if (createdBookingReferenceIds.length > 0) {
await prisma.bookingReference.deleteMany({
where: {
id: {
in: createdBookingReferenceIds,
},
},
});
}
await prisma.booking.delete({
where: {
id: testBooking.id,
},
});
await prisma.eventType.delete({
where: {
id: testEventType.id,
},
});
await prisma.credential.delete({
where: {
id: testCredential.id,
},
});
await prisma.user.delete({
where: {
id: testUser.id,
},
});
});
it("should only return active booking references, excluding soft-deleted ones", async () => {
const timestamp = Date.now();
const activeRef = await prisma.bookingReference.create({
data: {
type: "google_calendar",
uid: `api-active-ref-${timestamp}`,
meetingId: `api-active-meeting-${timestamp}`,
credentialId: testCredential.id,
bookingId: testBooking.id,
},
});
createdBookingReferenceIds.push(activeRef.id);
const deletedRef = await prisma.bookingReference.create({
data: {
type: "google_calendar",
uid: `api-deleted-ref-${timestamp}`,
meetingId: `api-deleted-meeting-${timestamp}`,
credentialId: testCredential.id,
bookingId: testBooking.id,
deleted: true,
},
});
createdBookingReferenceIds.push(deletedRef.id);
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "GET",
});
req.userId = testUser.id;
const responseData = await handler(req);
expect(responseData.booking_references).toBeDefined();
expect(Array.isArray(responseData.booking_references)).toBe(true);
const returnedActiveRef = responseData.booking_references.find(
(ref: { id: number }) => ref.id === activeRef.id
);
const returnedDeletedRef = responseData.booking_references.find(
(ref: { id: number }) => ref.id === deletedRef.id
);
expect(returnedActiveRef).toBeDefined();
expect(returnedDeletedRef).toBeUndefined();
});
it("should filter booking references by user when not system admin", async () => {
const timestamp = Date.now();
const otherUser = await prisma.user.create({
data: {
email: `other-user-bookingreference-${timestamp}@example.com`,
username: `other-user-bookingreference-${timestamp}`,
},
});
const otherBooking = await prisma.booking.create({
data: {
uid: `other-user-booking-uid-${timestamp}`,
title: "Other User Booking",
startTime: new Date(Date.now() + 86400000),
endTime: new Date(Date.now() + 90000000),
userId: otherUser.id,
eventTypeId: testEventType.id,
status: BookingStatus.ACCEPTED,
},
});
const otherUserRef = await prisma.bookingReference.create({
data: {
type: "zoom_video",
uid: `other-user-ref-${timestamp}`,
meetingId: `other-user-meeting-${timestamp}`,
credentialId: testCredential.id,
bookingId: otherBooking.id,
},
});
createdBookingReferenceIds.push(otherUserRef.id);
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "GET",
});
req.userId = testUser.id;
const responseData = await handler(req);
const userRefs = responseData.booking_references.filter(
(ref: { id: number }) => ref.id === otherUserRef.id
);
expect(userRefs).toHaveLength(0);
await prisma.booking.delete({ where: { id: otherBooking.id } });
await prisma.user.delete({ where: { id: otherUser.id } });
});
it("should return only active booking references for user, not soft-deleted ones for system admin", async () => {
const timestamp = Date.now();
const activeRef1 = await prisma.bookingReference.create({
data: {
type: "daily_video",
uid: `admin-active-ref-1-${timestamp}`,
meetingId: `admin-active-meeting-1-${timestamp}`,
credentialId: testCredential.id,
bookingId: testBooking.id,
},
});
createdBookingReferenceIds.push(activeRef1.id);
const activeRef2 = await prisma.bookingReference.create({
data: {
type: "daily_video",
uid: `admin-active-ref-2-${timestamp}`,
meetingId: `admin-active-meeting-2-${timestamp}`,
credentialId: testCredential.id,
bookingId: testBooking.id,
},
});
createdBookingReferenceIds.push(activeRef2.id);
const deletedRef = await prisma.bookingReference.create({
data: {
type: "daily_video",
uid: `admin-deleted-ref-${timestamp}`,
meetingId: `admin-deleted-meeting-${timestamp}`,
credentialId: testCredential.id,
bookingId: testBooking.id,
deleted: true,
},
});
createdBookingReferenceIds.push(deletedRef.id);
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "GET",
});
req.userId = testUser.id;
const responseData = await handler(req);
const activeRefs = responseData.booking_references.filter(
(ref: { id: number }) => ref.id === activeRef1.id || ref.id === activeRef2.id
);
const returnedDeletedRef = responseData.booking_references.find(
(ref: { id: number }) => ref.id === deletedRef.id
);
expect(activeRefs.length).toBe(2);
expect(returnedDeletedRef).toBeUndefined();
});
it("should verify soft-deleted references are never returned through the API", async () => {
const timestamp = Date.now();
const activeRef = await prisma.bookingReference.create({
data: {
type: "office365_calendar",
uid: `never-return-active-${timestamp}`,
meetingId: `never-return-active-meeting-${timestamp}`,
credentialId: testCredential.id,
bookingId: testBooking.id,
},
});
createdBookingReferenceIds.push(activeRef.id);
await prisma.bookingReference.update({
where: { id: activeRef.id },
data: { deleted: true },
});
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "GET",
});
req.userId = testUser.id;
const responseData = await handler(req);
const softDeletedRef = responseData.booking_references.find(
(ref: { id: number }) => ref.id === activeRef.id
);
expect(softDeletedRef).toBeUndefined();
const refInDb = await prisma.bookingReference.findUnique({
where: { id: activeRef.id },
});
expect(refInDb).toBeDefined();
expect(refInDb?.deleted).toBe(true);
});
});
describe("PATCH /api/booking-references/[id] - Existing functionality", () => {
let testUser: User;
let testCredential: Credential;
let testEventType: EventType;
let testBooking: Booking;
const createdBookingReferenceIds: number[] = [];
beforeAll(async () => {
testUser = await prisma.user.create({
data: {
email: "api-bookingreference-patch-test@example.com",
username: "api-bookingreference-patch-test",
},
});
testCredential = await prisma.credential.create({
data: {
type: "google_calendar",
key: {},
userId: testUser.id,
},
});
testEventType = await prisma.eventType.create({
data: {
title: "Test Event Type",
slug: "api-patch-test-event-type",
length: 30,
userId: testUser.id,
},
});
testBooking = await prisma.booking.create({
data: {
uid: "api-patch-test-booking-uid",
title: "API Patch Test Booking",
startTime: new Date(Date.now() + 86400000),
endTime: new Date(Date.now() + 90000000),
userId: testUser.id,
eventTypeId: testEventType.id,
status: BookingStatus.ACCEPTED,
},
});
});
afterAll(async () => {
if (createdBookingReferenceIds.length > 0) {
await prisma.bookingReference.deleteMany({
where: {
id: {
in: createdBookingReferenceIds,
},
},
});
}
await prisma.booking.delete({
where: {
id: testBooking.id,
},
});
await prisma.eventType.delete({
where: {
id: testEventType.id,
},
});
await prisma.credential.delete({
where: {
id: testCredential.id,
},
});
await prisma.user.delete({
where: {
id: testUser.id,
},
});
});
it("should successfully update an active booking reference", async () => {
const timestamp = Date.now();
const activeRef = await prisma.bookingReference.create({
data: {
type: "google_calendar",
uid: `patch-active-ref-${timestamp}`,
meetingId: `patch-active-meeting-${timestamp}`,
credentialId: testCredential.id,
bookingId: testBooking.id,
},
});
createdBookingReferenceIds.push(activeRef.id);
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "PATCH",
query: { id: activeRef.id.toString() },
body: {
meetingPassword: "new-password-123",
},
});
req.userId = testUser.id;
req.isSystemWideAdmin = false;
const responseData = await patchHandler(req);
expect(responseData.booking_reference).toBeDefined();
expect(responseData.booking_reference.id).toBe(activeRef.id);
expect(responseData.booking_reference.meetingPassword).toBe("new-password-123");
const updatedRef = await prisma.bookingReference.findUnique({
where: { id: activeRef.id },
});
expect(updatedRef?.meetingPassword).toBe("new-password-123");
});
it("should allow updating a soft-deleted booking reference (existing functionality)", async () => {
const timestamp = Date.now();
const deletedRef = await prisma.bookingReference.create({
data: {
type: "google_calendar",
uid: `patch-deleted-ref-${timestamp}`,
meetingId: `patch-deleted-meeting-${timestamp}`,
credentialId: testCredential.id,
bookingId: testBooking.id,
deleted: true,
meetingPassword: "original-password",
},
});
createdBookingReferenceIds.push(deletedRef.id);
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "PATCH",
query: { id: deletedRef.id.toString() },
body: {
meetingPassword: "updated-password",
},
});
req.userId = testUser.id;
req.isSystemWideAdmin = false;
const responseData = await patchHandler(req);
expect(responseData.booking_reference).toBeDefined();
expect(responseData.booking_reference.id).toBe(deletedRef.id);
expect(responseData.booking_reference.meetingPassword).toBe("updated-password");
const updatedRef = await prisma.bookingReference.findUnique({
where: { id: deletedRef.id },
});
expect(updatedRef?.meetingPassword).toBe("updated-password");
expect(updatedRef?.deleted).toBe(true);
});
it("should verify that booking references can be updated regardless of deleted status", async () => {
const timestamp = Date.now();
const activeRef = await prisma.bookingReference.create({
data: {
type: "zoom_video",
uid: `patch-verify-active-${timestamp}`,
meetingId: `patch-verify-active-meeting-${timestamp}`,
credentialId: testCredential.id,
bookingId: testBooking.id,
meetingPassword: "original-password",
},
});
createdBookingReferenceIds.push(activeRef.id);
await prisma.bookingReference.update({
where: { id: activeRef.id },
data: { deleted: true },
});
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "PATCH",
query: { id: activeRef.id.toString() },
body: {
meetingPassword: "updated-password",
},
});
req.userId = testUser.id;
req.isSystemWideAdmin = false;
const responseData = await patchHandler(req);
expect(responseData.booking_reference).toBeDefined();
expect(responseData.booking_reference.meetingPassword).toBe("updated-password");
const refInDb = await prisma.bookingReference.findUnique({
where: { id: activeRef.id },
});
expect(refInDb?.meetingPassword).toBe("updated-password");
expect(refInDb?.deleted).toBe(true);
});
});
@@ -1,7 +1,7 @@
import type { Request, Response } from "express"; import type { Request, Response } from "express";
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http"; import { createMocks } from "node-mocks-http";
import { describe, it, expect, beforeAll } from "vitest"; import { describe, it, expect } from "vitest";
import prisma from "@calcom/prisma"; import prisma from "@calcom/prisma";
@@ -11,30 +11,6 @@ type CustomNextApiRequest = NextApiRequest & Request;
type CustomNextApiResponse = NextApiResponse & Response; type CustomNextApiResponse = NextApiResponse & Response;
describe("PATCH /api/bookings", () => { describe("PATCH /api/bookings", () => {
beforeAll(async () => {
const acmeOrg = await prisma.team.findFirst({
where: {
slug: "acme",
isOrganization: true,
},
});
if (acmeOrg) {
await prisma.organizationSettings.upsert({
where: {
organizationId: acmeOrg.id,
},
update: {
isAdminAPIEnabled: true,
},
create: {
organizationId: acmeOrg.id,
orgAutoAcceptEmail: "acme.com",
isAdminAPIEnabled: true,
},
});
}
});
it("Returns 403 when user has no permission to the booking", async () => { it("Returns 403 when user has no permission to the booking", async () => {
const memberUser = await prisma.user.findFirstOrThrow({ where: { email: "member2-acme@example.com" } }); const memberUser = await prisma.user.findFirstOrThrow({ where: { email: "member2-acme@example.com" } });
const proUser = await prisma.user.findFirstOrThrow({ where: { email: "pro@example.com" } }); const proUser = await prisma.user.findFirstOrThrow({ where: { email: "pro@example.com" } });
@@ -5,11 +5,11 @@ import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http"; import { createMocks } from "node-mocks-http";
import { describe, expect, test, vi, afterEach } from "vitest"; import { describe, expect, test, vi, afterEach } from "vitest";
import { buildBooking } from "@calcom/lib/test/builder";
import { import {
getRecordingsOfCalVideoByRoomName, getRecordingsOfCalVideoByRoomName,
getDownloadLinkOfCalVideoByRecordingId, getDownloadLinkOfCalVideoByRecordingId,
} from "@calcom/features/conferencing/lib/videoClient"; } from "@calcom/features/conferencing/lib/videoClient";
import { buildBooking } from "@calcom/lib/test/builder";
import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers"; import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers";
@@ -5,8 +5,8 @@ import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http"; import { createMocks } from "node-mocks-http";
import { describe, expect, test, vi, afterEach } from "vitest"; import { describe, expect, test, vi, afterEach } from "vitest";
import { getAllTranscriptsAccessLinkFromRoomName } from "@calcom/features/conferencing/lib/videoClient";
import { buildBooking } from "@calcom/lib/test/builder"; import { buildBooking } from "@calcom/lib/test/builder";
import { getAllTranscriptsAccessLinkFromRoomName } from "@calcom/features/conferencing/lib/videoClient";
import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers"; import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers";
@@ -1,10 +1,10 @@
import type { Request, Response } from "express"; import type { Request, Response } from "express";
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http"; import { createMocks } from "node-mocks-http";
import { describe, expect, it, beforeAll } from "vitest"; import { describe, expect, it } from "vitest";
import { ZodError } from "zod"; import { ZodError } from "zod";
import { prisma } from "@calcom/prisma"; import prisma from "@calcom/prisma";
import { handler } from "../../../pages/api/bookings/_get"; import { handler } from "../../../pages/api/bookings/_get";
@@ -17,30 +17,6 @@ const DefaultPagination = {
}; };
describe("GET /api/bookings", async () => { describe("GET /api/bookings", async () => {
beforeAll(async () => {
const acmeOrg = await prisma.team.findFirst({
where: {
slug: "acme",
isOrganization: true,
},
});
if (acmeOrg) {
await prisma.organizationSettings.upsert({
where: {
organizationId: acmeOrg.id,
},
update: {
isAdminAPIEnabled: true,
},
create: {
organizationId: acmeOrg.id,
orgAutoAcceptEmail: "acme.com",
isAdminAPIEnabled: true,
},
});
}
});
const proUser = await prisma.user.findFirstOrThrow({ where: { email: "pro@example.com" } }); const proUser = await prisma.user.findFirstOrThrow({ where: { email: "pro@example.com" } });
const proUserBooking = await prisma.booking.findFirstOrThrow({ where: { userId: proUser.id } }); const proUserBooking = await prisma.booking.findFirstOrThrow({ where: { userId: proUser.id } });
@@ -217,22 +193,6 @@ describe("GET /api/bookings", async () => {
describe("Expand feature to add relational data in return payload", () => { describe("Expand feature to add relational data in return payload", () => {
it("Returns only team data when expand=team is set", async () => { it("Returns only team data when expand=team is set", async () => {
const adminUser = await prisma.user.findFirstOrThrow({ where: { email: "owner1-acme@example.com" } }); const adminUser = await prisma.user.findFirstOrThrow({ where: { email: "owner1-acme@example.com" } });
// Find a team booking and a non-team booking from seed data
const team1 = await prisma.team.findFirst({ where: { slug: "team1" } });
const teamEventType = await prisma.eventType.findFirst({
where: { teamId: team1?.id },
include: { bookings: true },
});
const teamBooking = teamEventType?.bookings[0];
const nonTeamBooking = await prisma.booking.findFirst({
where: {
eventType: { teamId: null },
userId: proUser.id,
},
});
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({ const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "GET", method: "GET",
query: { query: {
@@ -245,23 +205,14 @@ describe("GET /api/bookings", async () => {
req.isOrganizationOwnerOrAdmin = true; req.isOrganizationOwnerOrAdmin = true;
const responseData = await handler(req); const responseData = await handler(req);
console.log("bookings=>", responseData.bookings);
// Verify team booking has team data responseData.bookings.forEach((booking) => {
if (teamBooking) { if (booking.id === 31) expect(booking.eventType?.team?.slug).toBe("team1");
const returnedTeamBooking = responseData.bookings.find((b) => b.id === teamBooking.id); if (booking.id === 19) {
expect(returnedTeamBooking?.eventType?.team?.slug).toBe("team1"); // The team field can be either null or undefined due to nullish() in the schema
} expect(booking.eventType?.team === null || booking.eventType?.team === undefined).toBe(true);
// Verify non-team booking has null/undefined team
if (nonTeamBooking) {
const returnedNonTeamBooking = responseData.bookings.find((b) => b.id === nonTeamBooking.id);
if (returnedNonTeamBooking) {
expect(
returnedNonTeamBooking.eventType?.team === null ||
returnedNonTeamBooking.eventType?.team === undefined
).toBe(true);
} }
} });
}); });
}); });
@@ -367,6 +318,11 @@ describe("GET /api/bookings", async () => {
const testUser = await prisma.user.findFirstOrThrow({ where: { email: "pro@example.com" } }); const testUser = await prisma.user.findFirstOrThrow({ where: { email: "pro@example.com" } });
const testUserBooking = await prisma.booking.findFirstOrThrow({
where: { userId: testUser.id },
include: { attendees: true },
});
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({ const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "GET", method: "GET",
query: { query: {
@@ -1,7 +1,7 @@
import type { Request, Response } from "express"; import type { Request, Response } from "express";
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http"; import { createMocks } from "node-mocks-http";
import { describe, it, expect, beforeAll } from "vitest"; import { describe, it, expect } from "vitest";
import prisma from "@calcom/prisma"; import prisma from "@calcom/prisma";
@@ -12,53 +12,6 @@ type CustomNextApiRequest = NextApiRequest & Request;
type CustomNextApiResponse = NextApiResponse & Response; type CustomNextApiResponse = NextApiResponse & Response;
describe("isAdmin guard", () => { describe("isAdmin guard", () => {
beforeAll(async () => {
const acmeOrg = await prisma.team.findFirst({
where: {
slug: "acme",
isOrganization: true,
},
});
if (acmeOrg) {
await prisma.organizationSettings.upsert({
where: {
organizationId: acmeOrg.id,
},
update: {
isAdminAPIEnabled: true,
},
create: {
organizationId: acmeOrg.id,
orgAutoAcceptEmail: "acme.com",
isAdminAPIEnabled: true,
},
});
}
const dunderOrg = await prisma.team.findFirst({
where: {
slug: "dunder-mifflin",
isOrganization: true,
},
});
if (dunderOrg) {
await prisma.organizationSettings.upsert({
where: {
organizationId: dunderOrg.id,
},
update: {
isAdminAPIEnabled: false,
},
create: {
organizationId: dunderOrg.id,
orgAutoAcceptEmail: "dunder-mifflin.com",
isAdminAPIEnabled: false,
},
});
}
});
it("Returns false when user does not exist in the system", async () => { it("Returns false when user does not exist in the system", async () => {
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({ const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "POST", method: "POST",
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeAll } from "vitest"; import { describe, it, expect } from "vitest";
import prisma from "@calcom/prisma"; import prisma from "@calcom/prisma";
@@ -8,30 +8,6 @@ import {
} from "../../../lib/utils/retrieveScopedAccessibleUsers"; } from "../../../lib/utils/retrieveScopedAccessibleUsers";
describe("retrieveScopedAccessibleUsers tests", () => { describe("retrieveScopedAccessibleUsers tests", () => {
beforeAll(async () => {
const acmeOrg = await prisma.team.findFirst({
where: {
slug: "acme",
isOrganization: true,
},
});
if (acmeOrg) {
await prisma.organizationSettings.upsert({
where: {
organizationId: acmeOrg.id,
},
update: {
isAdminAPIEnabled: true,
},
create: {
organizationId: acmeOrg.id,
orgAutoAcceptEmail: "acme.com",
isAdminAPIEnabled: true,
},
});
}
});
describe("getAccessibleUsers", () => { describe("getAccessibleUsers", () => {
it("Does not return members when only admin user ID is supplied", async () => { it("Does not return members when only admin user ID is supplied", async () => {
const adminUser = await prisma.user.findFirstOrThrow({ where: { email: "owner1-acme@example.com" } }); const adminUser = await prisma.user.findFirstOrThrow({ where: { email: "owner1-acme@example.com" } });
-1
View File
@@ -43,4 +43,3 @@ lerna-debug.log*
!.env.example !.env.example
!.env.appStore.example !.env.appStore.example
/client/* /client/*
/generated/prisma/*
+6
View File
@@ -16,8 +16,14 @@ ENV DATABASE_URL=${DATABASE_URL}
COPY . . COPY . .
RUN yarn install RUN yarn install
# Build prisma schema and make sure that it is linked to v2 node_modules
RUN yarn workspace @calcom/api-v2 run generate-schemas RUN yarn workspace @calcom/api-v2 run generate-schemas
RUN rm -rf apps/api/v2/node_modules
RUN yarn install
RUN yarn workspace @calcom/platform-libraries run build RUN yarn workspace @calcom/platform-libraries run build
RUN yarn workspace @calcom/api-v2 run build RUN yarn workspace @calcom/api-v2 run build
EXPOSE 80 EXPOSE 80
-4
View File
@@ -22,10 +22,6 @@ const loadConfig = (): AppConfig => {
db: { db: {
readUrl: getEnv("DATABASE_READ_URL"), readUrl: getEnv("DATABASE_READ_URL"),
writeUrl: getEnv("DATABASE_WRITE_URL"), writeUrl: getEnv("DATABASE_WRITE_URL"),
readPoolMax: getEnv("DATABASE_READ_POOL_MAX", 9),
writePoolMax: getEnv("DATABASE_WRITE_POOL_MAX", 7),
workerReadPoolMax: getEnv("DATABASE_READ_WORKER_POOL_MAX", 4),
workerWritePoolMax: getEnv("DATABASE_WRITE_WORKER_POOL_MAX", 6),
redisUrl: getEnv("REDIS_URL"), redisUrl: getEnv("REDIS_URL"),
}, },
next: { next: {
-4
View File
@@ -13,10 +13,6 @@ export type AppConfig = {
db: { db: {
readUrl: string; readUrl: string;
writeUrl: string; writeUrl: string;
readPoolMax: number;
writePoolMax: number;
workerReadPoolMax: number;
workerWritePoolMax: number;
redisUrl: string; redisUrl: string;
}; };
next: { next: {
@@ -9,8 +9,6 @@ import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/
import { InstantBookingModule } from "@/lib/modules/instant-booking.module"; import { InstantBookingModule } from "@/lib/modules/instant-booking.module";
import { RecurringBookingModule } from "@/lib/modules/recurring-booking.module"; import { RecurringBookingModule } from "@/lib/modules/recurring-booking.module";
import { RegularBookingModule } from "@/lib/modules/regular-booking.module"; import { RegularBookingModule } from "@/lib/modules/regular-booking.module";
import { PrismaEventTypeRepository } from "@/lib/repositories/prisma-event-type.repository";
import { PrismaTeamRepository } from "@/lib/repositories/prisma-team.repository";
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository"; import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
import { AppsRepository } from "@/modules/apps/apps.repository"; import { AppsRepository } from "@/modules/apps/apps.repository";
import { BillingModule } from "@/modules/billing/billing.module"; import { BillingModule } from "@/modules/billing/billing.module";
@@ -57,8 +55,6 @@ import { Module } from "@nestjs/common";
AppsRepository, AppsRepository,
CalendarsRepository, CalendarsRepository,
SelectedCalendarsRepository, SelectedCalendarsRepository,
PrismaEventTypeRepository,
PrismaTeamRepository,
], ],
controllers: [BookingsController_2024_04_15], controllers: [BookingsController_2024_04_15],
}) })
@@ -1,7 +1,6 @@
import { bootstrap } from "@/app"; import { bootstrap } from "@/app";
import { AppModule } from "@/app.module"; import { AppModule } from "@/app.module";
import { CreateBookingInput_2024_04_15 } from "@/ee/bookings/2024-04-15/inputs/create-booking.input"; import { CreateBookingInput_2024_04_15 } from "@/ee/bookings/2024-04-15/inputs/create-booking.input";
import { CreateRecurringBookingInput_2024_04_15 } from "@/ee/bookings/2024-04-15/inputs/create-recurring-booking.input";
import { GetBookingOutput_2024_04_15 } from "@/ee/bookings/2024-04-15/outputs/get-booking.output"; import { GetBookingOutput_2024_04_15 } from "@/ee/bookings/2024-04-15/outputs/get-booking.output";
import { GetBookingsOutput_2024_04_15 } from "@/ee/bookings/2024-04-15/outputs/get-bookings.output"; import { GetBookingsOutput_2024_04_15 } from "@/ee/bookings/2024-04-15/outputs/get-bookings.output";
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input"; import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
@@ -22,7 +21,6 @@ import { randomString } from "test/utils/randomString";
import { withApiAuth } from "test/utils/withApiAuth"; import { withApiAuth } from "test/utils/withApiAuth";
import { SUCCESS_STATUS } from "@calcom/platform-constants"; import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { BookingResponse } from "@calcom/platform-libraries";
import { type RegularBookingCreateResult } from "@calcom/platform-libraries/bookings"; import { type RegularBookingCreateResult } from "@calcom/platform-libraries/bookings";
import type { ApiSuccessResponse, ApiErrorResponse } from "@calcom/platform-types"; import type { ApiSuccessResponse, ApiErrorResponse } from "@calcom/platform-types";
import type { User } from "@calcom/prisma/client"; import type { User } from "@calcom/prisma/client";
@@ -42,7 +40,6 @@ describe("Bookings Endpoints 2024-04-15", () => {
let user: User; let user: User;
let eventTypeId: number; let eventTypeId: number;
let recEventTypeId: number;
let createdBooking: RegularBookingCreateResult; let createdBooking: RegularBookingCreateResult;
@@ -84,18 +81,6 @@ describe("Bookings Endpoints 2024-04-15", () => {
}, },
user.id user.id
); );
const recEventType = await eventTypesRepositoryFixture.create(
{
title: `rec-bookings-2024-04-15-event-type-${randomString()}-${describe.name}`,
slug: `rec-bookings-2024-04-15-event-type-${randomString()}-${describe.name}`,
length: 60,
recurringEvent: { freq: 2, count: 4, interval: 1 },
},
user.id
);
recEventTypeId = recEventType.id;
eventTypeId = event.id; eventTypeId = event.id;
app = moduleRef.createNestApplication(); app = moduleRef.createNestApplication();
@@ -419,210 +404,6 @@ describe("Bookings Endpoints 2024-04-15", () => {
}); });
}); });
it("should create recurring bookings", async () => {
const bookingEventTypeId = recEventTypeId;
const bookingTimeZone = "Europe/London";
const bookingLanguage = "en";
const bookingHashedLink = "";
const bookingMetadata = {
timeFormat: "12",
meetingType: "organizer-phone",
};
const bookingResponses = {
name: "tester",
email: "tester@example.com",
location: {
value: "link",
optionValue: "",
},
notes: "test",
};
const body: CreateRecurringBookingInput_2024_04_15[] = [
{
start: "2040-06-21T09:30:00.000Z",
end: "2040-06-21T10:30:00.000Z",
eventTypeId: bookingEventTypeId,
timeZone: bookingTimeZone,
language: bookingLanguage,
metadata: bookingMetadata,
hashedLink: bookingHashedLink,
responses: bookingResponses,
recurringEventId: "test-recurring-event-id",
},
{
start: "2040-06-27T09:30:00.000Z",
end: "2040-06-27T10:30:00.000Z",
eventTypeId: bookingEventTypeId,
timeZone: bookingTimeZone,
language: bookingLanguage,
metadata: bookingMetadata,
hashedLink: bookingHashedLink,
responses: bookingResponses,
recurringEventId: "test-recurring-event-id-2",
},
{
start: "2040-06-04T09:30:00.000Z",
end: "2040-06-04T10:30:00.000Z",
eventTypeId: bookingEventTypeId,
timeZone: bookingTimeZone,
language: bookingLanguage,
metadata: bookingMetadata,
hashedLink: bookingHashedLink,
responses: bookingResponses,
recurringEventId: "test-recurring-event-id-3",
},
{
start: "2040-06-11T09:30:00.000Z",
end: "2040-06-11T10:30:00.000Z",
eventTypeId: bookingEventTypeId,
timeZone: bookingTimeZone,
language: bookingLanguage,
metadata: bookingMetadata,
hashedLink: bookingHashedLink,
responses: bookingResponses,
recurringEventId: "test-recurring-event-id-4",
},
];
return request(app.getHttpServer())
.post("/v2/bookings/recurring")
.send(body)
.expect(201)
.then(async (response) => {
const responseBody: ApiSuccessResponse<BookingResponse[]> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
responseBody.data.forEach((booking) => {
expect(booking.userPrimaryEmail).toBeDefined();
expect(booking.userPrimaryEmail).toEqual(userEmail);
expect(booking.id).toBeDefined();
expect(booking.uid).toBeDefined();
expect(booking.eventTypeId).toEqual(bookingEventTypeId);
expect(booking.user.timeZone).toEqual(bookingTimeZone);
expect(booking.metadata).toEqual(bookingMetadata);
expect(booking.responses).toEqual(bookingResponses);
expect(booking.creationSource).toEqual("API_V2");
});
});
});
describe("event type booking requires authentication", () => {
let eventTypeRequiringAuthenticationId: number;
let unauthorizedUser: User;
let unauthorizedUserApiKeyString: string;
beforeAll(async () => {
const eventTypeRequiringAuthentication = await eventTypesRepositoryFixture.create(
{
title: `event-type-requiring-authentication-${randomString()}`,
slug: `event-type-requiring-authentication-${randomString()}`,
length: 60,
requiresConfirmation: true,
bookingRequiresAuthentication: true,
},
user.id
);
eventTypeRequiringAuthenticationId = eventTypeRequiringAuthentication.id;
const unauthorizedUserEmail = `unauthorized-user-${randomString()}@api.com`;
unauthorizedUser = await userRepositoryFixture.create({
email: unauthorizedUserEmail,
});
const { keyString } = await apiKeysRepositoryFixture.createApiKey(unauthorizedUser.id, null);
unauthorizedUserApiKeyString = keyString;
});
afterAll(async () => {
if (unauthorizedUser) {
await userRepositoryFixture.deleteByEmail(unauthorizedUser.email);
}
});
it("can't be booked without credentials", async () => {
const body: CreateBookingInput_2024_04_15 = {
start: "2040-05-23T09:30:00.000Z",
end: "2040-05-23T10:30:00.000Z",
eventTypeId: eventTypeRequiringAuthenticationId,
timeZone: "Europe/London",
language: "en",
metadata: {},
hashedLink: "",
responses: {
name: "External Attendee",
email: "external@example.com",
location: {
value: "link",
optionValue: "",
},
},
};
await request(app.getHttpServer()).post("/v2/bookings").send(body).expect(401);
});
it("can't be booked with unauthorized user credentials", async () => {
const body: CreateBookingInput_2024_04_15 = {
start: "2040-05-23T10:30:00.000Z",
end: "2040-05-23T11:30:00.000Z",
eventTypeId: eventTypeRequiringAuthenticationId,
timeZone: "Europe/London",
language: "en",
metadata: {},
hashedLink: "",
responses: {
name: "External Attendee",
email: "external@example.com",
location: {
value: "link",
optionValue: "",
},
},
};
await request(app.getHttpServer())
.post("/v2/bookings")
.send(body)
.set({ Authorization: `Bearer cal_test_${unauthorizedUserApiKeyString}` })
.expect(403);
});
it("can be booked with event type owner credentials", async () => {
const body: CreateBookingInput_2024_04_15 = {
start: "2040-05-23T11:30:00.000Z",
end: "2040-05-23T12:30:00.000Z",
eventTypeId: eventTypeRequiringAuthenticationId,
timeZone: "Europe/London",
language: "en",
metadata: {},
hashedLink: "",
responses: {
name: "External Attendee",
email: "external@example.com",
location: {
value: "link",
optionValue: "",
},
},
};
const response = await request(app.getHttpServer())
.post("/v2/bookings")
.send(body)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.expect(201);
const responseBody: ApiSuccessResponse<RegularBookingCreateResult> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
expect(responseBody.data.id).toBeDefined();
if (responseBody.data.id) {
await bookingsRepositoryFixture.deleteById(responseBody.data.id);
}
});
});
afterAll(async () => { afterAll(async () => {
await userRepositoryFixture.deleteByEmail(user.email); await userRepositoryFixture.deleteByEmail(user.email);
await bookingsRepositoryFixture.deleteAllBookings(user.id, user.email); await bookingsRepositoryFixture.deleteAllBookings(user.id, user.email);
@@ -7,20 +7,13 @@ import { MarkNoShowOutput_2024_04_15 } from "@/ee/bookings/2024-04-15/outputs/ma
import { PlatformBookingsService } from "@/ee/bookings/shared/platform-bookings.service"; import { PlatformBookingsService } from "@/ee/bookings/shared/platform-bookings.service";
import { sha256Hash, isApiKey, stripApiKey } from "@/lib/api-key"; import { sha256Hash, isApiKey, stripApiKey } from "@/lib/api-key";
import { VERSION_2024_04_15, VERSION_2024_06_11, VERSION_2024_06_14 } from "@/lib/api-versions"; import { VERSION_2024_04_15, VERSION_2024_06_11, VERSION_2024_06_14 } from "@/lib/api-versions";
import { PrismaEventTypeRepository } from "@/lib/repositories/prisma-event-type.repository";
import { PrismaTeamRepository } from "@/lib/repositories/prisma-team.repository";
import { InstantBookingCreateService } from "@/lib/services/instant-booking-create.service"; import { InstantBookingCreateService } from "@/lib/services/instant-booking-create.service";
import { RecurringBookingService } from "@/lib/services/recurring-booking.service"; import { RecurringBookingService } from "@/lib/services/recurring-booking.service";
import { RegularBookingService } from "@/lib/services/regular-booking.service"; import { RegularBookingService } from "@/lib/services/regular-booking.service";
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository"; import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
import {
AuthOptionalUser,
GetOptionalUser,
} from "@/modules/auth/decorators/get-optional-user/get-optional-user.decorator";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator"; import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator"; import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard"; import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { OptionalApiAuthGuard } from "@/modules/auth/guards/optional-api-auth/optional-api-auth.guard";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard"; import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { BillingService } from "@/modules/billing/services/billing.service"; import { BillingService } from "@/modules/billing/services/billing.service";
import { KyselyReadService } from "@/modules/kysely/kysely-read.service"; import { KyselyReadService } from "@/modules/kysely/kysely-read.service";
@@ -45,8 +38,6 @@ import {
NotFoundException, NotFoundException,
UseGuards, UseGuards,
BadRequestException, BadRequestException,
UnauthorizedException,
ForbiddenException,
} from "@nestjs/common"; } from "@nestjs/common";
import { ConfigService } from "@nestjs/config"; import { ConfigService } from "@nestjs/config";
import { ApiQuery, ApiExcludeController as DocsExcludeController } from "@nestjs/swagger"; import { ApiQuery, ApiExcludeController as DocsExcludeController } from "@nestjs/swagger";
@@ -122,9 +113,7 @@ export class BookingsController_2024_04_15 {
private readonly usersService: UsersService, private readonly usersService: UsersService,
private readonly regularBookingService: RegularBookingService, private readonly regularBookingService: RegularBookingService,
private readonly recurringBookingService: RecurringBookingService, private readonly recurringBookingService: RecurringBookingService,
private readonly instantBookingCreateService: InstantBookingCreateService, private readonly instantBookingCreateService: InstantBookingCreateService
private readonly eventTypeRepository: PrismaEventTypeRepository,
private readonly teamRepository: PrismaTeamRepository
) {} ) {}
@Get("/") @Get("/")
@@ -177,12 +166,8 @@ export class BookingsController_2024_04_15 {
} }
@Get("/:bookingUid/reschedule") @Get("/:bookingUid/reschedule")
@UseGuards(OptionalApiAuthGuard) async getBookingForReschedule(@Param("bookingUid") bookingUid: string): Promise<ApiResponse<unknown>> {
async getBookingForReschedule( const booking = await getBookingForReschedule(bookingUid);
@Param("bookingUid") bookingUid: string,
@GetOptionalUser() user: AuthOptionalUser
): Promise<ApiResponse<unknown>> {
const booking = await getBookingForReschedule(bookingUid, user?.id);
if (!booking) { if (!booking) {
throw new NotFoundException(`Booking with UID=${bookingUid} does not exist.`); throw new NotFoundException(`Booking with UID=${bookingUid} does not exist.`);
@@ -205,7 +190,6 @@ export class BookingsController_2024_04_15 {
clientId?.toString() || (await this.getOAuthClientIdFromEventType(body.eventTypeId)); clientId?.toString() || (await this.getOAuthClientIdFromEventType(body.eventTypeId));
const { orgSlug, locationUrl } = body; const { orgSlug, locationUrl } = body;
try { try {
await this.checkBookingRequiresAuthentication(req, body.eventTypeId);
const bookingRequest = await this.createNextApiBookingRequest(req, oAuthClientId, locationUrl, isEmbed); const bookingRequest = await this.createNextApiBookingRequest(req, oAuthClientId, locationUrl, isEmbed);
const booking = await this.regularBookingService.createBooking({ const booking = await this.regularBookingService.createBooking({
bookingData: bookingRequest.body, bookingData: bookingRequest.body,
@@ -334,9 +318,11 @@ export class BookingsController_2024_04_15 {
recurringEvent.recurringEventId = recurringEventId; recurringEvent.recurringEventId = recurringEventId;
} }
} }
const bookingRequest = await this.createNextApiBookingRequest(req, oAuthClientId, undefined, isEmbed); const bookingRequest = await this.createNextApiBookingRequest(req, oAuthClientId, undefined, isEmbed);
const createdBookings: BookingResponse[] = await this.recurringBookingService.createBooking({ const createdBookings: BookingResponse[] = await this.recurringBookingService.createBooking({
bookingData: body.map((booking) => ({ ...booking, creationSource: CreationSource.API_V2 })), bookingData: bookingRequest.body,
bookingMeta: { bookingMeta: {
userId: bookingRequest.userId, userId: bookingRequest.userId,
hostname: bookingRequest.headers?.host || "", hostname: bookingRequest.headers?.host || "",
@@ -345,7 +331,6 @@ export class BookingsController_2024_04_15 {
platformCancelUrl: bookingRequest.platformCancelUrl, platformCancelUrl: bookingRequest.platformCancelUrl,
platformBookingUrl: bookingRequest.platformBookingUrl, platformBookingUrl: bookingRequest.platformBookingUrl,
platformBookingLocation: bookingRequest.platformBookingLocation, platformBookingLocation: bookingRequest.platformBookingLocation,
noEmail: bookingRequest.body.noEmail,
}, },
}); });
@@ -459,48 +444,6 @@ export class BookingsController_2024_04_15 {
return oAuthClientParams.platformClientId; return oAuthClientParams.platformClientId;
} }
private async checkBookingRequiresAuthentication(req: Request, eventTypeId: number): Promise<void> {
const eventType = await this.eventTypeRepository.findByIdIncludeHostsAndTeamMembers({
id: eventTypeId,
});
if (!eventType?.bookingRequiresAuthentication) {
return;
}
const userId = await this.getOwnerId(req);
if (!userId) {
throw new UnauthorizedException(
"This event type requires authentication. Please provide valid credentials."
);
}
const isEventTypeOwner = eventType.userId === userId;
const isHost = eventType.hosts.some((host) => host.userId === userId);
const isTeamAdminOrOwner =
eventType.team?.members.some((member) => member.userId === userId) ?? false;
let isOrgAdminOrOwner = false;
if (eventType.team?.parentId) {
const orgTeam = await this.teamRepository.getTeamByIdIfUserIsAdmin({
userId,
teamId: eventType.team.parentId,
});
isOrgAdminOrOwner = !!orgTeam;
} else if (eventType.team?.isOrganization) {
isOrgAdminOrOwner = isTeamAdminOrOwner;
}
const isAuthorized = isEventTypeOwner || isHost || isTeamAdminOrOwner || isOrgAdminOrOwner;
if (!isAuthorized) {
throw new ForbiddenException(
"You are not authorized to book this event type. You must be the event type owner, a host, a team admin/owner, or an organization admin/owner."
);
}
}
private async getOAuthClientsParams(clientId: string, isEmbed = false): Promise<OAuthRequestParams> { private async getOAuthClientsParams(clientId: string, isEmbed = false): Promise<OAuthRequestParams> {
const res = { ...DEFAULT_PLATFORM_PARAMS }; const res = { ...DEFAULT_PLATFORM_PARAMS };
@@ -560,10 +503,7 @@ export class BookingsController_2024_04_15 {
return clone as unknown as NextApiRequest & { userId?: number } & OAuthRequestParams; return clone as unknown as NextApiRequest & { userId?: number } & OAuthRequestParams;
} }
async setPlatformAttendeesEmails( async setPlatformAttendeesEmails(requestBody: any, oAuthClientId: string): Promise<void> {
requestBody: { responses?: { email?: string; guests?: string[] } },
oAuthClientId: string
): Promise<void> {
if (requestBody?.responses?.email) { if (requestBody?.responses?.email) {
requestBody.responses.email = await this.platformBookingsService.getPlatformAttendeeEmail( requestBody.responses.email = await this.platformBookingsService.getPlatformAttendeeEmail(
requestBody.responses.email, requestBody.responses.email,
@@ -625,9 +565,6 @@ export class BookingsController_2024_04_15 {
if (err instanceof Error) { if (err instanceof Error) {
const error = err as Error; const error = err as Error;
if (err instanceof HttpException) {
throw new HttpException(err.getResponse(), err.getStatus());
}
if (Object.values(ErrorCode).includes(error.message as unknown as ErrorCode)) { if (Object.values(ErrorCode).includes(error.message as unknown as ErrorCode)) {
throw new HttpException(error.message, 400); throw new HttpException(error.message, 400);
} }
@@ -21,7 +21,7 @@ export class CreateRecurringBookingInput_2024_04_15 extends CreateBookingInput_2
@IsOptional() @IsOptional()
@ApiPropertyOptional({ type: [Object] }) @ApiPropertyOptional({ type: [Object] })
allRecurringDates?: { start: string; end: string | undefined }[]; allRecurringDates?: Record<string, string>[];
@IsOptional() @IsOptional()
@IsNumber() @IsNumber()
@@ -9,7 +9,7 @@ export class BookingReferencesRepository_2024_08_13 {
constructor(private readonly dbRead: PrismaReadService) {} constructor(private readonly dbRead: PrismaReadService) {}
async getBookingReferences(bookingId: number, filter?: BookingReferencesFilterInput_2024_08_13) { async getBookingReferences(bookingId: number, filter?: BookingReferencesFilterInput_2024_08_13) {
const whereClause: Prisma.BookingReferenceWhereInput = { bookingId, deleted: null }; const whereClause: Prisma.BookingReferenceWhereInput = { bookingId };
if (filter?.type) { if (filter?.type) {
whereClause.type = filter.type; whereClause.type = filter.type;
@@ -30,7 +30,6 @@ export class BookingReferencesRepository_2024_08_13 {
return this.dbRead.prisma.bookingReference.findFirst({ return this.dbRead.prisma.bookingReference.findFirst({
where: { where: {
uid: eventUid, uid: eventUid,
deleted: null,
}, },
include: { include: {
credential: true, credential: true,
@@ -1,8 +1,6 @@
import { BookingGuestsController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/booking-guests.controller"; import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/booking-references.repository";
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.repository";
import { BookingsController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/bookings.controller"; import { BookingsController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/bookings.controller";
import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/booking-references.repository";
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository";
import { BookingGuestsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-guests.service";
import { BookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-references.service"; import { BookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-references.service";
import { BookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/bookings.service"; import { BookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/bookings.service";
import { CalVideoService } from "@/ee/bookings/2024-08-13/services/cal-video.service"; import { CalVideoService } from "@/ee/bookings/2024-08-13/services/cal-video.service";
@@ -17,7 +15,6 @@ import { CalendarsService } from "@/ee/calendars/services/calendars.service";
import { EventTypesModule_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/event-types.module"; import { EventTypesModule_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/event-types.module";
import { EventTypesModule_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.module"; import { EventTypesModule_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.module";
import { EventTypesRepository_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.repository"; import { EventTypesRepository_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.repository";
import { OutputEventTypesService_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/services/output-event-types.service";
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module"; import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
import { InstantBookingModule } from "@/lib/modules/instant-booking.module"; import { InstantBookingModule } from "@/lib/modules/instant-booking.module";
import { RecurringBookingModule } from "@/lib/modules/recurring-booking.module"; import { RecurringBookingModule } from "@/lib/modules/recurring-booking.module";
@@ -74,11 +71,9 @@ import { Module } from "@nestjs/common";
OAuthClientRepository, OAuthClientRepository,
OAuthClientUsersService, OAuthClientUsersService,
BookingsService_2024_08_13, BookingsService_2024_08_13,
BookingGuestsService_2024_08_13,
InputBookingsService_2024_08_13, InputBookingsService_2024_08_13,
OutputBookingsService_2024_08_13, OutputBookingsService_2024_08_13,
OutputBookingReferencesService_2024_08_13, OutputBookingReferencesService_2024_08_13,
OutputEventTypesService_2024_06_14,
BookingsRepository_2024_08_13, BookingsRepository_2024_08_13,
EventTypesRepository_2024_06_14, EventTypesRepository_2024_06_14,
BookingSeatRepository, BookingSeatRepository,
@@ -97,7 +92,7 @@ import { Module } from "@nestjs/common";
BookingReferencesRepository_2024_08_13, BookingReferencesRepository_2024_08_13,
CalVideoService, CalVideoService,
], ],
controllers: [BookingsController_2024_08_13, BookingGuestsController_2024_08_13], controllers: [BookingsController_2024_08_13],
exports: [InputBookingsService_2024_08_13, OutputBookingsService_2024_08_13, BookingsService_2024_08_13], exports: [InputBookingsService_2024_08_13, OutputBookingsService_2024_08_13, BookingsService_2024_08_13],
}) })
export class BookingsModule_2024_08_13 {} export class BookingsModule_2024_08_13 {}
@@ -50,20 +50,6 @@ export class BookingsRepository_2024_08_13 {
}); });
} }
async getByUidWithUserIdAndSeatsReferencesCount(bookingUid: string) {
return this.dbRead.prisma.booking.findUnique({
where: {
uid: bookingUid,
},
select: {
userId: true,
seatsReferences: {
take: 1,
},
},
});
}
async getByUid(bookingUid: string) { async getByUid(bookingUid: string) {
return this.dbRead.prisma.booking.findUnique({ return this.dbRead.prisma.booking.findUnique({
where: { where: {
@@ -1,67 +0,0 @@
import { BookingUidGuard } from "@/ee/bookings/2024-08-13/guards/booking-uid.guard";
import { AddGuestsOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/add-guests.output";
import { BookingGuestsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-guests.service";
import { VERSION_2024_08_13_VALUE, VERSION_2024_08_13 } from "@/lib/api-versions";
import { API_KEY_OR_ACCESS_TOKEN_HEADER } from "@/lib/docs/headers";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { Controller, Post, Logger, Body, UseGuards, Param, HttpCode, HttpStatus } from "@nestjs/common";
import { ApiOperation, ApiTags as DocsTags, ApiHeader } from "@nestjs/swagger";
import { BOOKING_WRITE, SUCCESS_STATUS } from "@calcom/platform-constants";
import { AddGuestsInput_2024_08_13 } from "@calcom/platform-types";
@Controller({
path: "/v2/bookings/:bookingUid/guests",
version: VERSION_2024_08_13_VALUE,
})
@UseGuards(PermissionsGuard)
@DocsTags("Bookings / Guests")
@ApiHeader({
name: "cal-api-version",
description: `Must be set to ${VERSION_2024_08_13}. This header is required as this endpoint does not exist in older API versions.`,
example: VERSION_2024_08_13,
required: true,
})
export class BookingGuestsController_2024_08_13 {
private readonly logger = new Logger("BookingGuestsController_2024_08_13");
constructor(private readonly bookingGuestsService: BookingGuestsService_2024_08_13) {}
@Post("/")
@HttpCode(HttpStatus.OK)
@Permissions([BOOKING_WRITE])
@UseGuards(ApiAuthGuard, BookingUidGuard)
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
@ApiOperation({
summary: "Add guests to an existing booking",
description: `Add one or more guests to an existing booking.
**Email Notifications:**
When guests are added, the following notifications are sent (unless disabled by event type settings):
- **Organizer & Team Members:** Receive an "Add Guests" notification email informing them that new guests have been added to the booking.
- **New Guests:** Receive a "Scheduled Event" email with full booking details and calendar invite. If they have a phone number, they also receive an SMS notification.
- **Existing Guests:** Receive an "Add Guests" notification email informing them that additional guests have been added to the booking.
<Note>The cal-api-version header is required for this endpoint. Without it, the request will fail with a 404 error.</Note>
`,
})
async addGuests(
@Param("bookingUid") bookingUid: string,
@Body() body: AddGuestsInput_2024_08_13,
@GetUser() user: ApiAuthGuardUser
): Promise<AddGuestsOutput_2024_08_13> {
const booking = await this.bookingGuestsService.addGuests(bookingUid, body, user);
return {
status: SUCCESS_STATUS,
data: booking,
};
}
}
@@ -134,8 +134,6 @@ export class BookingsController_2024_08_13 {
If you are creating a seated booking for an event type with 'show attendees' disabled, then to retrieve attendees in the response either set 'show attendees' to true on event type level or If you are creating a seated booking for an event type with 'show attendees' disabled, then to retrieve attendees in the response either set 'show attendees' to true on event type level or
you have to provide an authentication method of event type owner, host, team admin or owner or org admin or owner. you have to provide an authentication method of event type owner, host, team admin or owner or org admin or owner.
For event types that have SMS reminders workflow, you need to pass the attendee's phone number in the request body via \`attendee.phoneNumber\` (e.g., "+19876543210" in international format). This is an optional field, but becomes required when SMS reminders are enabled for the event type. For the complete attendee object structure, see the [attendee object](https://cal.com/docs/api-reference/v2/bookings/create-a-booking#body-attendee) documentation.
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note> <Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
`, `,
}) })
@@ -290,7 +288,7 @@ export class BookingsController_2024_08_13 {
{ $ref: getSchemaPath(RescheduleSeatedBookingInput_2024_08_13) }, { $ref: getSchemaPath(RescheduleSeatedBookingInput_2024_08_13) },
], ],
}, },
description: `Accepts different types of reschedule booking input: Reschedule Booking (Option 1) or Reschedule Seated Booking (Option 2). If you're rescheduling a seated booking as org admin of booking host, pass booking input for Reschedule Booking (Option 1) along with your access token in the request header. description: `Accepts different types of reschedule booking input: Reschedule Booking (Option 1) or Reschedule Seated Booking (Option 2).
If you are rescheduling a seated booking for an event type with 'show attendees' disabled, then to retrieve attendees in the response either set 'show attendees' to true on event type level or If you are rescheduling a seated booking for an event type with 'show attendees' disabled, then to retrieve attendees in the response either set 'show attendees' to true on event type level or
you have to provide an authentication method of event type owner, host, team admin or owner or org admin or owner.`, you have to provide an authentication method of event type owner, host, team admin or owner or org admin or owner.`,
@@ -322,13 +320,10 @@ export class BookingsController_2024_08_13 {
summary: "Cancel a booking", summary: "Cancel a booking",
description: `:bookingUid can be :bookingUid of an usual booking, individual recurrence or recurring booking to cancel all recurrences. description: `:bookingUid can be :bookingUid of an usual booking, individual recurrence or recurring booking to cancel all recurrences.
\nCancelling normal bookings:
If the booking is not seated and not recurring, simply pass :bookingUid in the request URL \`/bookings/:bookingUid/cancel\` and optionally cancellationReason in the request body \`{"cancellationReason": "Will travel"}\`.
\nCancelling seated bookings: \nCancelling seated bookings:
It is possible to cancel specific seat within a booking as an attendee or all of the seats as the host. It is possible to cancel specific seat within a booking as an attendee or all of the seats as the host.
\n1. As an attendee - provide :bookingUid in the request URL \`/bookings/:bookingUid/cancel\` and seatUid in the request body \`{"seatUid": "123-123-123"}\` . This will remove this particular attendance from the booking. \n1. As an attendee - provide :bookingUid in the request URL \`/bookings/:bookingUid/cancel\` and seatUid in the request body \`{"seatUid": "123-123-123"}\` . This will remove this particular attendance from the booking.
\n2. As the host or org admin of host - host can cancel booking for all attendees aka for every seat, this also applies to org admins. Provide :bookingUid in the request URL \`/bookings/:bookingUid/cancel\` and cancellationReason in the request body \`{"cancellationReason": "Will travel"}\` and \`Authorization: Bearer token\` request header where token is event type owner (host) credential. This will cancel the booking for all attendees. \n2. As the host - host can cancel booking for all attendees aka for every seat. Provide :bookingUid in the request URL \`/bookings/:bookingUid/cancel\` and cancellationReason in the request body \`{"cancellationReason": "Will travel"}\` and \`Authorization: Bearer token\` request header where token is event type owner (host) credential. This will cancel the booking for all attendees.
\nCancelling recurring seated bookings: \nCancelling recurring seated bookings:
For recurring seated bookings it is not possible to cancel all of them with 1 call For recurring seated bookings it is not possible to cancel all of them with 1 call
@@ -348,7 +343,7 @@ export class BookingsController_2024_08_13 {
], ],
}, },
description: description:
"Accepts different types of cancel booking input: Cancel Booking (Option 1 which is for normal or recurring bookings) or Cancel Seated Booking (Option 2 which is for seated bookings)", "Accepts different types of cancel booking input: Cancel Booking (Option 1) or Cancel Seated Booking (Option 2)",
}) })
@ApiExtraModels(CancelBookingInput_2024_08_13, CancelSeatedBookingInput_2024_08_13) @ApiExtraModels(CancelBookingInput_2024_08_13, CancelSeatedBookingInput_2024_08_13)
async cancelBooking( async cancelBooking(
@@ -1,523 +0,0 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { AddGuestsOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/add-guests.output";
import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output";
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { UsersModule } from "@/modules/users/users.module";
import { INestApplication } from "@nestjs/common";
import { NestExpressApplication } from "@nestjs/platform-express";
import { Test } from "@nestjs/testing";
import * as request from "supertest";
import { BookingsRepositoryFixture } from "test/fixtures/repository/bookings.repository.fixture";
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
import { TokensRepositoryFixture } from "test/fixtures/repository/tokens.repository.fixture";
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
import { randomString } from "test/utils/randomString";
import {
CAL_API_VERSION_HEADER,
ERROR_STATUS,
SUCCESS_STATUS,
VERSION_2024_08_13,
} from "@calcom/platform-constants";
import {
AttendeeAddGuestsEmail,
AttendeeScheduledEmail,
OrganizerAddGuestsEmail,
} from "@calcom/platform-libraries/emails";
import type { BookingOutput_2024_08_13, CreateBookingInput_2024_08_13 } from "@calcom/platform-types";
import type { User, Team } from "@calcom/prisma/client";
const attendeeAddGuestsEmailSpy = jest
.spyOn(AttendeeAddGuestsEmail.prototype, "getHtml")
.mockImplementation(() => Promise.resolve("<p>email</p>"));
const organizerAddGuestsEmailSpy = jest
.spyOn(OrganizerAddGuestsEmail.prototype, "getHtml")
.mockImplementation(() => Promise.resolve("<p>email</p>"));
const attendeeScheduledEmailSpy = jest
.spyOn(AttendeeScheduledEmail.prototype, "getHtml")
.mockImplementation(() => Promise.resolve("<p>email</p>"));
type TestUser = {
user: User;
accessToken: string;
refreshToken: string;
};
type TestSetup = {
organizer: TestUser;
unrelatedUser: TestUser;
guest: TestUser;
eventTypeId: number;
bookingUid: string;
};
describe("Bookings Endpoints 2024-08-13 add guests", () => {
let app: INestApplication;
let organization: Team;
let userRepositoryFixture: UserRepositoryFixture;
let bookingsRepositoryFixture: BookingsRepositoryFixture;
let schedulesService: SchedulesService_2024_04_15;
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
let teamRepositoryFixture: TeamRepositoryFixture;
let tokensRepositoryFixture: TokensRepositoryFixture;
let testSetup: TestSetup;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15],
})
.overrideGuard(PermissionsGuard)
.useValue({
canActivate: () => true,
})
.compile();
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef);
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
schedulesService = moduleRef.get<SchedulesService_2024_04_15>(SchedulesService_2024_04_15);
tokensRepositoryFixture = new TokensRepositoryFixture(moduleRef);
organization = await teamRepositoryFixture.create({
name: `user-emails-2024-08-13-organization-${randomString()}`,
});
await setupTestData();
app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication);
await app.init();
});
async function setupTestData() {
const oAuthClient = await createOAuthClient(organization.id, true);
const organizerUser = await userRepositoryFixture.create({
email: `user-emails-2024-08-13-organizer-${randomString()}@api.com`,
platformOAuthClients: {
connect: { id: oAuthClient.id },
},
});
const unrelatedUserData = await userRepositoryFixture.create({
email: `user-emails-2024-08-13-unrelated-${randomString()}@api.com`,
platformOAuthClients: {
connect: { id: oAuthClient.id },
},
});
const guestUser = await userRepositoryFixture.create({
email: `user-emails-2024-08-13-guest-${randomString()}@api.com`,
platformOAuthClients: {
connect: { id: oAuthClient.id },
},
});
const organizerTokens = await tokensRepositoryFixture.createTokens(organizerUser.id, oAuthClient.id);
const unrelatedUserTokens = await tokensRepositoryFixture.createTokens(
unrelatedUserData.id,
oAuthClient.id
);
const guestTokens = await tokensRepositoryFixture.createTokens(guestUser.id, oAuthClient.id);
const schedule: CreateScheduleInput_2024_04_15 = {
name: `user-add-guests-2024-08-13-schedule-${randomString()}`,
timeZone: "Europe/Rome",
isDefault: true,
};
await schedulesService.createUserSchedule(organizerUser.id, schedule);
const eventType = await eventTypesRepositoryFixture.create(
{
title: `user-add-guests-2024-08-13-event-type-${randomString()}`,
slug: `user-add-guests-2024-08-13-event-type-${randomString()}`,
length: 60,
},
organizerUser.id
);
testSetup = {
organizer: {
user: organizerUser,
accessToken: organizerTokens.accessToken,
refreshToken: organizerTokens.refreshToken,
},
unrelatedUser: {
user: unrelatedUserData,
accessToken: unrelatedUserTokens.accessToken,
refreshToken: unrelatedUserTokens.refreshToken,
},
guest: {
user: guestUser,
accessToken: guestTokens.accessToken,
refreshToken: guestTokens.refreshToken,
},
eventTypeId: eventType.id,
bookingUid: "",
};
}
async function createOAuthClient(organizationId: number, emailsEnabled: boolean) {
const data = {
logo: "logo-url",
name: "name",
redirectUris: ["http://localhost:5555"],
permissions: 32,
areEmailsEnabled: emailsEnabled,
};
const secret = "secret";
const client = await oauthClientRepositoryFixture.create(organizationId, data, secret);
return client;
}
beforeEach(async () => {
attendeeAddGuestsEmailSpy.mockClear();
organizerAddGuestsEmailSpy.mockClear();
attendeeScheduledEmailSpy.mockClear();
});
describe("POST /v2/bookings/:bookingUid/guests", () => {
beforeAll(async () => {
const createBookingBody: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 0, 8, 13, 0, 0)).toISOString(),
eventTypeId: testSetup.eventTypeId,
attendee: {
name: "Mr Proper",
email: "mr_proper@gmail.com",
timeZone: "Europe/Rome",
language: "it",
},
location: "https://meet.google.com/abc-def-ghi",
bookingFieldsResponses: {
customField: "customValue",
},
metadata: {
userId: "100",
},
};
const createBookingResponse = await request(app.getHttpServer())
.post("/v2/bookings")
.send(createBookingBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201);
const createBookingResponseBody: CreateBookingOutput_2024_08_13 = createBookingResponse.body;
expect(createBookingResponseBody.status).toEqual(SUCCESS_STATUS);
if (!responseDataIsBooking(createBookingResponseBody.data)) {
throw new Error(
"Invalid response data - expected booking but received array of possibly recurring bookings"
);
}
testSetup.bookingUid = createBookingResponseBody.data.uid;
});
describe("Authentication", () => {
it("should return 401 when adding guests without authentication", async () => {
const addGuestsBody = {
guests: [{ email: "unauthenticated.guest@example.com" }],
};
const addGuestsResponse = await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/guests`)
.send(addGuestsBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
expect(addGuestsResponse.status).toBe(401);
});
});
describe("Authorization - Organizer", () => {
it("should allow booking organizer to add multiple guests", async () => {
const addGuestsBody = {
guests: [{ email: "organizer.guest1@example.com" }, { email: "organizer.guest2@example.com" }],
};
const addGuestsResponse = await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/guests`)
.send(addGuestsBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
.expect(200);
const addGuestsResponseBody: AddGuestsOutput_2024_08_13 = addGuestsResponse.body;
verifyAddGuestsResponse(
addGuestsResponseBody,
["organizer.guest1@example.com", "organizer.guest2@example.com"],
true
);
});
it("should return 403 when unrelated user tries to add guests", async () => {
const addGuestsBody = {
guests: [
{ email: "non-organizer.guest1@example.com" },
{ email: "non-organizer.guest2@example.com" },
],
};
await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/guests`)
.send(addGuestsBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.unrelatedUser.accessToken}`)
.expect(403);
});
});
describe("Authorization - guest", () => {
it("should allow organizer to add a user as guest, then guest can add more guests", async () => {
// Step 1: Organizer adds guest user as a guest
const addguestBody = {
guests: [{ email: testSetup.guest.user.email }],
};
const addguestResponse = await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/guests`)
.send(addguestBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
.expect(200);
const addguestResponseBody: AddGuestsOutput_2024_08_13 = addguestResponse.body;
verifyAddGuestsResponse(addguestResponseBody, [testSetup.guest.user.email], true);
// Step 2: Now the guest can add their own guests
const addGuestsBody = {
guests: [{ email: "guest.guest1@example.com" }],
};
const addGuestsResponse = await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/guests`)
.send(addGuestsBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.guest.accessToken}`)
.expect(200);
const addGuestsResponseBody: AddGuestsOutput_2024_08_13 = addGuestsResponse.body;
verifyAddGuestsResponse(addGuestsResponseBody, ["guest.guest1@example.com"], true);
});
it("should return 403 when non-guest user tries to add guests", async () => {
const addGuestsBody = {
guests: [{ email: "non-guest.guest1@example.com" }, { email: "non-guest.guest2@example.com" }],
};
await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/guests`)
.send(addGuestsBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.unrelatedUser.accessToken}`)
.expect(403);
});
});
describe("Validation", () => {
it("should return 400 when attempting to add duplicate guest email", async () => {
const addGuestsBody = {
guests: [{ email: "organizer.guest1@example.com" }],
};
const addGuestsResponse = await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/guests`)
.send(addGuestsBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`);
expect(addGuestsResponse.status).toEqual(400);
expect(addGuestsResponse.body.status).toEqual(ERROR_STATUS);
});
});
});
describe("POST /v2/bookings/:bookingUid/guests - Emails Disabled", () => {
let emailsDisabledSetup: TestSetup;
beforeAll(async () => {
const oAuthClientDisabled = await createOAuthClient(organization.id, false);
const organizerUser = await userRepositoryFixture.create({
email: `user-no-emails-2024-08-13-organizer-${randomString()}@api.com`,
platformOAuthClients: {
connect: { id: oAuthClientDisabled.id },
},
});
const organizerTokens = await tokensRepositoryFixture.createTokens(
organizerUser.id,
oAuthClientDisabled.id
);
const schedule: CreateScheduleInput_2024_04_15 = {
name: `user-no-emails-2024-08-13-schedule-${randomString()}`,
timeZone: "Europe/Rome",
isDefault: true,
};
await schedulesService.createUserSchedule(organizerUser.id, schedule);
const eventType = await eventTypesRepositoryFixture.create(
{
title: `user-no-emails-2024-08-13-event-type-${randomString()}`,
slug: `user-no-emails-2024-08-13-event-type-${randomString()}`,
length: 60,
},
organizerUser.id
);
const createBookingBody: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 0, 9, 14, 0, 0)).toISOString(),
eventTypeId: eventType.id,
attendee: {
name: "No Email User",
email: "no.email.user@gmail.com",
timeZone: "Europe/Rome",
language: "it",
},
location: "https://meet.google.com/no-emails",
bookingFieldsResponses: {
customField: "noEmailValue",
},
metadata: {
userId: "200",
},
};
const createBookingResponse = await request(app.getHttpServer())
.post("/v2/bookings")
.send(createBookingBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201);
const createBookingResponseBody: CreateBookingOutput_2024_08_13 = createBookingResponse.body;
if (!responseDataIsBooking(createBookingResponseBody.data)) {
throw new Error(
"Invalid response data - expected booking but received array of possibly recurring bookings"
);
}
emailsDisabledSetup = {
organizer: {
user: organizerUser,
accessToken: organizerTokens.accessToken,
refreshToken: organizerTokens.refreshToken,
},
unrelatedUser: testSetup.unrelatedUser,
guest: testSetup.guest,
eventTypeId: eventType.id,
bookingUid: createBookingResponseBody.data.uid,
};
});
it("should NOT send emails when adding guests (emails disabled)", async () => {
attendeeAddGuestsEmailSpy.mockClear();
organizerAddGuestsEmailSpy.mockClear();
attendeeScheduledEmailSpy.mockClear();
const addGuestsBody = {
guests: [{ email: "no-email.guest1@example.com" }, { email: "no-email.guest2@example.com" }],
};
const addGuestsResponse = await request(app.getHttpServer())
.post(`/v2/bookings/${emailsDisabledSetup.bookingUid}/guests`)
.send(addGuestsBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${emailsDisabledSetup.organizer.accessToken}`)
.expect(200);
const addGuestsResponseBody: AddGuestsOutput_2024_08_13 = addGuestsResponse.body;
verifyAddGuestsResponse(
addGuestsResponseBody,
["no-email.guest1@example.com", "no-email.guest2@example.com"],
false
);
});
afterAll(async () => {
await userRepositoryFixture.deleteByEmail(emailsDisabledSetup.organizer.user.email);
await bookingsRepositoryFixture.deleteAllBookings(
emailsDisabledSetup.organizer.user.id,
emailsDisabledSetup.organizer.user.email
);
});
});
afterAll(async () => {
await teamRepositoryFixture.delete(organization.id);
await userRepositoryFixture.deleteByEmail(testSetup.organizer.user.email);
await userRepositoryFixture.deleteByEmail(testSetup.unrelatedUser.user.email);
await userRepositoryFixture.deleteByEmail(testSetup.guest.user.email);
await bookingsRepositoryFixture.deleteAllBookings(
testSetup.organizer.user.id,
testSetup.organizer.user.email
);
await app.close();
});
function responseDataIsBooking(data: unknown): data is BookingOutput_2024_08_13 {
return !Array.isArray(data) && typeof data === "object" && data !== null && "id" in data;
}
function verifyAddGuestsResponse(
responseBody: AddGuestsOutput_2024_08_13,
expectedGuestEmails: string[],
shouldEmailsBeSent: boolean
): BookingOutput_2024_08_13 {
expect(responseBody.status).toEqual(SUCCESS_STATUS);
if (!responseDataIsBooking(responseBody.data)) {
throw new Error(
"Invalid response data - expected booking but received array of possibly recurring bookings"
);
}
const bookingData = responseBody.data;
expect(bookingData.guests).toBeDefined();
const guestEmails = bookingData.guests;
expectedGuestEmails.forEach((email) => {
expect(guestEmails).toContain(email);
});
expect(bookingData.guests).toBeDefined();
expectedGuestEmails.forEach((email) => {
expect(bookingData.guests).toContain(email);
});
if (shouldEmailsBeSent) {
expect(attendeeAddGuestsEmailSpy).toHaveBeenCalled();
expect(organizerAddGuestsEmailSpy).toHaveBeenCalled();
expect(attendeeScheduledEmailSpy).toHaveBeenCalled();
} else {
expect(attendeeAddGuestsEmailSpy).not.toHaveBeenCalled();
expect(organizerAddGuestsEmailSpy).not.toHaveBeenCalled();
expect(attendeeScheduledEmailSpy).not.toHaveBeenCalled();
}
return bookingData;
}
});
@@ -70,7 +70,6 @@ describe("Managed user bookings 2024-08-13", () => {
let firstManagedUserEventTypeId: number; let firstManagedUserEventTypeId: number;
let eventTypeRequiresConfirmationId: number; let eventTypeRequiresConfirmationId: number;
let seatedEventTypeId: number;
const orgAdminManagedUserEmail = `managed-user-bookings-2024-08-13-org-admin-${randomString()}@api.com`; const orgAdminManagedUserEmail = `managed-user-bookings-2024-08-13-org-admin-${randomString()}@api.com`;
let orgAdminManagedUser: CreateManagedUserData; let orgAdminManagedUser: CreateManagedUserData;
@@ -310,20 +309,6 @@ describe("Managed user bookings 2024-08-13", () => {
eventTypeRequiresConfirmationId = eventTypeRequiresConfirmation.id; eventTypeRequiresConfirmationId = eventTypeRequiresConfirmation.id;
}); });
it("should create a seated event type for first managed user", async () => {
const seatedEventType = await eventTypesRepositoryFixture.create(
{
title: `managed-user-bookings-seated-event-type-${randomString()}`,
slug: `managed-user-bookings-seated-event-type-${randomString()}`,
length: 30,
seatsPerTimeSlot: 5,
seatsShowAttendees: true,
},
firstManagedUser.user.id
);
seatedEventTypeId = seatedEventType.id;
});
describe("bookings using original emails", () => { describe("bookings using original emails", () => {
it("managed user should be booked by managed user attendee and booking shows up in both users' bookings", async () => { it("managed user should be booked by managed user attendee and booking shows up in both users' bookings", async () => {
const body: CreateBookingInput_2024_08_13 = { const body: CreateBookingInput_2024_08_13 = {
@@ -788,107 +773,6 @@ describe("Managed user bookings 2024-08-13", () => {
}); });
}); });
describe("seated booking management by org admin", () => {
let seatedBookingUid: string;
it("should create a seated booking with multiple attendees", async () => {
const bodyOne: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 0, 10, 10, 0, 0)).toISOString(),
eventTypeId: seatedEventTypeId,
attendee: {
name: secondManagedUser.user.name!,
email: secondManagedUser.user.email,
timeZone: secondManagedUser.user.timeZone,
language: secondManagedUser.user.locale,
},
};
const responseOne = await request(app.getHttpServer())
.post("/v2/bookings")
.send(bodyOne)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201);
const responseBodyForFirstAttendee: ApiSuccessResponse<BookingOutput_2024_08_13> = responseOne.body;
expect(responseBodyForFirstAttendee.status).toEqual(SUCCESS_STATUS);
expect(responseBodyForFirstAttendee.data).toBeDefined();
const bookingDataForFirstAttendee = responseBodyForFirstAttendee.data as BookingOutput_2024_08_13;
seatedBookingUid = bookingDataForFirstAttendee.uid;
expect(bookingDataForFirstAttendee.attendees).toBeDefined();
expect(bookingDataForFirstAttendee.attendees.length).toBeGreaterThan(0);
const bodyTwo: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 0, 10, 10, 0, 0)).toISOString(),
eventTypeId: seatedEventTypeId,
attendee: {
name: thirdManagedUser.user.name!,
email: thirdManagedUser.user.email,
timeZone: thirdManagedUser.user.timeZone,
language: thirdManagedUser.user.locale,
},
};
const responseTwo = await request(app.getHttpServer())
.post("/v2/bookings")
.send(bodyTwo)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201);
const responseBodyForSecondAttendee: ApiSuccessResponse<BookingOutput_2024_08_13> = responseTwo.body;
expect(responseBodyForSecondAttendee.status).toEqual(SUCCESS_STATUS);
expect(responseBodyForSecondAttendee.data).toBeDefined();
const bookingDataForSecondAttendee = responseBodyForSecondAttendee.data as BookingOutput_2024_08_13;
expect(bookingDataForSecondAttendee.attendees).toBeDefined();
expect(bookingDataForSecondAttendee.attendees.length).toBeGreaterThan(0);
});
it("should allow org admin to reschedule all seats in a seated booking for a managed user", async () => {
const newStartTime = new Date(Date.UTC(2030, 0, 10, 11, 0, 0)).toISOString();
const response = await request(app.getHttpServer())
.post(`/v2/bookings/${seatedBookingUid}/reschedule`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${orgAdminManagedUser.accessToken}`)
.send({
start: newStartTime,
})
.expect(201);
const responseBody: ApiSuccessResponse<BookingOutput_2024_08_13> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
const bookingData = responseBody.data as BookingOutput_2024_08_13;
expect(bookingData.start).toEqual(newStartTime);
seatedBookingUid = bookingData.uid;
});
it("should allow org admin to cancel all seats in a seated booking for a managed user", async () => {
const response = await request(app.getHttpServer())
.post(`/v2/bookings/${seatedBookingUid}/cancel`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${orgAdminManagedUser.accessToken}`)
.send({
cancellationReason: "Org admin cancelled the booking",
})
.expect(200);
const responseBody: GetBookingOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
const bookingData = responseBody.data as BookingOutput_2024_08_13;
expect(bookingData.status).toEqual("cancelled");
expect(bookingData.uid).toEqual(seatedBookingUid);
const cancelledBooking = await bookingsRepositoryFixture.getByUid(seatedBookingUid);
expect(cancelledBooking?.status).toEqual("CANCELLED");
});
});
describe("event type booking requires authentication", () => { describe("event type booking requires authentication", () => {
let eventTypeRequiringAuthenticationId: number; let eventTypeRequiringAuthenticationId: number;
@@ -23,13 +23,10 @@ import { UserRepositoryFixture } from "test/fixtures/repository/users.repository
import { randomString } from "test/utils/randomString"; import { randomString } from "test/utils/randomString";
import { withApiAuth } from "test/utils/withApiAuth"; import { withApiAuth } from "test/utils/withApiAuth";
import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants"; import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants";
import type { CreateBookingInput_2024_08_13 } from "@calcom/platform-types"; import type { CreateBookingInput_2024_08_13 } from "@calcom/platform-types";
import type { Booking, User, PlatformOAuthClient, Team } from "@calcom/prisma/client"; import type { Booking, User, PlatformOAuthClient, Team } from "@calcom/prisma/client";
describe("Bookings Endpoints 2024-08-13", () => { describe("Bookings Endpoints 2024-08-13", () => {
describe("Reassign bookings", () => { describe("Reassign bookings", () => {
let app: INestApplication; let app: INestApplication;
@@ -50,23 +47,12 @@ describe("Bookings Endpoints 2024-08-13", () => {
const teamUserEmail = `reassign-bookings-2024-08-13-user1-${randomString()}@api.com`; const teamUserEmail = `reassign-bookings-2024-08-13-user1-${randomString()}@api.com`;
const teamUserEmail2 = `reassign-bookings-2024-08-13-user2-${randomString()}@api.com`; const teamUserEmail2 = `reassign-bookings-2024-08-13-user2-${randomString()}@api.com`;
const teamUserEmail3 = `reassign-bookings-2024-08-13-user3-${randomString()}@api.com`;
let teamUser1: User; let teamUser1: User;
let teamUser2: User; let teamUser2: User;
let teamUser3: User;
let teamRoundRobinEventTypeId: number; let teamRoundRobinEventTypeId: number;
let teamRoundRobinFixedHostEventTypeId: number;
let teamRoundRobinNonFixedEventTypeId: number;
let teamRoundRobinWithRescheduleReasonEventTypeId: number;
let teamRoundRobinNonFixedEventTypeTitle: string;
let teamRoundRobinFixedHostEventTypeTitle: string;
let teamRoundRobinWithRescheduleReasonEventTypeTitle: string;
let roundRobinBooking: Booking; let roundRobinBooking: Booking;
let rescheduleReasonBookingUid: string;
let rescheduleReasonBookingInitialHostId: number;
beforeAll(async () => { beforeAll(async () => {
const moduleRef = await withApiAuth( const moduleRef = await withApiAuth(
@@ -110,37 +96,23 @@ describe("Bookings Endpoints 2024-08-13", () => {
teamUser1 = await userRepositoryFixture.create({ teamUser1 = await userRepositoryFixture.create({
email: teamUserEmail, email: teamUserEmail,
locale: "en", locale: "it",
name: `reassign-bookings-2024-08-13-user1-${randomString()}`, name: `reassign-bookings-2024-08-13-user1-${randomString()}`,
}); });
teamUser2 = await userRepositoryFixture.create({ teamUser2 = await userRepositoryFixture.create({
email: teamUserEmail2, email: teamUserEmail2,
locale: "en", locale: "it",
name: `reassign-bookings-2024-08-13-user2-${randomString()}`, name: `reassign-bookings-2024-08-13-user2-${randomString()}`,
}); });
teamUser3 = await userRepositoryFixture.create({
email: teamUserEmail3,
locale: "en",
name: `reassign-bookings-2024-08-13-user3-${randomString()}`,
});
const userSchedule: CreateScheduleInput_2024_04_15 = { const userSchedule: CreateScheduleInput_2024_04_15 = {
name: `reassign-bookings-2024-08-13-schedule-${randomString()}`, name: `reassign-bookings-2024-08-13-schedule-${randomString()}`,
timeZone: "Europe/Rome", timeZone: "Europe/Rome",
isDefault: true, isDefault: true,
availabilities: [
{
days: [0, 1, 2, 3, 4, 5, 6], // All days of the week
startTime: new Date(Date.UTC(2024, 0, 1, 0, 0, 0)), // 00:00 UTC
endTime: new Date(Date.UTC(2024, 0, 1, 23, 59, 0)), // 23:59 UTC
},
],
}; };
await schedulesService.createUserSchedule(teamUser1.id, userSchedule); await schedulesService.createUserSchedule(teamUser1.id, userSchedule);
await schedulesService.createUserSchedule(teamUser2.id, userSchedule); await schedulesService.createUserSchedule(teamUser2.id, userSchedule);
await schedulesService.createUserSchedule(teamUser3.id, userSchedule);
await profileRepositoryFixture.create({ await profileRepositoryFixture.create({
uid: `usr-${teamUser1.id}`, uid: `usr-${teamUser1.id}`,
@@ -172,21 +144,6 @@ describe("Bookings Endpoints 2024-08-13", () => {
}, },
}); });
await profileRepositoryFixture.create({
uid: `usr-${teamUser3.id}`,
username: teamUserEmail3,
organization: {
connect: {
id: organization.id,
},
},
user: {
connect: {
id: teamUser3.id,
},
},
});
await membershipsRepositoryFixture.create({ await membershipsRepositoryFixture.create({
role: "MEMBER", role: "MEMBER",
team: { connect: { id: team.id } }, team: { connect: { id: team.id } },
@@ -201,13 +158,6 @@ describe("Bookings Endpoints 2024-08-13", () => {
accepted: true, accepted: true,
}); });
await membershipsRepositoryFixture.create({
role: "MEMBER",
team: { connect: { id: team.id } },
user: { connect: { id: teamUser3.id } },
accepted: true,
});
const team1EventType = await eventTypesRepositoryFixture.createTeamEventType({ const team1EventType = await eventTypesRepositoryFixture.createTeamEventType({
schedulingType: "ROUND_ROBIN", schedulingType: "ROUND_ROBIN",
team: { team: {
@@ -280,187 +230,12 @@ describe("Bookings Endpoints 2024-08-13", () => {
create: { create: {
email: "bob@gmail.com", email: "bob@gmail.com",
name: "Bob", name: "Bob",
locale: "en", locale: "it",
timeZone: "Europe/Rome", timeZone: "Europe/Rome",
}, },
}, },
}); });
const teamNonFixedEventType = await eventTypesRepositoryFixture.createTeamEventType({
schedulingType: "ROUND_ROBIN",
team: {
connect: { id: team.id },
},
users: {
connect: [{ id: teamUser2.id }, { id: teamUser3.id }],
},
title: `reassign-bookings-2024-08-13-non-fixed-event-type-${randomString()}`,
slug: `reassign-bookings-2024-08-13-non-fixed-event-type-${randomString()}`,
length: 60,
assignAllTeamMembers: false,
bookingFields: [],
locations: [{ type: "inPerson", address: "via 10, rome, italy" }],
});
teamRoundRobinNonFixedEventTypeId = teamNonFixedEventType.id;
teamRoundRobinNonFixedEventTypeTitle = teamNonFixedEventType.title;
await hostsRepositoryFixture.create({
isFixed: false,
user: {
connect: {
id: teamUser2.id,
},
},
eventType: {
connect: {
id: teamNonFixedEventType.id,
},
},
});
await hostsRepositoryFixture.create({
isFixed: false,
user: {
connect: {
id: teamUser3.id,
},
},
eventType: {
connect: {
id: teamNonFixedEventType.id,
},
},
});
const team2EventType = await eventTypesRepositoryFixture.createTeamEventType({
schedulingType: "ROUND_ROBIN",
team: {
connect: { id: team.id },
},
users: {
connect: [{ id: teamUser1.id }, { id: teamUser2.id }, { id: teamUser3.id }],
},
title: `reassign-bookings-2024-08-13-fixed-event-type-${randomString()}`,
slug: `reassign-bookings-2024-08-13-fixed-event-type-${randomString()}`,
length: 60,
assignAllTeamMembers: false,
bookingFields: [],
locations: [{ type: "inPerson", address: "via 10, rome, italy" }],
});
teamRoundRobinFixedHostEventTypeId = team2EventType.id;
teamRoundRobinFixedHostEventTypeTitle = team2EventType.title;
await hostsRepositoryFixture.create({
isFixed: true,
user: {
connect: {
id: teamUser1.id,
},
},
eventType: {
connect: {
id: team2EventType.id,
},
},
});
await hostsRepositoryFixture.create({
isFixed: false,
user: {
connect: {
id: teamUser2.id,
},
},
eventType: {
connect: {
id: team2EventType.id,
},
},
});
await hostsRepositoryFixture.create({
isFixed: false,
user: {
connect: {
id: teamUser3.id,
},
},
eventType: {
connect: {
id: team2EventType.id,
},
},
});
const teamEventTypeWithRescheduleReason = await eventTypesRepositoryFixture.createTeamEventType({
schedulingType: "ROUND_ROBIN",
team: {
connect: { id: team.id },
},
users: {
connect: [{ id: teamUser1.id }, { id: teamUser2.id }],
},
title: `reassign-bookings-2024-08-13-reschedule-reason-event-type-${randomString()}`,
slug: `reassign-bookings-2024-08-13-reschedule-reason-event-type-${randomString()}`,
length: 60,
assignAllTeamMembers: false,
bookingFields: [
{
name: "rescheduleReason",
type: "textarea",
defaultLabel: "Reason for rescheduling",
required: true,
sources: [
{
id: "default",
type: "default",
label: "Default",
},
],
editable: "system",
views: [
{
id: "reschedule",
label: "Reschedule View",
},
],
},
],
locations: [{ type: "inPerson", address: "via 10, rome, italy" }],
});
teamRoundRobinWithRescheduleReasonEventTypeId = teamEventTypeWithRescheduleReason.id;
teamRoundRobinWithRescheduleReasonEventTypeTitle = teamEventTypeWithRescheduleReason.title;
await hostsRepositoryFixture.create({
isFixed: false,
user: {
connect: {
id: teamUser1.id,
},
},
eventType: {
connect: {
id: teamEventTypeWithRescheduleReason.id,
},
},
});
await hostsRepositoryFixture.create({
isFixed: false,
user: {
connect: {
id: teamUser2.id,
},
},
eventType: {
connect: {
id: teamEventTypeWithRescheduleReason.id,
},
},
});
app = moduleRef.createNestApplication(); app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication); bootstrap(app as NestExpressApplication);
@@ -532,198 +307,6 @@ describe("Bookings Endpoints 2024-08-13", () => {
}); });
}); });
it("should have correct title when reassigning round robin booking with non-fixed host", async () => {
const nonFixedHostBookingBody: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2050, 0, 9, 13, 0, 0)).toISOString(),
eventTypeId: teamRoundRobinNonFixedEventTypeId,
attendee: {
name: "Charlie",
email: "charlie@gmail.com",
timeZone: "Europe/Rome",
language: "en",
},
meetingUrl: "https://meet.google.com/abc-def-ghi",
};
const createResponse = await request(app.getHttpServer())
.post("/v2/bookings")
.send(nonFixedHostBookingBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201);
const bookingUid = createResponse.body.data.uid;
const booking = await bookingsRepositoryFixture.getByUid(bookingUid);
expect(booking).toBeDefined();
expect(booking?.userId).toEqual(teamUser2.id);
const expectedInitialTitle = `${teamRoundRobinNonFixedEventTypeTitle} between ${teamUser2.name} and Charlie`;
expect(booking?.title).toEqual(expectedInitialTitle);
return request(app.getHttpServer())
.post(`/v2/bookings/${bookingUid}/reassign`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(200)
.then(async (response) => {
const responseBody: ReassignBookingOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
const data: ReassignBookingOutput_2024_08_13["data"] = responseBody.data;
expect(data.bookingUid).toEqual(bookingUid);
expect(data.reassignedTo.id).toEqual(teamUser3.id);
const reassigned = await bookingsRepositoryFixture.getByUid(bookingUid);
expect(reassigned?.userId).toEqual(teamUser3.id);
const expectedReassignedTitle = `${teamRoundRobinNonFixedEventTypeTitle} between ${teamUser3.name} and Charlie`;
expect(reassigned?.title).toEqual(expectedReassignedTitle);
});
});
it("should have correct title when reassigning round robin booking with fixed host", async () => {
const fixedHostBookingBody: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2050, 0, 8, 13, 0, 0)).toISOString(),
eventTypeId: teamRoundRobinFixedHostEventTypeId,
attendee: {
name: "Alice",
email: "alice@gmail.com",
timeZone: "Europe/Rome",
language: "en",
},
meetingUrl: "https://meet.google.com/abc-def-ghi",
};
const createResponse = await request(app.getHttpServer())
.post("/v2/bookings")
.send(fixedHostBookingBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201);
const bookingUid = createResponse.body.data.uid;
const booking = await bookingsRepositoryFixture.getByUid(bookingUid);
expect(booking).toBeDefined();
expect(booking?.userId).toEqual(teamUser1.id);
const expectedInitialTitle = `${teamRoundRobinFixedHostEventTypeTitle} between ${team.name} and Alice`;
expect(booking?.title).toEqual(expectedInitialTitle);
return request(app.getHttpServer())
.post(`/v2/bookings/${bookingUid}/reassign/${teamUser3.id}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(200)
.then(async (response) => {
const responseBody: ReassignBookingOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
const data: ReassignBookingOutput_2024_08_13["data"] = responseBody.data;
expect(data.bookingUid).toEqual(bookingUid);
expect(data.reassignedTo.id).toEqual(teamUser1.id);
const reassigned = await bookingsRepositoryFixture.getByUid(bookingUid);
expect(reassigned?.userId).toEqual(teamUser1.id);
const expectedReassignedTitle = `${teamRoundRobinFixedHostEventTypeTitle} between ${team.name} and Alice`;
expect(reassigned?.title).toEqual(expectedReassignedTitle);
});
});
it("should preserve attendee name when reassigning round robin host manually with rescheduleReason required", async () => {
const bookingBody: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2050, 0, 10, 13, 0, 0)).toISOString(),
eventTypeId: teamRoundRobinWithRescheduleReasonEventTypeId,
attendee: {
name: "David",
email: "david@gmail.com",
timeZone: "Europe/Rome",
language: "en",
},
meetingUrl: "https://meet.google.com/abc-def-ghi",
};
const createResponse = await request(app.getHttpServer())
.post("/v2/bookings")
.send(bookingBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201);
const bookingUid = createResponse.body.data.uid;
rescheduleReasonBookingUid = bookingUid;
const booking = await bookingsRepositoryFixture.getByUid(bookingUid);
expect(booking).toBeDefined();
expect(booking?.userId).toBeDefined();
const initialHostId = booking!.userId!;
rescheduleReasonBookingInitialHostId = initialHostId;
const expectedInitialTitle = `${teamRoundRobinWithRescheduleReasonEventTypeTitle} between ${
booking?.userId === teamUser1.id ? teamUser1.name : teamUser2.name
} and David`;
expect(booking?.title).toEqual(expectedInitialTitle);
expect(booking?.title).not.toContain("Nameless");
const reassignToHostId = initialHostId === teamUser1.id ? teamUser2.id : teamUser1.id;
const reassignToHostName = reassignToHostId === teamUser1.id ? teamUser1.name : teamUser2.name;
return request(app.getHttpServer())
.post(`/v2/bookings/${bookingUid}/reassign/${reassignToHostId}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(200)
.then(async (response) => {
const responseBody: ReassignBookingOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
const data: ReassignBookingOutput_2024_08_13["data"] = responseBody.data;
expect(data.bookingUid).toEqual(bookingUid);
expect(data.reassignedTo.id).toEqual(reassignToHostId);
const reassigned = await bookingsRepositoryFixture.getByUid(bookingUid);
expect(reassigned?.userId).toEqual(reassignToHostId);
const expectedReassignedTitle = `${teamRoundRobinWithRescheduleReasonEventTypeTitle} between ${reassignToHostName} and David`;
expect(reassigned?.title).toEqual(expectedReassignedTitle);
expect(reassigned?.title).not.toContain("Nameless");
});
});
it("should preserve attendee name when reassigning round robin host automatically with rescheduleReason required", async () => {
const bookingUid = rescheduleReasonBookingUid;
const booking = await bookingsRepositoryFixture.getByUid(bookingUid);
expect(booking).toBeDefined();
expect(booking?.userId).toBeDefined();
const currentHostId = booking!.userId!;
const initialHostId = rescheduleReasonBookingInitialHostId;
const initialHostName = initialHostId === teamUser1.id ? teamUser1.name : teamUser2.name;
expect(currentHostId).not.toEqual(initialHostId);
return request(app.getHttpServer())
.post(`/v2/bookings/${bookingUid}/reassign`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(200)
.then(async (response) => {
const responseBody: ReassignBookingOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
const data: ReassignBookingOutput_2024_08_13["data"] = responseBody.data;
expect(data.bookingUid).toEqual(bookingUid);
expect(data.reassignedTo.id).toEqual(initialHostId);
const autoReassigned = await bookingsRepositoryFixture.getByUid(bookingUid);
expect(autoReassigned?.userId).toEqual(initialHostId);
const expectedAutoReassignedTitle = `${teamRoundRobinWithRescheduleReasonEventTypeTitle} between ${initialHostName} and David`;
expect(autoReassigned?.title).toEqual(expectedAutoReassignedTitle);
expect(autoReassigned?.title).not.toContain("Nameless");
});
});
async function createOAuthClient(organizationId: number) { async function createOAuthClient(organizationId: number) {
const data = { const data = {
logo: "logo-url", logo: "logo-url",
@@ -742,10 +325,8 @@ describe("Bookings Endpoints 2024-08-13", () => {
await teamRepositoryFixture.delete(organization.id); await teamRepositoryFixture.delete(organization.id);
await userRepositoryFixture.deleteByEmail(teamUser1.email); await userRepositoryFixture.deleteByEmail(teamUser1.email);
await userRepositoryFixture.deleteByEmail(teamUserEmail2); await userRepositoryFixture.deleteByEmail(teamUserEmail2);
await userRepositoryFixture.deleteByEmail(teamUserEmail3);
await bookingsRepositoryFixture.deleteAllBookings(teamUser1.id, teamUser1.email); await bookingsRepositoryFixture.deleteAllBookings(teamUser1.id, teamUser1.email);
await bookingsRepositoryFixture.deleteAllBookings(teamUser2.id, teamUser2.email); await bookingsRepositoryFixture.deleteAllBookings(teamUser2.id, teamUser2.email);
await bookingsRepositoryFixture.deleteAllBookings(teamUser3.id, teamUser3.email);
await app.close(); await app.close();
}); });
}); });
@@ -1,3 +0,0 @@
import { GetBookingOutput_2024_08_13 } from "@calcom/platform-types";
export class AddGuestsOutput_2024_08_13 extends GetBookingOutput_2024_08_13 {}
@@ -1,46 +0,0 @@
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository";
import { BookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/bookings.service";
import { PlatformBookingsService } from "@/ee/bookings/shared/platform-bookings.service";
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { Injectable, Logger, HttpException, NotFoundException } from "@nestjs/common";
import { addGuestsHandler } from "@calcom/platform-libraries/bookings";
import type { AddGuestsInput_2024_08_13 } from "@calcom/platform-types";
@Injectable()
export class BookingGuestsService_2024_08_13 {
private readonly logger = new Logger("BookingGuestsService_2024_08_13");
constructor(
private readonly bookingsRepository: BookingsRepository_2024_08_13,
private readonly bookingsService: BookingsService_2024_08_13,
private readonly platformBookingsService: PlatformBookingsService
) {}
async addGuests(bookingUid: string, input: AddGuestsInput_2024_08_13, user: ApiAuthGuardUser) {
const booking = await this.bookingsRepository.getByUidWithAttendeesAndUserAndEvent(bookingUid);
if (!booking) {
throw new NotFoundException(`Booking with uid ${bookingUid} not found`);
}
const platformClientParams = booking.eventTypeId
? await this.platformBookingsService.getOAuthClientParams(booking.eventTypeId)
: undefined;
const emailsEnabled = platformClientParams ? platformClientParams.arePlatformEmailsEnabled : true;
const res = await addGuestsHandler({
ctx: { user },
input: { bookingId: booking.id, guests: input.guests },
emailsEnabled,
});
if (res.message === "Guests added") {
return await this.bookingsService.getBooking(bookingUid, user);
} else {
throw new HttpException(
"Failed to add guests to the booking",
500
);
}
}
}
@@ -1,5 +1,5 @@
import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/booking-references.repository"; import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/booking-references.repository";
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository"; import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.repository";
import { BookingReferencesFilterInput_2024_08_13 } from "@/ee/bookings/2024-08-13/inputs/booking-references-filter.input"; import { BookingReferencesFilterInput_2024_08_13 } from "@/ee/bookings/2024-08-13/inputs/booking-references-filter.input";
import { OutputBookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output-booking-references.service"; import { OutputBookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output-booking-references.service";
import { Injectable, NotFoundException, BadRequestException } from "@nestjs/common"; import { Injectable, NotFoundException, BadRequestException } from "@nestjs/common";
@@ -1,4 +1,4 @@
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository"; import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.repository";
import { CalendarLink } from "@/ee/bookings/2024-08-13/outputs/calendar-links.output"; import { CalendarLink } from "@/ee/bookings/2024-08-13/outputs/calendar-links.output";
import { ErrorsBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/errors.service"; import { ErrorsBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/errors.service";
import { InputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/input.service"; import { InputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/input.service";
@@ -49,7 +49,6 @@ import {
confirmBookingHandler, confirmBookingHandler,
getCalendarLinks, getCalendarLinks,
} from "@calcom/platform-libraries"; } from "@calcom/platform-libraries";
import { PrismaOrgMembershipRepository } from "@calcom/platform-libraries/bookings";
import { import {
CreateBookingInput_2024_08_13, CreateBookingInput_2024_08_13,
CreateBookingInput, CreateBookingInput,
@@ -65,7 +64,6 @@ import {
RescheduleBookingInput, RescheduleBookingInput,
CancelBookingInput, CancelBookingInput,
} from "@calcom/platform-types"; } from "@calcom/platform-types";
import type { RescheduleSeatedBookingInput_2024_08_13 } from "@calcom/platform-types";
import type { PrismaClient } from "@calcom/prisma"; import type { PrismaClient } from "@calcom/prisma";
import type { EventType, User, Team } from "@calcom/prisma/client"; import type { EventType, User, Team } from "@calcom/prisma/client";
@@ -764,26 +762,16 @@ export class BookingsService_2024_08_13 {
authUser: AuthOptionalUser authUser: AuthOptionalUser
) { ) {
try { try {
const isIndividualSeatRequest = this.isRescheduleSeatedBody(body); await this.canRescheduleBooking(bookingUid);
const isIndividualSeatReschedule = await this.shouldRescheduleIndividualSeat(
bookingUid,
isIndividualSeatRequest,
authUser
);
const bookingRequest = await this.inputService.createRescheduleBookingRequest( const bookingRequest = await this.inputService.createRescheduleBookingRequest(
request, request,
bookingUid, bookingUid,
body, body
isIndividualSeatReschedule
); );
await this.canRescheduleBooking(bookingUid);
const booking = await this.regularBookingService.createBooking({ const booking = await this.regularBookingService.createBooking({
bookingData: bookingRequest.body, bookingData: bookingRequest.body,
bookingMeta: { bookingMeta: {
userId: bookingRequest.userId ?? authUser?.id, userId: bookingRequest.userId,
hostname: bookingRequest.headers?.host || "", hostname: bookingRequest.headers?.host || "",
platformClientId: bookingRequest.platformClientId, platformClientId: bookingRequest.platformClientId,
platformRescheduleUrl: bookingRequest.platformRescheduleUrl, platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
@@ -852,57 +840,6 @@ export class BookingsService_2024_08_13 {
return booking; return booking;
} }
async shouldRescheduleIndividualSeat(
bookingUid: string,
isIndividualSeatReschedule: boolean,
authUser: AuthOptionalUser
) {
const booking = await this.bookingsRepository.getByUidWithUserIdAndSeatsReferencesCount(bookingUid);
if (!booking) {
throw new NotFoundException(`Booking with uid=${bookingUid} was not found in the database`);
}
const hasSeatsPresent = booking.seatsReferences.length > 0;
if (!hasSeatsPresent) return false;
return await this.isIndividualSeatOrOrgAdminReschedule(
isIndividualSeatReschedule,
booking.userId,
authUser?.id
);
}
async isIndividualSeatOrOrgAdminReschedule(
isIndividualSeatReschedule: boolean,
bookingUserId: number | null,
authUserId?: number | null
) {
if (isIndividualSeatReschedule) {
return true;
}
if (!authUserId) {
throw new Error(`No auth user found`);
}
if (!bookingUserId) {
throw new Error(`No user found for booking`);
}
const isOrgAdmin = await PrismaOrgMembershipRepository.isLoggedInUserOrgAdminOfBookingHost(
authUserId,
bookingUserId
);
return isOrgAdmin;
}
isRescheduleSeatedBody(body: RescheduleBookingInput): body is RescheduleSeatedBookingInput_2024_08_13 {
return "seatUid" in body;
}
async cancelBooking( async cancelBooking(
request: Request, request: Request,
bookingUid: string, bookingUid: string,
@@ -1,4 +1,4 @@
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository"; import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.repository";
import { OutputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output.service"; import { OutputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output.service";
import { Injectable, Logger, NotFoundException } from "@nestjs/common"; import { Injectable, Logger, NotFoundException } from "@nestjs/common";
@@ -1,4 +1,4 @@
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository"; import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.repository";
import { import {
eventTypeBookingFieldsSchema, eventTypeBookingFieldsSchema,
EventTypeWithOwnerAndTeam, EventTypeWithOwnerAndTeam,
@@ -507,13 +507,11 @@ export class InputBookingsService_2024_08_13 {
async createRescheduleBookingRequest( async createRescheduleBookingRequest(
request: Request, request: Request,
bookingUid: string, bookingUid: string,
body: RescheduleBookingInput, body: RescheduleBookingInput
isIndividualSeatReschedule: boolean
): Promise<BookingRequest> { ): Promise<BookingRequest> {
const bodyTransformed = const bodyTransformed = this.isRescheduleSeatedBody(body)
isIndividualSeatReschedule && "seatUid" in body ? await this.transformInputRescheduleSeatedBooking(bookingUid, body)
? await this.transformInputRescheduleSeatedBooking(bookingUid, body) : await this.transformInputRescheduleBooking(bookingUid, body);
: await this.transformInputRescheduleBooking(bookingUid, body, isIndividualSeatReschedule);
const oAuthClientParams = await this.platformBookingsService.getOAuthClientParams( const oAuthClientParams = await this.platformBookingsService.getOAuthClientParams(
bodyTransformed.eventTypeId bodyTransformed.eventTypeId
@@ -556,7 +554,7 @@ export class InputBookingsService_2024_08_13 {
} }
isRescheduleSeatedBody(body: RescheduleBookingInput): body is RescheduleSeatedBookingInput_2024_08_13 { isRescheduleSeatedBody(body: RescheduleBookingInput): body is RescheduleSeatedBookingInput_2024_08_13 {
return Object.prototype.hasOwnProperty.call(body, "seatUid"); return body.hasOwnProperty("seatUid");
} }
async transformInputRescheduleSeatedBooking( async transformInputRescheduleSeatedBooking(
@@ -608,11 +606,7 @@ export class InputBookingsService_2024_08_13 {
}; };
} }
async transformInputRescheduleBooking( async transformInputRescheduleBooking(bookingUid: string, inputBooking: RescheduleBookingInput_2024_08_13) {
bookingUid: string,
inputBooking: RescheduleBookingInput_2024_08_13,
isIndividualSeatReschedule: boolean
) {
const booking = await this.bookingsRepository.getByUidWithAttendeesAndUserAndEvent(bookingUid); const booking = await this.bookingsRepository.getByUidWithAttendeesAndUserAndEvent(bookingUid);
if (!booking) { if (!booking) {
throw new NotFoundException(`Booking with uid=${bookingUid} not found`); throw new NotFoundException(`Booking with uid=${bookingUid} not found`);
@@ -624,7 +618,7 @@ export class InputBookingsService_2024_08_13 {
if (!eventType) { if (!eventType) {
throw new NotFoundException(`Event type with id=${booking.eventTypeId} not found`); throw new NotFoundException(`Event type with id=${booking.eventTypeId} not found`);
} }
if (eventType.seatsPerTimeSlot && !isIndividualSeatReschedule) { if (eventType.seatsPerTimeSlot) {
throw new BadRequestException( throw new BadRequestException(
`Booking with uid=${bookingUid} is a seated booking which means you have to provide seatUid in the request body to specify which seat specifically you want to reschedule. First, fetch the booking using https://cal.com/docs/api-reference/v2/bookings/get-a-booking and then within the attendees array you will find the seatUid of the booking you want to reschedule. Second, provide the seatUid in the request body to specify which seat specifically you want to reschedule using the reschedule endpoint https://cal.com/docs/api-reference/v2/bookings/reschedule-a-booking#option-2` `Booking with uid=${bookingUid} is a seated booking which means you have to provide seatUid in the request body to specify which seat specifically you want to reschedule. First, fetch the booking using https://cal.com/docs/api-reference/v2/bookings/get-a-booking and then within the attendees array you will find the seatUid of the booking you want to reschedule. Second, provide the seatUid in the request body to specify which seat specifically you want to reschedule using the reschedule endpoint https://cal.com/docs/api-reference/v2/bookings/reschedule-a-booking#option-2`
); );
@@ -658,6 +652,7 @@ export class InputBookingsService_2024_08_13 {
const startTime = DateTime.fromISO(inputBooking.start, { zone: "utc" }).setZone(attendee.timeZone); const startTime = DateTime.fromISO(inputBooking.start, { zone: "utc" }).setZone(attendee.timeZone);
const endTime = startTime.plus({ minutes: eventType.length }); const endTime = startTime.plus({ minutes: eventType.length });
return { return {
start: startTime.toISO(), start: startTime.toISO(),
end: endTime.toISO(), end: endTime.toISO(),
@@ -775,7 +770,7 @@ export class InputBookingsService_2024_08_13 {
} }
isCancelSeatedBody(body: CancelBookingInput): body is CancelSeatedBookingInput_2024_08_13 { isCancelSeatedBody(body: CancelBookingInput): body is CancelSeatedBookingInput_2024_08_13 {
return Object.prototype.hasOwnProperty.call(body, "seatUid"); return body.hasOwnProperty("seatUid");
} }
async transformInputCancelBooking(bookingUid: string, inputBooking: CancelBookingInput_2024_08_13) { async transformInputCancelBooking(bookingUid: string, inputBooking: CancelBookingInput_2024_08_13) {
@@ -1,4 +1,4 @@
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository"; import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.repository";
import { import {
defaultBookingMetadata, defaultBookingMetadata,
defaultBookingResponses, defaultBookingResponses,
@@ -1,5 +1,5 @@
import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/booking-references.repository"; import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/booking-references.repository";
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository"; import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.repository";
import { CalendarsRepository } from "@/ee/calendars/calendars.repository"; import { CalendarsRepository } from "@/ee/calendars/calendars.repository";
import { CalendarsController } from "@/ee/calendars/controllers/calendars.controller"; import { CalendarsController } from "@/ee/calendars/controllers/calendars.controller";
import { AppleCalendarService } from "@/ee/calendars/services/apple-calendar.service"; import { AppleCalendarService } from "@/ee/calendars/services/apple-calendar.service";
@@ -22,17 +22,29 @@ import { UserRepositoryFixture } from "test/fixtures/repository/users.repository
import { randomString } from "test/utils/randomString"; import { randomString } from "test/utils/randomString";
import { withApiAuth } from "test/utils/withApiAuth"; import { withApiAuth } from "test/utils/withApiAuth";
import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_06_14 } from "@calcom/platform-constants"; import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_06_14 } from "@calcom/platform-constants";
import { BookingWindowPeriodInputTypeEnum_2024_06_14, BookerLayoutsInputEnum_2024_06_14, ConfirmationPolicyEnum, NoticeThresholdUnitEnum, FrequencyInput } from "@calcom/platform-enums"; import {
BookingWindowPeriodInputTypeEnum_2024_06_14,
BookerLayoutsInputEnum_2024_06_14,
ConfirmationPolicyEnum,
NoticeThresholdUnitEnum,
FrequencyInput,
} from "@calcom/platform-enums";
import { SchedulingType } from "@calcom/platform-libraries"; import { SchedulingType } from "@calcom/platform-libraries";
import { type ApiSuccessResponse, type CreateEventTypeInput_2024_06_14, type EventTypeOutput_2024_06_14, type GuestsDefaultFieldOutput_2024_06_14, type NameDefaultFieldInput_2024_06_14, type NotesDefaultFieldInput_2024_06_14, type SplitNameDefaultFieldOutput_2024_06_14, type UpdateEventTypeInput_2024_06_14 } from "@calcom/platform-types"; import {
type ApiSuccessResponse,
type CreateEventTypeInput_2024_06_14,
type EventTypeOutput_2024_06_14,
type GuestsDefaultFieldOutput_2024_06_14,
type NameDefaultFieldInput_2024_06_14,
type NotesDefaultFieldInput_2024_06_14,
type SplitNameDefaultFieldOutput_2024_06_14,
type UpdateEventTypeInput_2024_06_14,
} from "@calcom/platform-types";
import { FAILED_RECURRING_EVENT_TYPE_WITH_BOOKER_LIMITS_ERROR_MESSAGE } from "@calcom/platform-types/event-types/event-types_2024_06_14/inputs/validators/CantHaveRecurrenceAndBookerActiveBookingsLimit"; import { FAILED_RECURRING_EVENT_TYPE_WITH_BOOKER_LIMITS_ERROR_MESSAGE } from "@calcom/platform-types/event-types/event-types_2024_06_14/inputs/validators/CantHaveRecurrenceAndBookerActiveBookingsLimit";
import { REQUIRES_AT_LEAST_ONE_PROPERTY_ERROR } from "@calcom/platform-types/utils/RequiresOneOfPropertiesWhenNotDisabled"; import { REQUIRES_AT_LEAST_ONE_PROPERTY_ERROR } from "@calcom/platform-types/utils/RequiresOneOfPropertiesWhenNotDisabled";
import type { PlatformOAuthClient, Team, User, Schedule, EventType } from "@calcom/prisma/client"; import type { PlatformOAuthClient, Team, User, Schedule, EventType } from "@calcom/prisma/client";
const orderBySlug = (a: { slug: string }, b: { slug: string }) => { const orderBySlug = (a: { slug: string }, b: { slug: string }) => {
if (a.slug < b.slug) return -1; if (a.slug < b.slug) return -1;
if (a.slug > b.slug) return 1; if (a.slug > b.slug) return 1;
@@ -1629,197 +1641,6 @@ describe("Event types Endpoints", () => {
} }
await app.close(); await app.close();
}); });
describe("confirmationPolicy", () => {
describe("negative tests", () => {
it("should not create an event type with type 'time' without noticeThreshold", async () => {
const body: CreateEventTypeInput_2024_06_14 = {
title: "Event requiring confirmation with time",
slug: "event-confirmation-time-missing-threshold",
description: "This event requires confirmation based on time.",
lengthInMinutes: 60,
confirmationPolicy: {
type: ConfirmationPolicyEnum.TIME,
blockUnconfirmedBookingsInBooker: true,
},
};
const response = await request(app.getHttpServer())
.post("/api/v2/event-types")
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_14)
.set("Authorization", `Bearer ${apiKeyString}`)
.send(body)
.expect(400);
expect(response.body.error).toBeDefined();
expect(response.status).toBe(400);
});
it("should not update an event type to type 'time' without noticeThreshold", async () => {
// First create an event type with type 'always'
const createBody: CreateEventTypeInput_2024_06_14 = {
title: "Event requiring confirmation always",
slug: "event-confirmation-always-to-time",
description: "This event always requires confirmation.",
lengthInMinutes: 60,
confirmationPolicy: {
type: ConfirmationPolicyEnum.ALWAYS,
blockUnconfirmedBookingsInBooker: true,
},
};
const createResponse = await request(app.getHttpServer())
.post("/api/v2/event-types")
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_14)
.set("Authorization", `Bearer ${apiKeyString}`)
.send(createBody)
.expect(201);
const createdEventType = createResponse.body.data;
// Try to update to type 'time' without noticeThreshold
const updateBody: UpdateEventTypeInput_2024_06_14 = {
confirmationPolicy: {
type: ConfirmationPolicyEnum.TIME,
blockUnconfirmedBookingsInBooker: true,
},
};
const updateResponse = await request(app.getHttpServer())
.patch(`/api/v2/event-types/${createdEventType.id}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_14)
.set("Authorization", `Bearer ${apiKeyString}`)
.send(updateBody)
.expect(400);
expect(updateResponse.body.error).toBeDefined();
expect(updateResponse.status).toBe(400);
// Cleanup
await eventTypesRepositoryFixture.delete(createdEventType.id);
});
});
describe("positive tests", () => {
let eventTypeWithConfirmationTimeId: number;
it("should create an event type with type 'always'", async () => {
const body: CreateEventTypeInput_2024_06_14 = {
title: "Event requiring confirmation always",
slug: "event-confirmation-always",
description: "This event always requires confirmation.",
lengthInMinutes: 60,
confirmationPolicy: {
type: ConfirmationPolicyEnum.ALWAYS,
blockUnconfirmedBookingsInBooker: true,
},
};
return request(app.getHttpServer())
.post("/api/v2/event-types")
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_14)
.set("Authorization", `Bearer ${apiKeyString}`)
.send(body)
.expect(201)
.then(async (response) => {
const responseBody: ApiSuccessResponse<EventTypeOutput_2024_06_14> = response.body;
const createdEventType = responseBody.data;
expect(createdEventType).toHaveProperty("id");
expect(createdEventType.title).toEqual(body.title);
expect(createdEventType.confirmationPolicy).toEqual(body.confirmationPolicy);
await eventTypesRepositoryFixture.delete(createdEventType.id);
});
});
it("should create an event type with type 'time' and noticeThreshold", async () => {
const body: CreateEventTypeInput_2024_06_14 = {
title: "Event requiring confirmation with time",
slug: "event-confirmation-time-with-threshold",
description: "This event requires confirmation based on time.",
lengthInMinutes: 60,
confirmationPolicy: {
type: ConfirmationPolicyEnum.TIME,
noticeThreshold: {
unit: NoticeThresholdUnitEnum.HOURS,
count: 24,
},
blockUnconfirmedBookingsInBooker: true,
},
};
return request(app.getHttpServer())
.post("/api/v2/event-types")
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_14)
.set("Authorization", `Bearer ${apiKeyString}`)
.send(body)
.expect(201)
.then(async (response) => {
const responseBody: ApiSuccessResponse<EventTypeOutput_2024_06_14> = response.body;
const createdEventType = responseBody.data;
expect(createdEventType).toHaveProperty("id");
expect(createdEventType.title).toEqual(body.title);
expect(createdEventType.confirmationPolicy).toEqual(body.confirmationPolicy);
eventTypeWithConfirmationTimeId = createdEventType.id;
});
});
it("should update an event type from type 'time' to 'always'", async () => {
const body: UpdateEventTypeInput_2024_06_14 = {
confirmationPolicy: {
type: ConfirmationPolicyEnum.ALWAYS,
blockUnconfirmedBookingsInBooker: false,
},
};
return request(app.getHttpServer())
.patch(`/api/v2/event-types/${eventTypeWithConfirmationTimeId}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_14)
.set("Authorization", `Bearer ${apiKeyString}`)
.send(body)
.expect(200)
.then(async (response) => {
const responseBody: ApiSuccessResponse<EventTypeOutput_2024_06_14> = response.body;
const updatedEventType = responseBody.data;
const policy = updatedEventType.confirmationPolicy as any;
expect(policy?.type).toEqual(ConfirmationPolicyEnum.ALWAYS);
expect(policy?.blockUnconfirmedBookingsInBooker).toEqual(false);
expect(policy?.noticeThreshold).toBeUndefined();
});
});
it("should update an event type from type 'always' to 'time' with noticeThreshold", async () => {
const body: UpdateEventTypeInput_2024_06_14 = {
confirmationPolicy: {
type: ConfirmationPolicyEnum.TIME,
noticeThreshold: {
unit: NoticeThresholdUnitEnum.MINUTES,
count: 120,
},
blockUnconfirmedBookingsInBooker: true,
},
};
return request(app.getHttpServer())
.patch(`/api/v2/event-types/${eventTypeWithConfirmationTimeId}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_14)
.set("Authorization", `Bearer ${apiKeyString}`)
.send(body)
.expect(200)
.then(async (response) => {
const responseBody: ApiSuccessResponse<EventTypeOutput_2024_06_14> = response.body;
const updatedEventType = responseBody.data;
const policy = updatedEventType.confirmationPolicy as any;
expect(policy?.type).toEqual(ConfirmationPolicyEnum.TIME);
expect(policy?.noticeThreshold).toEqual({
unit: NoticeThresholdUnitEnum.MINUTES,
count: 120,
});
expect(policy?.blockUnconfirmedBookingsInBooker).toEqual(true);
await eventTypesRepositoryFixture.delete(eventTypeWithConfirmationTimeId);
});
});
});
});
}); });
describe("Handle event-types booking fields", () => { describe("Handle event-types booking fields", () => {
@@ -39,11 +39,9 @@ export class EventTypesService_2024_06_14 {
} }
await this.checkCanCreateEventType(user.id, body); await this.checkCanCreateEventType(user.id, body);
const eventTypeUser = await this.getUserToCreateEvent(user); const eventTypeUser = await this.getUserToCreateEvent(user);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { destinationCalendar: _destinationCalendar, ...rest } = body; const { destinationCalendar: _destinationCalendar, ...rest } = body;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const { eventType: eventTypeCreated } = await createEventType({ const { eventType: eventTypeCreated } = await createEventType({
input: rest, input: rest,
ctx: { ctx: {
-4
View File
@@ -34,10 +34,6 @@ export type Environment = {
IS_TEAM_BILLING_ENABLED: boolean; IS_TEAM_BILLING_ENABLED: boolean;
// Used to enable/disable the rewrite of /api/v2 to /v2, active by default. // Used to enable/disable the rewrite of /api/v2 to /v2, active by default.
REWRITE_API_V2_PREFIX: string; REWRITE_API_V2_PREFIX: string;
DATABASE_READ_POOL_MAX: number;
DATABASE_WRITE_POOL_MAX: number;
DATABASE_READ_WORKER_POOL_MAX: number;
DATABASE_WRITE_WORKER_POOL_MAX: number;
}; };
export const getEnv = <K extends keyof Environment>(key: K, fallback?: Environment[K]): Environment[K] => { export const getEnv = <K extends keyof Environment>(key: K, fallback?: Environment[K]): Environment[K] => {
@@ -16,12 +16,12 @@ import { FilterHostsService } from "@/lib/services/filter-hosts.service";
import { NoSlotsNotificationService } from "@/lib/services/no-slots-notification.service"; import { NoSlotsNotificationService } from "@/lib/services/no-slots-notification.service";
import { QualifiedHostsService } from "@/lib/services/qualified-hosts.service"; import { QualifiedHostsService } from "@/lib/services/qualified-hosts.service";
import { UserAvailabilityService } from "@/lib/services/user-availability.service"; import { UserAvailabilityService } from "@/lib/services/user-availability.service";
import { PrismaWorkerModule } from "@/modules/prisma/prisma-worker.module"; import { PrismaModule } from "@/modules/prisma/prisma.module";
import { RedisService } from "@/modules/redis/redis.service"; import { RedisService } from "@/modules/redis/redis.service";
import { Module } from "@nestjs/common"; import { Module } from "@nestjs/common";
@Module({ @Module({
imports: [PrismaWorkerModule], imports: [PrismaModule],
providers: [ providers: [
PrismaOOORepository, PrismaOOORepository,
PrismaScheduleRepository, PrismaScheduleRepository,
@@ -7,7 +7,6 @@ import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository"
import { CacheService } from "@/lib/services/cache.service"; import { CacheService } from "@/lib/services/cache.service";
import { CheckBookingAndDurationLimitsService } from "@/lib/services/check-booking-and-duration-limits.service"; import { CheckBookingAndDurationLimitsService } from "@/lib/services/check-booking-and-duration-limits.service";
import { CheckBookingLimitsService } from "@/lib/services/check-booking-limits.service"; import { CheckBookingLimitsService } from "@/lib/services/check-booking-limits.service";
import { HashedLinkService } from "@/lib/services/hashed-link.service";
import { LuckyUserService } from "@/lib/services/lucky-user.service"; import { LuckyUserService } from "@/lib/services/lucky-user.service";
import { RegularBookingService } from "@/lib/services/regular-booking.service"; import { RegularBookingService } from "@/lib/services/regular-booking.service";
import { PrismaModule } from "@/modules/prisma/prisma.module"; import { PrismaModule } from "@/modules/prisma/prisma.module";
@@ -25,10 +24,9 @@ import { Module } from "@nestjs/common";
CacheService, CacheService,
CheckBookingAndDurationLimitsService, CheckBookingAndDurationLimitsService,
CheckBookingLimitsService, CheckBookingLimitsService,
HashedLinkService,
LuckyUserService, LuckyUserService,
RegularBookingService, RegularBookingService,
], ],
exports: [RegularBookingService], exports: [RegularBookingService],
}) })
export class RegularBookingModule { } export class RegularBookingModule {}
@@ -5,7 +5,9 @@ import { BookingCancelService as BaseBookingCancelService } from "@calcom/featur
@Injectable() @Injectable()
export class BookingCancelService extends BaseBookingCancelService { export class BookingCancelService extends BaseBookingCancelService {
constructor(prismaWriteService: PrismaWriteService) { constructor(
prismaWriteService: PrismaWriteService,
) {
super({ super({
prismaClient: prismaWriteService.prisma, prismaClient: prismaWriteService.prisma,
}); });
@@ -1,10 +0,0 @@
import { Injectable } from "@nestjs/common";
import { HashedLinkService as BaseHashedLinkService } from "@calcom/platform-libraries/private-links";
@Injectable()
export class HashedLinkService extends BaseHashedLinkService {
constructor() {
super();
}
}
@@ -2,7 +2,6 @@ import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repos
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository"; import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
import { CacheService } from "@/lib/services/cache.service"; import { CacheService } from "@/lib/services/cache.service";
import { CheckBookingAndDurationLimitsService } from "@/lib/services/check-booking-and-duration-limits.service"; import { CheckBookingAndDurationLimitsService } from "@/lib/services/check-booking-and-duration-limits.service";
import { HashedLinkService } from "@/lib/services/hashed-link.service";
import { LuckyUserService } from "@/lib/services/lucky-user.service"; import { LuckyUserService } from "@/lib/services/lucky-user.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service"; import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common"; import { Injectable } from "@nestjs/common";
@@ -17,7 +16,6 @@ export class RegularBookingService extends BaseRegularBookingService {
checkBookingAndDurationLimitsService: CheckBookingAndDurationLimitsService, checkBookingAndDurationLimitsService: CheckBookingAndDurationLimitsService,
prismaWriteService: PrismaWriteService, prismaWriteService: PrismaWriteService,
bookingRepository: PrismaBookingRepository, bookingRepository: PrismaBookingRepository,
hashedLinkService: HashedLinkService,
luckyUserService: LuckyUserService, luckyUserService: LuckyUserService,
userRepository: PrismaUserRepository userRepository: PrismaUserRepository
) { ) {
@@ -26,7 +24,6 @@ export class RegularBookingService extends BaseRegularBookingService {
checkBookingAndDurationLimitsService, checkBookingAndDurationLimitsService,
prismaClient: prismaWriteService.prisma as unknown as PrismaClient, prismaClient: prismaWriteService.prisma as unknown as PrismaClient,
bookingRepository, bookingRepository,
hashedLinkService,
luckyUserService, luckyUserService,
userRepository, userRepository,
}); });
@@ -286,9 +286,10 @@ export class EventTypesAtomService {
.filter(({ ...app }) => app.slug === slug) .filter(({ ...app }) => app.slug === slug)
.map( .map(
async ({ async ({
// eslint-disable-next-line @typescript-eslint/no-unused-vars
credentials: _, credentials: _,
credential, credential,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
key: _2 /* don't leak to frontend */, key: _2 /* don't leak to frontend */,
...app ...app
}: EnabledAppType) => { }: EnabledAppType) => {
@@ -367,7 +368,7 @@ export class EventTypesAtomService {
endTime: endTime.toString(), endTime: endTime.toString(),
}; };
if (!eventType) throw new NotFoundException(`Event type with uid ${uid} not found`); if (!eventType) throw new NotFoundException(`Event type with uid ${uid} not found`);
if (eventType.users.length === 0 && !eventType.team) if (eventType.users.length === 0 && !!!eventType.team)
throw new NotFoundException(`No users found or no team present for event type with uid ${uid}`); throw new NotFoundException(`No users found or no team present for event type with uid ${uid}`);
const [user] = eventType?.users.length const [user] = eventType?.users.length
? eventType.users ? eventType.users
@@ -1,4 +1,4 @@
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository"; import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.repository";
import { BillingProcessor } from "@/modules/billing/billing.processor"; import { BillingProcessor } from "@/modules/billing/billing.processor";
import { BillingRepository } from "@/modules/billing/billing.repository"; import { BillingRepository } from "@/modules/billing/billing.repository";
import { BillingController } from "@/modules/billing/controllers/billing.controller"; import { BillingController } from "@/modules/billing/controllers/billing.controller";
@@ -1,7 +1,6 @@
import { PlatformPlan } from "@/modules/billing/types"; import { PlatformPlan } from "@/modules/billing/types";
import type { StripeService } from "@/modules/stripe/stripe.service"; import type { StripeService } from "@/modules/stripe/stripe.service";
import Stripe from "stripe"; import Stripe from "stripe";
import { PlatformBilling, Team } from "@calcom/prisma/client"; import { PlatformBilling, Team } from "@calcom/prisma/client";
export type BillingData = { export type BillingData = {
@@ -1,5 +1,5 @@
import { AppConfig } from "@/config/type"; import { AppConfig } from "@/config/type";
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository"; import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.repository";
import { BILLING_QUEUE, INCREMENT_JOB, IncrementJobDataType } from "@/modules/billing/billing.processor"; import { BILLING_QUEUE, INCREMENT_JOB, IncrementJobDataType } from "@/modules/billing/billing.processor";
import { BillingRepository } from "@/modules/billing/billing.repository"; import { BillingRepository } from "@/modules/billing/billing.repository";
import { IBillingService } from "@/modules/billing/interfaces/billing-service.interface"; import { IBillingService } from "@/modules/billing/interfaces/billing-service.interface";
@@ -1,4 +1,4 @@
import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/booking-references.repository"; import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/booking-references.repository";
import { CalendarsRepository } from "@/ee/calendars/calendars.repository"; import { CalendarsRepository } from "@/ee/calendars/calendars.repository";
import { CalendarsCacheService } from "@/ee/calendars/services/calendars-cache.service"; import { CalendarsCacheService } from "@/ee/calendars/services/calendars-cache.service";
import { CalendarsService } from "@/ee/calendars/services/calendars.service"; import { CalendarsService } from "@/ee/calendars/services/calendars.service";
@@ -1,4 +1,4 @@
import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/booking-references.repository"; import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/booking-references.repository";
import { GoogleCalendarService as GCalService } from "@/ee/calendars/services/gcal.service"; import { GoogleCalendarService as GCalService } from "@/ee/calendars/services/gcal.service";
import { GoogleCalendarEventResponse } from "@/modules/cal-unified-calendars/pipes/get-calendar-event-details-output-pipe"; import { GoogleCalendarEventResponse } from "@/modules/cal-unified-calendars/pipes/get-calendar-event-details-output-pipe";
import { calendar_v3 } from "@googleapis/calendar"; import { calendar_v3 } from "@googleapis/calendar";
@@ -107,7 +107,7 @@ export class MembershipsRepository {
}, },
}); });
return userOrgAdminMemberships.map((m: { teamId: number }) => m.teamId); return userOrgAdminMemberships.map((m) => m.teamId);
} }
async createMembership(teamId: number, userId: number, role: MembershipRole, accepted: boolean) { async createMembership(teamId: number, userId: number, role: MembershipRole, accepted: boolean) {
@@ -2,8 +2,6 @@ import { MembershipsRepository } from "@/modules/memberships/memberships.reposit
import { Injectable } from "@nestjs/common"; import { Injectable } from "@nestjs/common";
import { intersectionBy } from "lodash"; import { intersectionBy } from "lodash";
import type { Membership } from "@calcom/prisma/client";
@Injectable() @Injectable()
export class MembershipsService { export class MembershipsService {
constructor(private readonly membershipsRepository: MembershipsRepository) {} constructor(private readonly membershipsRepository: MembershipsRepository) {}
@@ -18,8 +16,8 @@ export class MembershipsService {
const secondUserMemberships = await this.membershipsRepository.findUserMemberships(secondUserId); const secondUserMemberships = await this.membershipsRepository.findUserMemberships(secondUserId);
return intersectionBy( return intersectionBy(
firstUserMemberships.filter((m: Membership) => m.accepted), firstUserMemberships.filter((m) => m.accepted),
secondUserMemberships.filter((m: Membership) => m.accepted), secondUserMemberships.filter((m) => m.accepted),
"teamId" "teamId"
); );
} }
@@ -31,7 +31,6 @@ import {
Delete, Delete,
Query, Query,
NotFoundException, NotFoundException,
ParseIntPipe,
} from "@nestjs/common"; } from "@nestjs/common";
import { ApiOperation, ApiTags as DocsTags, ApiHeader } from "@nestjs/swagger"; import { ApiOperation, ApiTags as DocsTags, ApiHeader } from "@nestjs/swagger";
@@ -112,7 +111,7 @@ export class OAuthClientUsersController {
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER]) @MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER])
async getUserById( async getUserById(
@Param("clientId") clientId: string, @Param("clientId") clientId: string,
@Param("userId", ParseIntPipe) userId: number @Param("userId") userId: number
): Promise<GetManagedUserOutput> { ): Promise<GetManagedUserOutput> {
const user = await this.validateManagedUserOwnership(clientId, userId); const user = await this.validateManagedUserOwnership(clientId, userId);
@@ -128,7 +127,7 @@ export class OAuthClientUsersController {
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER]) @MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER])
async updateUser( async updateUser(
@Param("clientId") clientId: string, @Param("clientId") clientId: string,
@Param("userId", ParseIntPipe) userId: number, @Param("userId") userId: number,
@Body() body: UpdateManagedUserInput, @Body() body: UpdateManagedUserInput,
@GetOrgId() organizationId: number @GetOrgId() organizationId: number
): Promise<GetManagedUserOutput> { ): Promise<GetManagedUserOutput> {
@@ -154,7 +153,7 @@ export class OAuthClientUsersController {
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER]) @MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER])
async deleteUser( async deleteUser(
@Param("clientId") clientId: string, @Param("clientId") clientId: string,
@Param("userId", ParseIntPipe) userId: number @Param("userId") userId: number
): Promise<GetManagedUserOutput> { ): Promise<GetManagedUserOutput> {
const user = await this.validateManagedUserOwnership(clientId, userId); const user = await this.validateManagedUserOwnership(clientId, userId);
await this.userRepository.delete(userId); await this.userRepository.delete(userId);
@@ -175,7 +174,7 @@ export class OAuthClientUsersController {
}) })
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER]) @MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER])
async forceRefresh( async forceRefresh(
@Param("userId", ParseIntPipe) userId: number, @Param("userId") userId: number,
@Param("clientId") oAuthClientId: string @Param("clientId") oAuthClientId: string
): Promise<KeysResponseDto> { ): Promise<KeysResponseDto> {
this.logger.log(`Forcing new access tokens for managed user with ID ${userId}`); this.logger.log(`Forcing new access tokens for managed user with ID ${userId}`);
@@ -434,19 +434,20 @@ describe("Organizations Event Types Endpoints", () => {
const responseTeamEvent = responseBody.data.find((event) => event.teamId === team.id); const responseTeamEvent = responseBody.data.find((event) => event.teamId === team.id);
expect(responseTeamEvent).toBeDefined(); expect(responseTeamEvent).toBeDefined();
expect(responseTeamEvent?.hosts?.find((host) => host.userId === teammate1.id)).toEqual({ expect(responseTeamEvent?.hosts).toEqual([
userId: teammate1.id, {
name: teammate1.name, userId: teammate1.id,
username: teammate1.username, name: teammate1.name,
avatarUrl: teammate1.avatarUrl, username: teammate1.username,
}); avatarUrl: teammate1.avatarUrl,
},
expect(responseTeamEvent?.hosts?.find((host) => host.userId === teammate2.id)).toEqual({ {
userId: teammate2.id, userId: teammate2.id,
name: teammate2.name, name: teammate2.name,
username: teammate2.username, username: teammate2.username,
avatarUrl: teammate2.avatarUrl, avatarUrl: teammate2.avatarUrl,
}); },
]);
if (!responseTeamEvent) { if (!responseTeamEvent) {
throw new Error("Team event not found"); throw new Error("Team event not found");
@@ -1,6 +1,6 @@
import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/booking-references.repository"; import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/booking-references.repository";
import { BookingsModule_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.module"; import { BookingsModule_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.module";
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository"; import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.repository";
import { BookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-references.service"; import { BookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-references.service";
import { OutputBookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output-booking-references.service"; import { OutputBookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output-booking-references.service";
import { MembershipsModule } from "@/modules/memberships/memberships.module"; import { MembershipsModule } from "@/modules/memberships/memberships.module";
@@ -122,6 +122,7 @@ describe("Organizations Teams Invite Endpoints", () => {
.expect(404); .expect(404);
}); });
afterAll(async () => { afterAll(async () => {
await userRepositoryFixture.deleteByEmail(user.email); await userRepositoryFixture.deleteByEmail(user.email);
await organizationsRepositoryFixture.delete(org.id); await organizationsRepositoryFixture.delete(org.id);
@@ -130,3 +131,5 @@ describe("Organizations Teams Invite Endpoints", () => {
}); });
}); });
}); });
@@ -1,9 +1,5 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions"; import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { import { OPTIONAL_API_KEY_HEADER, OPTIONAL_X_CAL_CLIENT_ID_HEADER, OPTIONAL_X_CAL_SECRET_KEY_HEADER } from "@/lib/docs/headers";
OPTIONAL_API_KEY_HEADER,
OPTIONAL_X_CAL_CLIENT_ID_HEADER,
OPTIONAL_X_CAL_SECRET_KEY_HEADER,
} from "@/lib/docs/headers";
import { Roles } from "@/modules/auth/decorators/roles/roles.decorator"; import { Roles } from "@/modules/auth/decorators/roles/roles.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard"; import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { PlatformPlanGuard } from "@/modules/auth/guards/billing/platform-plan.guard"; import { PlatformPlanGuard } from "@/modules/auth/guards/billing/platform-plan.guard";
@@ -15,8 +11,10 @@ import { Controller, UseGuards, Post, Param, ParseIntPipe, HttpCode, HttpStatus
import { ApiHeader, ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger"; import { ApiHeader, ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { SUCCESS_STATUS } from "@calcom/platform-constants"; import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { TeamService } from "@calcom/platform-libraries"; import { TeamService } from "@calcom/platform-libraries";
import { CreateInviteOutputDto } from "./outputs/invite.output"; import { CreateInviteOutputDto } from "./outputs/invite.output";
@Controller({ @Controller({
@@ -41,3 +39,5 @@ export class OrganizationsTeamsInviteController {
return { status: SUCCESS_STATUS, data: result }; return { status: SUCCESS_STATUS, data: result };
} }
} }
@@ -11,8 +11,7 @@ export class InviteDataDto {
@ApiProperty({ @ApiProperty({
description: description:
"Complete invitation URL that can be shared with prospective members. Opens the signup page with the token and redirects to getting started after signup.", "Complete invitation URL that can be shared with prospective members. Opens the signup page with the token and redirects to getting started after signup.",
example: example: "http://app.cal.com/signup?token=f6a5c8b1d2e34c7f90a1b2c3d4e5f6a5b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2&callbackUrl=/getting-started",
"http://app.cal.com/signup?token=f6a5c8b1d2e34c7f90a1b2c3d4e5f6a5b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2&callbackUrl=/getting-started",
}) })
inviteLink!: string; inviteLink!: string;
} }
@@ -24,3 +23,5 @@ export class CreateInviteOutputDto {
@ApiProperty({ type: InviteDataDto }) @ApiProperty({ type: InviteDataDto })
data!: InviteDataDto; data!: InviteDataDto;
} }
@@ -1,8 +1,7 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service"; import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service"; import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common"; import { Injectable } from "@nestjs/common";
import type { Prisma } from "@calcom/prisma/client";
import type { Prisma, AttributeToUser, Membership, User, Profile } from "@calcom/prisma/client";
@Injectable() @Injectable()
export class OrganizationsUsersRepository { export class OrganizationsUsersRepository {
@@ -61,11 +60,7 @@ export class OrganizationsUsersRepository {
skip, skip,
take, take,
}); });
return attributeToUsersWithProfile.map( return attributeToUsersWithProfile.map((attributeToUser) => attributeToUser.member.user);
(
attributeToUser: AttributeToUser & { member: Membership & { user: User & { profiles: Profile[] } } }
) => attributeToUser.member.user
);
} }
async getOrganizationUsersByEmails( async getOrganizationUsersByEmails(
@@ -1,79 +1,36 @@
import type { OnModuleDestroy, OnModuleInit } from "@nestjs/common"; import type { OnModuleDestroy, OnModuleInit } from "@nestjs/common";
import { Injectable, Logger } from "@nestjs/common"; import { Injectable, Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config"; import { ConfigService } from "@nestjs/config";
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
import { PrismaClient } from "@calcom/prisma/client"; import { PrismaClient } from "@calcom/prisma/client";
const DB_MAX_POOL_CONNECTION = 10;
export interface PrismaServiceOptions {
readUrl?: string;
maxReadConnections?: number;
e2e?: boolean;
type: "main" | "worker";
}
@Injectable() @Injectable()
export class PrismaReadService implements OnModuleInit, OnModuleDestroy { export class PrismaReadService implements OnModuleInit, OnModuleDestroy {
private logger = new Logger("PrismaReadService"); private logger = new Logger("PrismaReadService");
public prisma!: PrismaClient; public prisma: PrismaClient;
private pool!: Pool;
private options!: PrismaServiceOptions;
constructor(private configService?: ConfigService) { constructor(readonly configService: ConfigService) {
if (configService) { const dbUrl = configService.get("db.readUrl", { infer: true });
// Use ConfigService defaults
const readUrl = configService.get<string>("db.readUrl", { infer: true });
const poolMax = parseInt(
configService.get<number>("db.readPoolMax", { infer: true }) ?? DB_MAX_POOL_CONNECTION
);
const e2e = configService.get<boolean>("e2e", { infer: true }) ?? false;
this.setOptions({ this.prisma = new PrismaClient({
readUrl, datasources: {
maxReadConnections: poolMax, db: {
e2e, url: dbUrl,
type: "main", },
}); },
}
}
setOptions(options: PrismaServiceOptions) {
this.options = options;
const dbUrl = options.readUrl;
const isE2E = options.e2e ?? false;
this.pool = new Pool({
connectionString: dbUrl,
max: isE2E ? 1 : options.maxReadConnections ?? DB_MAX_POOL_CONNECTION,
idleTimeoutMillis: 300000,
}); });
const adapter = new PrismaPg(this.pool);
this.prisma = new PrismaClient({ adapter });
} }
async onModuleInit() { async onModuleInit() {
if (!this.prisma) return; this.prisma.$connect();
try {
await this.prisma.$connect();
this.logger.log("Connected to read database");
} catch (error) {
this.logger.error("Database connection failed", error);
}
} }
async onModuleDestroy() { async onModuleDestroy() {
try { try {
if (this.prisma) await this.prisma.$disconnect(); await this.prisma.$disconnect();
if (this.pool) await this.pool.end();
} catch (error) { } catch (error) {
this.logger.error("Error disconnecting from read database", error); this.logger.error(error);
} }
} }
} }
@@ -1,40 +0,0 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
@Module({
imports: [ConfigModule],
providers: [
{
provide: PrismaReadService,
useFactory: (config: ConfigService) => {
const service = new PrismaReadService();
service.setOptions({
readUrl: config.get<string>("db.readUrl", { infer: true }),
maxReadConnections: parseInt(config.get<number>("db.workerReadPoolMax", { infer: true })),
e2e: config.get<boolean>("e2e", { infer: true }) ?? false,
type: "worker",
});
return service;
},
inject: [ConfigService],
},
{
provide: PrismaWriteService,
useFactory: (config: ConfigService) => {
const service = new PrismaWriteService();
service.setOptions({
writeUrl: config.get<string>("db.writeUrl", { infer: true }),
maxWriteConnections: parseInt(config.get<number>("db.workerWritePoolMax", { infer: true })),
e2e: config.get<boolean>("e2e", { infer: true }) ?? false,
type: "worker",
});
return service;
},
inject: [ConfigService],
},
],
exports: [PrismaReadService, PrismaWriteService],
})
export class PrismaWorkerModule {}
@@ -1,75 +1,36 @@
import { OnModuleDestroy, OnModuleInit, Injectable, Logger } from "@nestjs/common"; import { OnModuleDestroy, OnModuleInit } from "@nestjs/common";
import { Injectable, Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config"; import { ConfigService } from "@nestjs/config";
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
import { PrismaClient } from "@calcom/prisma/client"; import { PrismaClient } from "@calcom/prisma/client";
const DB_MAX_POOL_CONNECTION = 5;
export interface PrismaServiceOptions {
writeUrl?: string;
maxWriteConnections?: number;
e2e?: boolean;
type: "main" | "worker";
}
@Injectable() @Injectable()
export class PrismaWriteService implements OnModuleInit, OnModuleDestroy { export class PrismaWriteService implements OnModuleInit, OnModuleDestroy {
private logger = new Logger("PrismaWriteService"); private logger = new Logger("PrismaWriteService");
public prisma!: PrismaClient;
private pool!: Pool;
private options!: PrismaServiceOptions;
constructor(private configService?: ConfigService) { public prisma: PrismaClient;
if (configService) {
const writeUrl = configService.get<string>("db.writeUrl", { infer: true });
const poolMax = parseInt(
configService.get<number>("db.writePoolMax", { infer: true }) ?? DB_MAX_POOL_CONNECTION
);
const e2e = configService.get<boolean>("e2e", { infer: true }) ?? false;
this.setOptions({ constructor(readonly configService: ConfigService) {
writeUrl, const dbUrl = configService.get("db.writeUrl", { infer: true });
maxWriteConnections: poolMax,
e2e,
type: "main",
});
}
}
setOptions(options: PrismaServiceOptions) { this.prisma = new PrismaClient({
this.options = options; datasources: {
db: {
const dbUrl = options.writeUrl; url: dbUrl,
const isE2E = options.e2e ?? false; },
this.pool = new Pool({ },
connectionString: dbUrl,
max: isE2E ? 1 : options.maxWriteConnections ?? DB_MAX_POOL_CONNECTION,
idleTimeoutMillis: 300000,
}); });
const adapter = new PrismaPg(this.pool);
this.prisma = new PrismaClient({ adapter });
} }
async onModuleInit() { async onModuleInit() {
if (!this.prisma) return; this.prisma.$connect();
try {
await this.prisma.$connect();
this.logger.log("Connected to write database");
} catch (error) {
this.logger.error("Database connection failed", error);
}
} }
async onModuleDestroy() { async onModuleDestroy() {
try { try {
if (this.prisma) await this.prisma.$disconnect(); await this.prisma.$disconnect();
if (this.pool) await this.pool.end();
} catch (error) { } catch (error) {
this.logger.error("Error disconnecting from write database", error); this.logger.error(error);
} }
} }
} }
@@ -1,40 +1,9 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service"; import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service"; import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Module } from "@nestjs/common"; import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
@Module({ @Module({
imports: [ConfigModule], providers: [PrismaReadService, PrismaWriteService],
providers: [
{
provide: PrismaReadService,
useFactory: (config: ConfigService) => {
const service = new PrismaReadService();
service.setOptions({
readUrl: config.get<string>("db.readUrl", { infer: true }),
maxReadConnections: parseInt(config.get<number>("db.readPoolMax", { infer: true })),
e2e: config.get<boolean>("e2e", { infer: true }) ?? false,
type: "main",
});
return service;
},
inject: [ConfigService],
},
{
provide: PrismaWriteService,
useFactory: (config: ConfigService) => {
const service = new PrismaWriteService();
service.setOptions({
writeUrl: config.get<string>("db.writeUrl", { infer: true }),
maxWriteConnections: parseInt(config.get<number>("db.writePoolMax", { infer: true })),
e2e: config.get<boolean>("e2e", { infer: true }) ?? false,
type: "main",
});
return service;
},
inject: [ConfigService],
},
],
exports: [PrismaReadService, PrismaWriteService], exports: [PrismaReadService, PrismaWriteService],
}) })
export class PrismaModule {} export class PrismaModule {}
@@ -2,7 +2,7 @@
// Needed if ConfigService is used anywhere // Needed if ConfigService is used anywhere
import appConfig from "@/config/app"; import appConfig from "@/config/app";
import { AvailableSlotsModule } from "@/lib/modules/available-slots.module"; import { AvailableSlotsModule } from "@/lib/modules/available-slots.module";
import { PrismaWorkerModule } from "@/modules/prisma/prisma-worker.module"; import { PrismaModule } from "@/modules/prisma/prisma.module";
import { Module, Logger } from "@nestjs/common"; import { Module, Logger } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config"; import { ConfigModule } from "@nestjs/config";
import { SentryModule } from "@sentry/nestjs/setup"; import { SentryModule } from "@sentry/nestjs/setup";
@@ -15,7 +15,7 @@ import { SentryModule } from "@sentry/nestjs/setup";
isGlobal: true, isGlobal: true,
load: [appConfig], load: [appConfig],
}), }),
PrismaWorkerModule, PrismaModule,
AvailableSlotsModule, AvailableSlotsModule,
], ],
providers: [Logger], providers: [Logger],
@@ -118,7 +118,7 @@ export class StripeService {
userId userId
); );
const credentialIdsToDelete = existingCredentials.map((item: Credential) => item.id); const credentialIdsToDelete = existingCredentials.map((item) => item.id);
if (credentialIdsToDelete.length > 0) { if (credentialIdsToDelete.length > 0) {
await this.appsRepository.deleteAppCredentials(credentialIdsToDelete, userId); await this.appsRepository.deleteAppCredentials(credentialIdsToDelete, userId);
} }
@@ -17,7 +17,7 @@ export const MembershipUserSelect: Prisma.UserSelect = {
name: true, name: true,
metadata: true, metadata: true,
bio: true, bio: true,
} satisfies Prisma.UserSelect; };
@Injectable() @Injectable()
export class TeamsMembershipsRepository { export class TeamsMembershipsRepository {
@@ -3,7 +3,7 @@ import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable, NotFoundException } from "@nestjs/common"; import { Injectable, NotFoundException } from "@nestjs/common";
import { teamMetadataSchema } from "@calcom/platform-libraries"; import { teamMetadataSchema } from "@calcom/platform-libraries";
import type { Membership, Prisma } from "@calcom/prisma/client"; import { Prisma } from "@calcom/prisma/client";
@Injectable() @Injectable()
export class TeamsRepository { export class TeamsRepository {
@@ -41,7 +41,7 @@ export class TeamsRepository {
return []; return [];
} }
return teamMembers.map((member: Membership) => member.userId); return teamMembers.map((member) => member.userId);
} }
async getTeamManagedUsersIds(teamId: number) { async getTeamManagedUsersIds(teamId: number) {
@@ -57,7 +57,7 @@ export class TeamsRepository {
return []; return [];
} }
return teamMembers.map((member: Membership) => member.userId); return teamMembers.map((member) => member.userId);
} }
async getTeamsUserIsMemberOf(userId: number) { async getTeamsUserIsMemberOf(userId: number) {
@@ -289,7 +289,7 @@ export class UsersRepository {
user: true, user: true,
}, },
}); });
return profiles.map((profile: Profile & { user: User }) => profile.user); return profiles.map((profile) => profile.user);
} }
async setDefaultConferencingApp(userId: number, appSlug?: string, appLink?: string) { async setDefaultConferencingApp(userId: number, appSlug?: string, appLink?: string) {
+1 -1
View File
@@ -14,7 +14,7 @@
"jsx": "react-jsx", "jsx": "react-jsx",
"paths": { "paths": {
"@/*": ["./src/*"], "@/*": ["./src/*"],
"@calcom/prisma/client": ["../../../packages/prisma/generated/prisma/client"], "@prisma/client/*": ["./client/*"],
"@calcom/prisma/enums": ["../../../packages/prisma/enums"], "@calcom/prisma/enums": ["../../../packages/prisma/enums"],
"@calcom/platform-constants": ["../../../packages/platform/constants/index.ts"], "@calcom/platform-constants": ["../../../packages/platform/constants/index.ts"],
"@calcom/platform-types": ["../../../packages/platform/types/index.ts"], "@calcom/platform-types": ["../../../packages/platform/types/index.ts"],
-3
View File
@@ -1,3 +0,0 @@
.git
.github
.env.example
@@ -3,7 +3,6 @@ import { unstable_cache } from "next/cache";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils"; import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
import { getTeamData } from "@calcom/features/ee/teams/lib/getTeamData"; import { getTeamData } from "@calcom/features/ee/teams/lib/getTeamData";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import { import {
getEventTypeHosts, getEventTypeHosts,
getProfileFromEvent, getProfileFromEvent,
@@ -12,9 +11,10 @@ import {
} from "@calcom/features/eventtypes/lib/getPublicEvent"; } from "@calcom/features/eventtypes/lib/getPublicEvent";
import { getTeamEventType } from "@calcom/features/eventtypes/lib/getTeamEventType"; import { getTeamEventType } from "@calcom/features/eventtypes/lib/getTeamEventType";
import { FeaturesRepository } from "@calcom/features/flags/features.repository"; import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { NEXTJS_CACHE_TTL } from "@calcom/lib/constants"; import { NEXTJS_CACHE_TTL } from "@calcom/lib/constants";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage"; import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { prisma } from "@calcom/prisma"; import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client"; import type { Prisma } from "@calcom/prisma/client";
import type { SchedulingType } from "@calcom/prisma/enums"; import type { SchedulingType } from "@calcom/prisma/enums";
@@ -6,9 +6,7 @@ import { redirect } from "next/navigation";
import { z } from "zod"; import { z } from "zod";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession"; import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service"; import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums"; import { MembershipRole } from "@calcom/prisma/enums";
import { buildLegacyRequest } from "@lib/buildLegacyCtx"; import { buildLegacyRequest } from "@lib/buildLegacyCtx";
@@ -54,18 +52,12 @@ const Page = async ({ params }: PageProps) => {
canReadOthersBookings = teamIdsWithPermission.length > 0; canReadOthersBookings = teamIdsWithPermission.length > 0;
} }
const featuresRepository = new FeaturesRepository(prisma);
const isCalendarViewEnabled = await featuresRepository.checkIfFeatureIsEnabledGlobally(
"booking-calendar-view"
);
return ( return (
<ShellMainAppDir heading={t("bookings")} subtitle={t("bookings_description")}> <ShellMainAppDir heading={t("bookings")} subtitle={t("bookings_description")}>
<BookingsList <BookingsList
status={parsed.data.status} status={parsed.data.status}
userId={session?.user?.id} userId={session?.user?.id}
permissions={{ canReadOthersBookings }} permissions={{ canReadOthersBookings }}
isCalendarViewEnabled={isCalendarViewEnabled}
/> />
</ShellMainAppDir> </ShellMainAppDir>
); );
@@ -6,7 +6,6 @@ import { unstable_cache } from "next/cache";
import { cookies, headers } from "next/headers"; import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { checkOnboardingRedirect } from "@calcom/features/auth/lib/onboardingUtils";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession"; import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { getTeamsFiltersFromQuery } from "@calcom/features/filters/lib/getTeamsFiltersFromQuery"; import { getTeamsFiltersFromQuery } from "@calcom/features/filters/lib/getTeamsFiltersFromQuery";
import { eventTypesRouter } from "@calcom/trpc/server/routers/viewer/eventTypes/_router"; import { eventTypesRouter } from "@calcom/trpc/server/routers/viewer/eventTypes/_router";
@@ -54,17 +53,6 @@ const Page = async ({ searchParams }: PageProps) => {
return redirect("/auth/login"); return redirect("/auth/login");
} }
// Check if user needs onboarding and redirect before fetching event types data
// Use organizationId from session profile if available to avoid extra query
const organizationId = session.user.profile?.organizationId ?? null;
const onboardingPath = await checkOnboardingRedirect(session.user.id, {
checkEmailVerification: true,
organizationId,
});
if (onboardingPath) {
return redirect(onboardingPath);
}
const t = await getTranslate(); const t = await getTranslate();
const filters = getTeamsFiltersFromQuery(_searchParams); const filters = getTeamsFiltersFromQuery(_searchParams);
const userEventGroupsData = await getCachedEventGroups(_headers, _cookies, filters); const userEventGroupsData = await getCachedEventGroups(_headers, _cookies, filters);
@@ -23,14 +23,8 @@ const ServerPage = async ({ searchParams: _searchParams }: ServerPageProps) => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) }); const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
const searchParams = await _searchParams; const searchParams = await _searchParams;
const token = Array.isArray(searchParams?.token) ? searchParams.token[0] : searchParams?.token; const token = Array.isArray(searchParams?.token) ? searchParams.token[0] : searchParams?.token;
const autoAccept = Array.isArray(searchParams?.autoAccept) const autoAccept = Array.isArray(searchParams?.autoAccept) ? searchParams.autoAccept[0] : searchParams?.autoAccept;
? searchParams.autoAccept[0] const callbackUrl = token ? `/teams?token=${encodeURIComponent(token)}${autoAccept ? `&autoAccept=${encodeURIComponent(autoAccept)}` : ''}` : null;
: searchParams?.autoAccept;
const callbackUrl = token
? `/teams?token=${encodeURIComponent(token)}${
autoAccept ? `&autoAccept=${encodeURIComponent(autoAccept)}` : ""
}`
: null;
if (!session) { if (!session) {
redirect(callbackUrl ? `/auth/login?callbackUrl=${callbackUrl}` : "/auth/login"); redirect(callbackUrl ? `/auth/login?callbackUrl=${callbackUrl}` : "/auth/login");
@@ -3,9 +3,9 @@ import type { Session } from "next-auth";
import { unstable_cache } from "next/cache"; import { unstable_cache } from "next/cache";
import { TeamsListing } from "@calcom/features/ee/teams/components/TeamsListing"; import { TeamsListing } from "@calcom/features/ee/teams/components/TeamsListing";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository"; import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import { TeamService } from "@calcom/features/ee/teams/services/teamService"; import { TeamService } from "@calcom/features/ee/teams/services/teamService";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import prisma from "@calcom/prisma"; import prisma from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums"; import { MembershipRole } from "@calcom/prisma/enums";
@@ -33,9 +33,7 @@ export const ServerTeamsListing = async ({
session: Session; session: Session;
}) => { }) => {
const token = Array.isArray(searchParams?.token) ? searchParams.token[0] : searchParams?.token; const token = Array.isArray(searchParams?.token) ? searchParams.token[0] : searchParams?.token;
const autoAccept = Array.isArray(searchParams?.autoAccept) const autoAccept = Array.isArray(searchParams?.autoAccept) ? searchParams.autoAccept[0] : searchParams?.autoAccept;
? searchParams.autoAccept[0]
: searchParams?.autoAccept;
const userId = session.user.id; const userId = session.user.id;
let invitationAccepted = false; let invitationAccepted = false;
@@ -44,7 +42,7 @@ export const ServerTeamsListing = async ({
if (token) { if (token) {
try { try {
if (autoAccept === "true") { if (autoAccept === "true") {
await TeamService.acceptInvitationByToken(token, userId); await TeamService.acceptInvitationByToken(token, userId);
invitationAccepted = true; invitationAccepted = true;
} else { } else {
@@ -17,21 +17,21 @@ export const generateMetadata = async ({ params }: _PageProps) => {
if (!p.success) { if (!p.success) {
return notFound(); return notFound();
} }
const slugFromUrl = p.data.slug;
const props = await getStaticProps(slugFromUrl); const props = await getStaticProps(p.data.slug);
if (!props) { if (!props) {
notFound(); notFound();
} }
const { name, logo, dirName: appStoreDirSlug, slug: appSlug, description } = props.data; const { name, logo, description } = props.data;
return await generateAppMetadata( return await generateAppMetadata(
{ slug: appStoreDirSlug ?? appSlug, logoUrl: logo, name, description }, { slug: logo, name, description },
() => name, () => name,
() => description, () => description,
undefined, undefined,
undefined, undefined,
`/apps/${appSlug}` `/apps/${p.data.slug}`
); );
}; };
@@ -308,7 +308,7 @@ const WeightedAttributesSelector = ({
/> />
</div> </div>
<div className="bg-muted mt-1 rounded-xl p-2"> <div className="bg-muted mt-1 rounded-xl p-2">
{attributeIdForWeights ? ( {!!attributeIdForWeights ? (
<SelectField <SelectField
size="sm" size="sm"
containerClassName="data-testid-select-router" containerClassName="data-testid-select-router"
@@ -6,7 +6,6 @@ import { useFormContext } from "react-hook-form";
import { isFallbackRoute } from "@calcom/app-store/routing-forms/lib/isFallbackRoute"; import { isFallbackRoute } from "@calcom/app-store/routing-forms/lib/isFallbackRoute";
import type { RoutingFormWithResponseCount } from "@calcom/app-store/routing-forms/types/types"; import type { RoutingFormWithResponseCount } from "@calcom/app-store/routing-forms/types/types";
import { useHasPaidPlan } from "@calcom/features/billing/hooks/useHasPaidPlan";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired"; import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
import SkeletonLoaderTeamList from "@calcom/features/ee/teams/components/SkeletonloaderTeamList"; import SkeletonLoaderTeamList from "@calcom/features/ee/teams/components/SkeletonloaderTeamList";
import { CreateButtonWithTeamsList } from "@calcom/features/ee/teams/components/createButton/CreateButtonWithTeamsList"; import { CreateButtonWithTeamsList } from "@calcom/features/ee/teams/components/createButton/CreateButtonWithTeamsList";
@@ -16,6 +15,7 @@ import { getTeamsFiltersFromQuery } from "@calcom/features/filters/lib/getTeamsF
import { ShellMain } from "@calcom/features/shell/Shell"; import { ShellMain } from "@calcom/features/shell/Shell";
import { UpgradeTip } from "@calcom/features/tips"; import { UpgradeTip } from "@calcom/features/tips";
import { WEBAPP_URL } from "@calcom/lib/constants"; import { WEBAPP_URL } from "@calcom/lib/constants";
import { useHasPaidPlan } from "@calcom/lib/hooks/useHasPaidPlan";
import { useLocale } from "@calcom/lib/hooks/useLocale"; import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery"; import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
import { MembershipRole } from "@calcom/prisma/enums"; import { MembershipRole } from "@calcom/prisma/enums";
@@ -76,6 +76,7 @@ export default function RoutingForms({ appUrl }: { appUrl: string }) {
useEffect(() => { useEffect(() => {
hookForm.reset({}); hookForm.reset({});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
const filters = getTeamsFiltersFromQuery(routerQuery); const filters = getTeamsFiltersFromQuery(routerQuery);
@@ -5,8 +5,8 @@ import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession"; import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { APP_NAME } from "@calcom/lib/constants"; import { APP_NAME } from "@calcom/lib/constants";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import prisma from "@calcom/prisma"; import prisma from "@calcom/prisma";
import { meRouter } from "@calcom/trpc/server/routers/viewer/me/_router"; import { meRouter } from "@calcom/trpc/server/routers/viewer/me/_router";

Some files were not shown because too many files have changed in this diff Show More