Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
076550b384 | ||
|
|
08e1b0a9c8 | ||
|
|
ef4deb1657 | ||
|
|
f81074c4f5 | ||
|
|
5df14c344e | ||
|
|
cd311f076c | ||
|
|
d60f165223 | ||
|
|
8477128605 | ||
|
|
84606543ae | ||
|
|
a11242e93d | ||
|
|
5939a99aca | ||
|
|
050abd9fab | ||
|
|
1adf2ad5a8 | ||
|
|
3f2d83d89f | ||
|
|
528a4fbb97 | ||
|
|
95e2ad3007 | ||
|
|
c41e5ddc2c | ||
|
|
f206b3d135 | ||
|
|
0b03bcb90e | ||
|
|
b09b32b121 | ||
|
|
d5f7065fdb | ||
|
|
dc40cc664d | ||
|
|
3eaf84e961 | ||
|
|
c36249b5a7 | ||
|
|
3666c260ee | ||
|
|
77f3fd3b38 | ||
|
|
848bcbfb8f | ||
|
|
24936d8b7b | ||
|
|
ad62f9d2bd | ||
|
|
829dd937d6 | ||
|
|
dda4b17a7c | ||
|
|
4def31e98f | ||
|
|
6d3f5495cb | ||
|
|
008af08148 | ||
|
|
ac0930a11f | ||
|
|
0e62800af6 | ||
|
|
b6ab1ef80a | ||
|
|
13347edced | ||
|
|
d734841184 | ||
|
|
a2998b6c84 | ||
|
|
da5df7164a | ||
|
|
3e28160fa7 | ||
|
|
2b9bdb9c80 | ||
|
|
90ce124bbb | ||
|
|
fba3f46779 | ||
|
|
b9a1522abc | ||
|
|
f92a95dc2e | ||
|
|
46acac5dd8 | ||
|
|
8dbd96a2f9 | ||
|
|
3b186b19e6 | ||
|
|
53ec5daa1b | ||
|
|
96b58422fd | ||
|
|
25970e72de | ||
|
|
e5887ec0fa | ||
|
|
e075dcdeaa | ||
|
|
3ab735ba9c | ||
|
|
d429f0ee04 | ||
|
|
3d0a853c4b | ||
|
|
3a46375fed | ||
|
|
07de77ddc6 | ||
|
|
cf45443726 | ||
|
|
629b9391dd | ||
|
|
25da11c497 | ||
|
|
003e2630e7 | ||
|
|
4eef7138c1 | ||
|
|
253d0174be | ||
|
|
5ee5c117c4 | ||
|
|
0f268bbef7 | ||
|
|
d342e3f9e0 | ||
|
|
7f1e20fe19 | ||
|
|
3078423848 | ||
|
|
9953d73444 | ||
|
|
100136aae7 | ||
|
|
3c6e9aaa63 | ||
|
|
8fa39f2ae5 | ||
|
|
3aca72fb06 | ||
|
|
c46905e9a7 | ||
|
|
5ce96c7704 | ||
|
|
23eb77b8ac | ||
|
|
e63edc9d36 | ||
|
|
d33681eddd | ||
|
|
e7816cfb0c | ||
|
|
a268d8743d | ||
|
|
45db5c0d5e | ||
|
|
583661a15d | ||
|
|
461d5e0535 | ||
|
|
099d830e7e | ||
|
|
add59896f5 | ||
|
|
03b97fdb51 | ||
|
|
4c576fbd57 | ||
|
|
06ce1988f3 | ||
|
|
c059d79a51 | ||
|
|
b91c767d0c | ||
|
|
bb29edd30f | ||
|
|
b9a8b613bb | ||
|
|
76377d2d2c | ||
|
|
f4f09eaf9e |
No files matched your search
@@ -259,6 +259,8 @@ NEXT_PUBLIC_AVAILABILITY_SCHEDULE_INTERVAL=
|
|||||||
# This variable should only be set to 1 or true if you are in a non-prod environment and you want to
|
# This variable should only be set to 1 or true if you are in a non-prod environment and you want to
|
||||||
# use organizations
|
# use organizations
|
||||||
ORGANIZATIONS_ENABLED=
|
ORGANIZATIONS_ENABLED=
|
||||||
|
NEXT_PUBLIC_ORGANIZATIONS_MIN_SELF_SERVE_SEATS=30
|
||||||
|
NEXT_PUBLIC_ORGANIZATIONS_SELF_SERVE_PRICE=3700 # $37.00 per seat
|
||||||
|
|
||||||
# This variable should only be set to 1 or true if you want to autolink external provider sing-ups with
|
# This variable should only be set to 1 or true if you want to autolink external provider sing-ups with
|
||||||
# existing organizations based on email domain address
|
# existing organizations based on email domain address
|
||||||
|
|||||||
@@ -37,8 +37,6 @@ runs:
|
|||||||
with:
|
with:
|
||||||
path: ${{ steps.yarn-config.outputs.CACHE_FOLDER }}
|
path: ${{ steps.yarn-config.outputs.CACHE_FOLDER }}
|
||||||
key: yarn-download-cache-${{ hashFiles('yarn.lock') }}
|
key: yarn-download-cache-${{ hashFiles('yarn.lock') }}
|
||||||
restore-keys: |
|
|
||||||
yarn-download-cache-
|
|
||||||
|
|
||||||
# Invalidated on yarn.lock changes
|
# Invalidated on yarn.lock changes
|
||||||
- name: Restore node_modules
|
- name: Restore node_modules
|
||||||
|
|||||||
@@ -3,6 +3,10 @@ description: "Install playwright, cache and restore if necessary"
|
|||||||
runs:
|
runs:
|
||||||
using: "composite"
|
using: "composite"
|
||||||
steps:
|
steps:
|
||||||
|
- name: Get installed Playwright version
|
||||||
|
shell: bash
|
||||||
|
id: playwright-version
|
||||||
|
run: echo "PLAYWRIGHT_VERSION=$(node -e "console.log(require('./package.json').devDependencies['@playwright/test'])")" >> $GITHUB_ENV
|
||||||
- name: Cache playwright binaries
|
- name: Cache playwright binaries
|
||||||
id: playwright-cache
|
id: playwright-cache
|
||||||
uses: buildjet/cache@v4
|
uses: buildjet/cache@v4
|
||||||
@@ -11,9 +15,7 @@ runs:
|
|||||||
~/Library/Caches/ms-playwright
|
~/Library/Caches/ms-playwright
|
||||||
~/.cache/ms-playwright
|
~/.cache/ms-playwright
|
||||||
${{ github.workspace }}/node_modules/playwright
|
${{ github.workspace }}/node_modules/playwright
|
||||||
key: cache-playwright-${{ hashFiles('**/yarn.lock') }}
|
key: ${{ runner.os }}-playwright-${{ env.PLAYWRIGHT_VERSION }}
|
||||||
restore-keys: cache-playwright-
|
|
||||||
- name: Yarn playwright install
|
- name: Yarn playwright install
|
||||||
shell: bash
|
shell: bash
|
||||||
if: steps.playwright-cache.outputs.cache-hit != 'true'
|
run: yarn playwright install --with-deps
|
||||||
run: yarn playwright install
|
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
name: Delete
|
||||||
|
|
||||||
|
on:
|
||||||
|
delete:
|
||||||
|
branches-ignore: [main, gh-pages]
|
||||||
|
|
||||||
|
# ensures that currently running Playwright workflow of deleted branch gets cancelled
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.event.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
delete_reports:
|
||||||
|
name: Delete Reports
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
# Contains all reports for deleted branch
|
||||||
|
BRANCH_REPORTS_DIR: reports/${{ github.event.ref }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout GitHub Pages Branch
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
ref: gh-pages
|
||||||
|
- name: Set Git User
|
||||||
|
# see: https://github.com/actions/checkout/issues/13#issuecomment-724415212
|
||||||
|
run: |
|
||||||
|
git config --global user.name "github-actions[bot]"
|
||||||
|
git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||||
|
- name: Check for workflow reports
|
||||||
|
run: |
|
||||||
|
if [ -z "$(ls -A $BRANCH_REPORTS_DIR)" ]; then
|
||||||
|
echo "BRANCH_REPORTS_EXIST="false"" >> $GITHUB_ENV
|
||||||
|
else
|
||||||
|
echo "BRANCH_REPORTS_EXIST="true"" >> $GITHUB_ENV
|
||||||
|
fi
|
||||||
|
- name: Delete reports from repo for branch
|
||||||
|
if: ${{ env.BRANCH_REPORTS_EXIST == 'true' }}
|
||||||
|
timeout-minutes: 3
|
||||||
|
run: |
|
||||||
|
cd $BRANCH_REPORTS_DIR/..
|
||||||
|
|
||||||
|
rm -rf ${{ github.event.ref }}
|
||||||
|
git add .
|
||||||
|
git commit -m "workflow: remove all reports for branch ${{ github.event.ref }}"
|
||||||
|
|
||||||
|
while true; do
|
||||||
|
git pull --rebase
|
||||||
|
if [ $? -ne 0 ]; then
|
||||||
|
echo "Failed to rebase. Please review manually."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
git push
|
||||||
|
if [ $? -eq 0 ]; then
|
||||||
|
echo "Successfully pushed HTML reports to repo."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
@@ -98,5 +98,5 @@ jobs:
|
|||||||
if: ${{ always() }}
|
if: ${{ always() }}
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: app-store-results
|
name: blob-report-app-store
|
||||||
path: test-results
|
path: blob-report
|
||||||
@@ -85,5 +85,5 @@ jobs:
|
|||||||
if: ${{ always() }}
|
if: ${{ always() }}
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: embed-react-results
|
name: blob-report-embed-react
|
||||||
path: test-results
|
path: blob-report
|
||||||
@@ -91,5 +91,5 @@ jobs:
|
|||||||
if: ${{ always() }}
|
if: ${{ always() }}
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: embed-core-results
|
name: blob-report-embed-core
|
||||||
path: test-results
|
path: blob-report
|
||||||
@@ -89,8 +89,9 @@ jobs:
|
|||||||
- name: Run Tests
|
- name: Run Tests
|
||||||
run: yarn e2e --shard=${{ matrix.shard }}/${{ strategy.job-total }}
|
run: yarn e2e --shard=${{ matrix.shard }}/${{ strategy.job-total }}
|
||||||
- name: Upload Test Results
|
- name: Upload Test Results
|
||||||
if: ${{ always() }}
|
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
|
if: always()
|
||||||
with:
|
with:
|
||||||
name: test-results-${{ matrix.shard }}_${{ strategy.job-total }}
|
name: blob-report-${{ matrix.shard }}
|
||||||
path: test-results
|
path: blob-report
|
||||||
|
retention-days: 30
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# https://playwright.dev/docs/test-sharding#merging-reports-from-multiple-shards
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
jobs:
|
||||||
|
merge-reports:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: ./.github/actions/dangerous-git-checkout
|
||||||
|
- uses: ./.github/actions/yarn-install
|
||||||
|
- uses: ./.github/actions/yarn-playwright-install
|
||||||
|
- name: Download blob reports from GitHub Actions Artifacts
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
path: all-blob-reports
|
||||||
|
pattern: blob-report-*
|
||||||
|
merge-multiple: true
|
||||||
|
- name: Merge into HTML Report
|
||||||
|
run: yarn playwright merge-reports --reporter html ./all-blob-reports
|
||||||
|
- name: Upload HTML report
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: html-report--attempt-${{ github.run_number }}-${{ github.run_attempt }}
|
||||||
|
path: playwright-report
|
||||||
|
retention-days: 14
|
||||||
@@ -7,11 +7,14 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
label-pr:
|
label-pr:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
actions: read
|
||||||
|
issues: write
|
||||||
|
pull-requests: write
|
||||||
steps:
|
steps:
|
||||||
- name: Label PR as ready for E2E
|
- name: Label PR as ready for E2E
|
||||||
if: github.event.review.state == 'approved'
|
if: github.event.review.state == 'approved'
|
||||||
uses: actions-ecosystem/action-add-labels@v1
|
uses: actions-ecosystem/action-add-labels@v1
|
||||||
with:
|
with:
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
github_token: ${{ secrets.READY_FOR_E2E_PAT }}
|
||||||
labels: 'ready-for-e2e'
|
labels: 'ready-for-e2e'
|
||||||
@@ -91,44 +91,50 @@ jobs:
|
|||||||
console.log('Found the label?', labelFound);
|
console.log('Found the label?', labelFound);
|
||||||
core.setOutput('run-e2e', labelFound);
|
core.setOutput('run-e2e', labelFound);
|
||||||
|
|
||||||
|
deps:
|
||||||
|
name: Install dependencies
|
||||||
|
needs: [changes, check-label]
|
||||||
|
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
||||||
|
uses: ./.github/workflows/yarn-install.yml
|
||||||
|
|
||||||
type-check:
|
type-check:
|
||||||
name: Type check
|
name: Type check
|
||||||
needs: [changes, check-label]
|
needs: [changes, check-label, deps]
|
||||||
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
||||||
uses: ./.github/workflows/check-types.yml
|
uses: ./.github/workflows/check-types.yml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
|
|
||||||
lint:
|
lint:
|
||||||
name: Linters
|
name: Linters
|
||||||
needs: [changes, check-label]
|
needs: [changes, check-label, deps]
|
||||||
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
||||||
uses: ./.github/workflows/lint.yml
|
uses: ./.github/workflows/lint.yml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
|
|
||||||
unit-test:
|
unit-test:
|
||||||
name: Tests
|
name: Tests
|
||||||
needs: [changes, check-label]
|
needs: [changes, check-label, deps]
|
||||||
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
||||||
uses: ./.github/workflows/unit-tests.yml
|
uses: ./.github/workflows/unit-tests.yml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
|
|
||||||
build-api-v1:
|
build-api-v1:
|
||||||
name: Production builds
|
name: Production builds
|
||||||
needs: [changes, check-label]
|
needs: [changes, check-label, deps]
|
||||||
if: ${{ needs.check-label.outputs.run-e2e == 'true' && needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
if: ${{ needs.check-label.outputs.run-e2e == 'true' && needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
||||||
uses: ./.github/workflows/api-v1-production-build.yml
|
uses: ./.github/workflows/api-v1-production-build.yml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
|
|
||||||
build-api-v2:
|
build-api-v2:
|
||||||
name: Production builds
|
name: Production builds
|
||||||
needs: [changes, check-label]
|
needs: [changes, check-label, deps]
|
||||||
if: ${{ needs.check-label.outputs.run-e2e == 'true' && needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
if: ${{ needs.check-label.outputs.run-e2e == 'true' && needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
||||||
uses: ./.github/workflows/api-v2-production-build.yml
|
uses: ./.github/workflows/api-v2-production-build.yml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
|
|
||||||
build:
|
build:
|
||||||
name: Production builds
|
name: Production builds
|
||||||
needs: [changes, check-label]
|
needs: [changes, check-label, deps]
|
||||||
if: ${{ needs.check-label.outputs.run-e2e == 'true' && needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
if: ${{ needs.check-label.outputs.run-e2e == 'true' && needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
||||||
uses: ./.github/workflows/production-build-without-database.yml
|
uses: ./.github/workflows/production-build-without-database.yml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
@@ -181,8 +187,42 @@ jobs:
|
|||||||
uses: ./.github/workflows/nextjs-bundle-analysis.yml
|
uses: ./.github/workflows/nextjs-bundle-analysis.yml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
|
|
||||||
|
merge-reports:
|
||||||
|
name: Merge reports
|
||||||
|
if: ${{ !cancelled() && needs.check-label.outputs.run-e2e == 'true' && needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
||||||
|
needs: [changes, check-label, e2e, e2e-embed, e2e-embed-react, e2e-app-store]
|
||||||
|
uses: ./.github/workflows/merge-reports.yml
|
||||||
|
secrets: inherit
|
||||||
|
|
||||||
|
publish-report:
|
||||||
|
name: Publish HTML report
|
||||||
|
if: ${{ !cancelled() && needs.check-label.outputs.run-e2e == 'true' && needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
issues: write
|
||||||
|
pull-requests: write
|
||||||
|
needs: [changes, check-label, merge-reports]
|
||||||
|
uses: ./.github/workflows/publish-report.yml
|
||||||
|
secrets: inherit
|
||||||
|
|
||||||
required:
|
required:
|
||||||
needs: [changes, lint, type-check, unit-test, integration-test, check-label, build, build-api-v1, build-api-v2, e2e, e2e-api-v2, e2e-embed, e2e-embed-react, e2e-app-store]
|
needs:
|
||||||
|
[
|
||||||
|
changes,
|
||||||
|
lint,
|
||||||
|
type-check,
|
||||||
|
unit-test,
|
||||||
|
integration-test,
|
||||||
|
check-label,
|
||||||
|
build,
|
||||||
|
build-api-v1,
|
||||||
|
build-api-v2,
|
||||||
|
e2e,
|
||||||
|
e2e-api-v2,
|
||||||
|
e2e-embed,
|
||||||
|
e2e-embed-react,
|
||||||
|
e2e-app-store,
|
||||||
|
]
|
||||||
if: always()
|
if: always()
|
||||||
runs-on: buildjet-2vcpu-ubuntu-2204
|
runs-on: buildjet-2vcpu-ubuntu-2204
|
||||||
steps:
|
steps:
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
issues: write
|
||||||
|
pull-requests: write
|
||||||
|
jobs:
|
||||||
|
publish-report:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
continue-on-error: true
|
||||||
|
env:
|
||||||
|
# Unique URL path for each workflow run attempt
|
||||||
|
HTML_REPORT_URL_PATH: reports/${{ github.ref_name }}/${{ github.run_id }}/${{ github.run_attempt }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout GitHub Pages Branch
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: gh-pages
|
||||||
|
- name: Set Git User
|
||||||
|
# see: https://github.com/actions/checkout/issues/13#issuecomment-724415212
|
||||||
|
run: |
|
||||||
|
git config --global user.name "github-actions[bot]"
|
||||||
|
git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||||
|
- name: Download zipped HTML report
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: html-report--attempt-${{ github.run_number }}-${{ github.run_attempt }}
|
||||||
|
path: ${{ env.HTML_REPORT_URL_PATH }}
|
||||||
|
- name: Push HTML Report
|
||||||
|
timeout-minutes: 3
|
||||||
|
# commit report, then try push-rebase-loop until it's able to merge the HTML report to the gh-pages branch
|
||||||
|
# this is necessary when this job running at least twice at the same time (e.g. through two pushes at the same time)
|
||||||
|
run: |
|
||||||
|
git add .
|
||||||
|
git commit -m "workflow: add HTML report for run-id ${{ github.run_id }} (attempt: ${{ github.run_attempt }})"
|
||||||
|
|
||||||
|
while true; do
|
||||||
|
git pull --rebase
|
||||||
|
if [ $? -ne 0 ]; then
|
||||||
|
echo "Failed to rebase. Please review manually."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
git push
|
||||||
|
if [ $? -eq 0 ]; then
|
||||||
|
echo "Successfully pushed HTML report to repo."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
- name: Output Report URL as Workflow Annotation
|
||||||
|
id: url
|
||||||
|
run: |
|
||||||
|
FULL_HTML_REPORT_URL=https://calcom.github.io/cal.com/$HTML_REPORT_URL_PATH
|
||||||
|
echo "::notice title=📋 Published Playwright Test Report::$FULL_HTML_REPORT_URL"
|
||||||
|
echo "link=$FULL_HTML_REPORT_URL" >> $GITHUB_OUTPUT
|
||||||
|
- name: Find Comment
|
||||||
|
uses: peter-evans/find-comment@v2
|
||||||
|
id: fc
|
||||||
|
with:
|
||||||
|
issue-number: ${{ github.event.pull_request.number }}
|
||||||
|
comment-author: "github-actions[bot]"
|
||||||
|
body-includes: <!-- GENERATED-E2E-RESULTS -->
|
||||||
|
- name: Create comment
|
||||||
|
if: steps.fc.outputs.comment-id == ''
|
||||||
|
uses: peter-evans/create-or-update-comment@v3
|
||||||
|
with:
|
||||||
|
issue-number: ${{ github.event.pull_request.number }}
|
||||||
|
body: |
|
||||||
|
<!-- GENERATED-E2E-RESULTS -->
|
||||||
|
## E2E results are ready!
|
||||||
|
- [Attempt #${{ github.run_number }}.${{ github.run_attempt }} results](${{ steps.url.outputs.link }})
|
||||||
|
- name: Update comment
|
||||||
|
if: steps.fc.outputs.comment-id != ''
|
||||||
|
uses: peter-evans/create-or-update-comment@v3
|
||||||
|
with:
|
||||||
|
comment-id: ${{ steps.fc.outputs.comment-id }}
|
||||||
|
body: |
|
||||||
|
- [Attempt #${{ github.run_number }}.${{ github.run_attempt }} results](${{ steps.url.outputs.link }})
|
||||||
@@ -15,3 +15,4 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: ./.github/actions/dangerous-git-checkout
|
- uses: ./.github/actions/dangerous-git-checkout
|
||||||
- uses: ./.github/actions/yarn-install
|
- uses: ./.github/actions/yarn-install
|
||||||
|
- uses: ./.github/actions/yarn-playwright-install
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
<a href="https://cal.com"><strong>Learn more »</strong></a>
|
<a href="https://cal.com"><strong>Learn more »</strong></a>
|
||||||
<br />
|
<br />
|
||||||
<br />
|
<br />
|
||||||
<a href="https://go.cal.com/discord">Discord</a>
|
<a href="https://github.com/calcom/cal.com/discussions">Discussions</a>
|
||||||
·
|
·
|
||||||
<a href="https://cal.com">Website</a>
|
<a href="https://cal.com">Website</a>
|
||||||
·
|
·
|
||||||
@@ -23,7 +23,6 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://go.cal.com/discord"><img src="https://img.shields.io/badge/Discord-go.cal.com%2Fdiscord-%234A154B" alt="Join Cal.com Discord"></a>
|
|
||||||
<a href="https://www.producthunt.com/products/cal-com"><img src="https://img.shields.io/badge/Product%20Hunt-%231%20Product%20of%20the%20Month-%23DA552E" alt="Product Hunt"></a>
|
<a href="https://www.producthunt.com/products/cal-com"><img src="https://img.shields.io/badge/Product%20Hunt-%231%20Product%20of%20the%20Month-%23DA552E" alt="Product Hunt"></a>
|
||||||
<a href="https://status.cal.com"><img height="20px" src="https://betteruptime.com/status-badges/v1/monitor/a9kf.svg" alt="Uptime"></a>
|
<a href="https://status.cal.com"><img height="20px" src="https://betteruptime.com/status-badges/v1/monitor/a9kf.svg" alt="Uptime"></a>
|
||||||
<a href="https://github.com/calcom/cal.com/stargazers"><img src="https://img.shields.io/github/stars/calcom/cal.com" alt="Github Stars"></a>
|
<a href="https://github.com/calcom/cal.com/stargazers"><img src="https://img.shields.io/github/stars/calcom/cal.com" alt="Github Stars"></a>
|
||||||
@@ -37,7 +36,6 @@
|
|||||||
<a href="https://twitch.tv/calcomtv"><img src="https://img.shields.io/twitch/status/calcomtv?style=flat"></a>
|
<a href="https://twitch.tv/calcomtv"><img src="https://img.shields.io/twitch/status/calcomtv?style=flat"></a>
|
||||||
<a href="https://github.com/calcom/cal.com/issues?q=is:issue+is:open+label:%22%F0%9F%99%8B%F0%9F%8F%BB%E2%80%8D%E2%99%82%EF%B8%8Fhelp+wanted%22"><img src="https://img.shields.io/badge/Help%20Wanted-Contribute-blue"></a>
|
<a href="https://github.com/calcom/cal.com/issues?q=is:issue+is:open+label:%22%F0%9F%99%8B%F0%9F%8F%BB%E2%80%8D%E2%99%82%EF%B8%8Fhelp+wanted%22"><img src="https://img.shields.io/badge/Help%20Wanted-Contribute-blue"></a>
|
||||||
<a href="https://cal.com/figma"><img src="https://img.shields.io/badge/Figma-Design%20System-blueviolet"></a>
|
<a href="https://cal.com/figma"><img src="https://img.shields.io/badge/Figma-Design%20System-blueviolet"></a>
|
||||||
<a href="https://discord.com/channels/1125390093386010654/1125398231585661040"><img src="https://img.shields.io/badge/translations-contribute-brightgreen" /></a>
|
|
||||||
<a href="https://contributor-covenant.org/version/1/4/code-of-conduct/ "><img src="https://img.shields.io/badge/Contributor%20Covenant-1.4-purple" /></a>
|
<a href="https://contributor-covenant.org/version/1/4/code-of-conduct/ "><img src="https://img.shields.io/badge/Contributor%20Covenant-1.4-purple" /></a>
|
||||||
<a href="https://console.algora.io/org/cal/bounties?status=open"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fconsole.algora.io%2Fapi%2Fshields%2Fcal%2Fbounties%3Fstatus%3Dopen" /></a>
|
<a href="https://console.algora.io/org/cal/bounties?status=open"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fconsole.algora.io%2Fapi%2Fshields%2Fcal%2Fbounties%3Fstatus%3Dopen" /></a>
|
||||||
</p>
|
</p>
|
||||||
@@ -461,7 +459,7 @@ We have a list of [help wanted](https://github.com/calcom/cal.com/issues?q=is:is
|
|||||||
|
|
||||||
### Translations
|
### Translations
|
||||||
|
|
||||||
Don't code but still want to contribute? Join our [discord](https://go.cal.com/discord) and join the [#Translate channel](https://discord.com/channels/1125390093386010654/1125398231585661040) and let us know what language you want to translate.
|
Don't code but still want to contribute? Join our [Discussions](https://github.com/calcom/cal.com/discussions) and join the [#Translate channel](https://github.com/calcom/cal.com/discussions/categories/translations) and let us know what language you want to translate.
|
||||||
|
|
||||||
                                            !
|
|
||||||
|
|
||||||
This app lets you chat with your calendar via email:
|
|
||||||
|
|
||||||
- Turn informal emails into bookings eg. forward "wanna meet tmrw at 2pm?"
|
|
||||||
- List and rearrange your bookings eg. "clear my afternoon"
|
|
||||||
- Answer basic questions about your busiest times eg. "how does my Tuesday look?"
|
|
||||||
|
|
||||||
The core logic is contained in [agent/route.ts](/apps/ai/src/app/api/agent/route.ts). Here, a [LangChain Agent Executor](https://docs.langchain.com/docs/components/agents/agent-executor) is tasked with following your instructions. Given your last-known timezone, working hours, and busy times, it attempts to CRUD your bookings.
|
|
||||||
|
|
||||||
_The AI agent can only choose from a set of tools, without ever seeing your API key._
|
|
||||||
|
|
||||||
Emails are cleaned and routed in [receive/route.ts](/apps/ai/src/app/api/receive/route.ts) using [MailParser](https://nodemailer.com/extras/mailparser/).
|
|
||||||
|
|
||||||
Incoming emails are routed by email address. Addresses are verified by [DKIM record](https://support.google.com/a/answer/174124?hl=en), making them hard to spoof.
|
|
||||||
|
|
||||||
## Recognition
|
|
||||||
|
|
||||||
<a href="https://www.producthunt.com/posts/cal-ai?utm_source=badge-top-post-badge&utm_medium=badge&utm_souce=badge-cal-ai" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/top-post-badge.svg?post_id=419860&theme=light&period=daily" alt="Cal.ai - World's first open source AI scheduling assistant | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a> <a href="https://www.producthunt.com/posts/cal-ai?utm_source=badge-featured&utm_medium=badge&utm_souce=badge-cal-ai" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=419860&theme=light" alt="Cal.ai - World's first open source AI scheduling assistant | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a>
|
|
||||||
|
|
||||||
## Getting Started
|
|
||||||
|
|
||||||
### Development
|
|
||||||
|
|
||||||
If you haven't yet, please run the [root setup](/README.md) steps.
|
|
||||||
|
|
||||||
Before running the app, please see [env.mjs](./src/env.mjs) for all required environment variables. Run `cp .env.example .env` in this folder to get started. You'll need:
|
|
||||||
|
|
||||||
- An [OpenAI API key](https://platform.openai.com/account/api-keys) with access to GPT-4
|
|
||||||
- A [SendGrid API key](https://app.sendgrid.com/settings/api_keys)
|
|
||||||
- A default sender email (for example, `[email protected]`)
|
|
||||||
- The Cal.ai app's ID and URL (see [add.ts](/packages/app-store/cal-ai/api/index.ts))
|
|
||||||
- A unique value for `PARSE_KEY` with `openssl rand -hex 32`
|
|
||||||
|
|
||||||
To stand up the API and AI apps simultaneously, simply run `yarn dev:ai`.
|
|
||||||
|
|
||||||
### Agent Architecture
|
|
||||||
|
|
||||||
The scheduling agent in [agent/route.ts](/apps/ai/src/app/api/agent/route.ts) calls an LLM (in this case, GPT-4) in a loop to accomplish a multi-step task. We use an [OpenAI Functions agent](https://js.langchain.com/docs/modules/agents/agent_types/openai_functions_agent), which is fine-tuned to output text suited for passing to tools.
|
|
||||||
|
|
||||||
Tools (eg. [`createBooking`](/apps/ai/src/tools/createBooking.ts)) are simply JavaScript methods wrapped by Zod schemas, telling the agent what format to output.
|
|
||||||
|
|
||||||
Here is the full architecture:
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
### Email Router
|
|
||||||
|
|
||||||
To expose the AI app, you can use either [Tunnelmole](https://github.com/robbie-cahill/tunnelmole-client), an open source tunnelling tool; or [nGrok](https://ngrok.com/), a popular closed source tunnelling tool.
|
|
||||||
|
|
||||||
For Tunnelmole, run `tmole 3005` (or the AI app's port number) in a new terminal. Please replace `3005` with the port number if it is different. In the output, you'll see two URLs, one http and a https (we recommend using the https url for privacy and security). To install Tunnelmole, use `curl -O https://install.tunnelmole.com/8dPBw/install && sudo bash install`. (On Windows, download [tmole.exe](https://tunnelmole.com/downloads/tmole.exe))
|
|
||||||
|
|
||||||
For nGrok, run `ngrok http 3005` (or the AI app's port number) in a new terminal. You may need to install nGrok first.
|
|
||||||
|
|
||||||
To forward incoming emails to the serverless function at `/agent`, we use [SendGrid's Inbound Parse](https://docs.sendgrid.com/for-developers/parsing-email/setting-up-the-inbound-parse-webhook).
|
|
||||||
|
|
||||||
1. Ensure you have a [SendGrid account](https://signup.sendgrid.com/)
|
|
||||||
2. Ensure you have an authenticated domain. Go to Settings > Sender Authentication > Authenticate. For DNS host, select `I'm not sure`. Click Next and add your domain, eg. `example.com`. Choose Manual Setup. You'll be given three CNAME records to add to your DNS settings, eg. in [Vercel Domains](https://vercel.com/dashboard/domains). After adding those records, click Verify. To troubleshoot, see the [full instructions](https://docs.sendgrid.com/ui/account-and-settings/how-to-set-up-domain-authentication).
|
|
||||||
3. Authorize your domain for email with MX records: one with name `[your domain].com` and value `mx.sendgrid.net.`, and another with name `bounces.[your domain].com` and value `feedback-smtp.us-east-1.amazonses.com`. Set the priority to `10` if prompted.
|
|
||||||
4. Go to Settings > [Inbound Parse](https://app.sendgrid.com/settings/parse) > Add Host & URL. Choose your authenticated domain.
|
|
||||||
5. In the Destination URL field, use the Tunnelmole or ngrok URL from above along with the path, `/api/receive`, and one param, `parseKey`, which lives in [this app's .env](/apps/ai/.env.example) under `PARSE_KEY`. The full URL should look like `https://abc.tunnelmole.net/api/receive?parseKey=ABC-123` or `https://abc.ngrok.io/api/receive?parseKey=ABC-123`.
|
|
||||||
6. Activate "POST the raw, full MIME message".
|
|
||||||
7. Send an email to `[anyUsername]@example.com`. You should see a ping on the Tunnelmole or ngrok listener and server.
|
|
||||||
8. Adjust the logic in [receive/route.ts](/apps/ai/src/app/api/receive/route.ts), save to hot-reload, and send another email to test the behaviour.
|
|
||||||
|
|
||||||
Please feel free to improve any part of this architecture!
|
|
||||||
Vendored
-5
@@ -1,5 +0,0 @@
|
|||||||
/// <reference types="next" />
|
|
||||||
/// <reference types="next/image-types/global" />
|
|
||||||
|
|
||||||
// NOTE: This file should not be edited
|
|
||||||
// see https://nextjs.org/docs/basic-features/typescript for more information.
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
const withBundleAnalyzer = require("@next/bundle-analyzer");
|
|
||||||
|
|
||||||
const plugins = [];
|
|
||||||
plugins.push(withBundleAnalyzer({ enabled: process.env.ANALYZE === "true" }));
|
|
||||||
|
|
||||||
/** @type {import("next").NextConfig} */
|
|
||||||
const nextConfig = {
|
|
||||||
async redirects() {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
source: "/",
|
|
||||||
destination: "https://cal.com/ai",
|
|
||||||
permanent: true,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
},
|
|
||||||
i18n: {
|
|
||||||
defaultLocale: "en",
|
|
||||||
locales: ["en"],
|
|
||||||
},
|
|
||||||
reactStrictMode: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = () => plugins.reduce((acc, next) => next(acc), nextConfig);
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "@calcom/ai",
|
|
||||||
"version": "1.2.1",
|
|
||||||
"private": true,
|
|
||||||
"author": "Cal.com Inc.",
|
|
||||||
"dependencies": {
|
|
||||||
"@calcom/prisma": "*",
|
|
||||||
"@langchain/core": "^0.1.26",
|
|
||||||
"@langchain/openai": "^0.0.14",
|
|
||||||
"@t3-oss/env-nextjs": "^0.6.1",
|
|
||||||
"langchain": "^0.1.17",
|
|
||||||
"mailparser": "^3.6.5",
|
|
||||||
"next": "^13.5.4",
|
|
||||||
"supports-color": "8.1.1",
|
|
||||||
"zod": "^3.22.4"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/mailparser": "^3.4.0"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"build": "next build",
|
|
||||||
"dev": "next dev -p 3005",
|
|
||||||
"format": "npx prettier . --write",
|
|
||||||
"lint": "eslint . --ext .ts,.js,.tsx,.jsx",
|
|
||||||
"lint:fix": "eslint . --ext .ts,.js,.tsx,.jsx --fix",
|
|
||||||
"start": "next start"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
import type { NextRequest } from "next/server";
|
|
||||||
import { NextResponse } from "next/server";
|
|
||||||
|
|
||||||
import agent from "../../../utils/agent";
|
|
||||||
import sendEmail from "../../../utils/sendEmail";
|
|
||||||
import { verifyParseKey } from "../../../utils/verifyParseKey";
|
|
||||||
|
|
||||||
// Allow agent loop to run for up to 5 minutes
|
|
||||||
export const maxDuration = 300;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Launches a LangChain agent to process an incoming email,
|
|
||||||
* then sends the response to the user.
|
|
||||||
*/
|
|
||||||
export const POST = async (request: NextRequest) => {
|
|
||||||
const verified = verifyParseKey(request.url);
|
|
||||||
|
|
||||||
if (!verified) {
|
|
||||||
return new NextResponse("Unauthorized", { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const json = await request.json();
|
|
||||||
|
|
||||||
const { apiKey, userId, message, subject, user, users, replyTo: agentEmail } = json;
|
|
||||||
|
|
||||||
if ((!message && !subject) || !user) {
|
|
||||||
return new NextResponse("Missing fields", { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await agent(`${subject}\n\n${message}`, { ...user }, users, apiKey, userId, agentEmail);
|
|
||||||
|
|
||||||
// Send response to user
|
|
||||||
await sendEmail({
|
|
||||||
subject: `Re: ${subject}`,
|
|
||||||
text: response.replace(/(?:\r\n|\r|\n)/g, "\n"),
|
|
||||||
to: user.email,
|
|
||||||
from: agentEmail,
|
|
||||||
});
|
|
||||||
|
|
||||||
return new NextResponse("ok");
|
|
||||||
} catch (error) {
|
|
||||||
await sendEmail({
|
|
||||||
subject: `Re: ${subject}`,
|
|
||||||
text: "Thanks for using Cal.ai! We're experiencing high demand and can't currently process your request. Please try again later.",
|
|
||||||
to: user.email,
|
|
||||||
from: agentEmail,
|
|
||||||
});
|
|
||||||
|
|
||||||
return new NextResponse(
|
|
||||||
(error as Error).message || "Something went wrong. Please try again or reach out for help.",
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
import type { NextRequest } from "next/server";
|
|
||||||
|
|
||||||
import prisma from "@calcom/prisma";
|
|
||||||
|
|
||||||
import { env } from "../../../env.mjs";
|
|
||||||
import sendEmail from "../../../utils/sendEmail";
|
|
||||||
|
|
||||||
export const POST = async (request: NextRequest) => {
|
|
||||||
const { userId } = await request.json();
|
|
||||||
|
|
||||||
const user = await prisma.user.findUnique({
|
|
||||||
select: {
|
|
||||||
email: true,
|
|
||||||
name: true,
|
|
||||||
username: true,
|
|
||||||
},
|
|
||||||
where: {
|
|
||||||
id: userId,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return new Response("User not found", { status: 404 });
|
|
||||||
}
|
|
||||||
|
|
||||||
await sendEmail({
|
|
||||||
subject: "Welcome to Cal AI",
|
|
||||||
to: user.email,
|
|
||||||
from: `${user.username}@${env.SENDER_DOMAIN}`,
|
|
||||||
text: `Hi ${
|
|
||||||
user.name || `@${user.username}`
|
|
||||||
},\n\nI'm Cal AI, your personal booking assistant! I'll be here, 24/7 to help manage your busy schedule and find times to meet with the people you care about.\n\nHere are some things you can ask me:\n\n- "Book a meeting with @someone" (The @ symbol lets you tag Cal.com users)\n- "What meetings do I have today?" (I'll show you your schedule)\n- "Find a time for coffee with [email protected]" (I'll intro and send them some good times)\n\nI'm still learning, so if you have any feedback, please tweet it to @calcom!\n\nRemember, you can always reach me here, at ${
|
|
||||||
user.username
|
|
||||||
}@${
|
|
||||||
env.SENDER_DOMAIN
|
|
||||||
}.\n\nLooking forward to working together (:\n\n- Cal AI, Your personal booking assistant`,
|
|
||||||
html: `Hi ${
|
|
||||||
user.name || `@${user.username}`
|
|
||||||
},<br><br>I'm Cal AI, your personal booking assistant! I'll be here, 24/7 to help manage your busy schedule and find times to meet with the people you care about.<br><br>Here are some things you can ask me:<br><br>- "Book a meeting with @someone" (The @ symbol lets you tag Cal.com users)<br>- "What meetings do I have today?" (I'll show you your schedule)<br>- "Find a time for coffee with [email protected]" (I'll intro and send them some good times)<br><br>I'm still learning, so if you have any feedback, please send it to <a href="https://twitter.com/calcom">@calcom</a> on X!<br><br>Remember, you can always reach me here, at ${
|
|
||||||
user.username
|
|
||||||
}@${env.SENDER_DOMAIN}.<br><br>Looking forward to working together (:<br><br>- Cal AI`,
|
|
||||||
});
|
|
||||||
return new Response("OK", { status: 200 });
|
|
||||||
};
|
|
||||||
@@ -1,186 +0,0 @@
|
|||||||
import type { ParsedMail, Source } from "mailparser";
|
|
||||||
import { simpleParser } from "mailparser";
|
|
||||||
import type { NextRequest } from "next/server";
|
|
||||||
import { NextResponse } from "next/server";
|
|
||||||
|
|
||||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
|
||||||
import prisma from "@calcom/prisma";
|
|
||||||
|
|
||||||
import { env } from "../../../env.mjs";
|
|
||||||
import { fetchAvailability } from "../../../tools/getAvailability";
|
|
||||||
import { fetchEventTypes } from "../../../tools/getEventTypes";
|
|
||||||
import { extractUsers } from "../../../utils/extractUsers";
|
|
||||||
import getHostFromHeaders from "../../../utils/host";
|
|
||||||
import now from "../../../utils/now";
|
|
||||||
import sendEmail from "../../../utils/sendEmail";
|
|
||||||
import { verifyParseKey } from "../../../utils/verifyParseKey";
|
|
||||||
|
|
||||||
// Allow receive loop to run for up to 30 seconds
|
|
||||||
// Why so long? the rate determining API call (getAvailability, getEventTypes) can take up to 15 seconds at peak times so we give it a little extra time to complete.
|
|
||||||
export const maxDuration = 30;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verifies email signature and app authorization,
|
|
||||||
* then hands off to booking agent.
|
|
||||||
*/
|
|
||||||
export const POST = async (request: NextRequest) => {
|
|
||||||
const verified = verifyParseKey(request.url);
|
|
||||||
|
|
||||||
if (!verified) {
|
|
||||||
return new NextResponse("Unauthorized", { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const formData = await request.formData();
|
|
||||||
const body = Object.fromEntries(formData);
|
|
||||||
const envelope = JSON.parse(body.envelope as string);
|
|
||||||
|
|
||||||
const aiEmail = envelope.to[0];
|
|
||||||
const subject = body.subject || "";
|
|
||||||
|
|
||||||
try {
|
|
||||||
await checkRateLimitAndThrowError({
|
|
||||||
identifier: `ai:email:${envelope.from}`,
|
|
||||||
rateLimitingType: "ai",
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
await sendEmail({
|
|
||||||
subject: `Re: ${subject}`,
|
|
||||||
text: "Thanks for using Cal.ai! You've reached your daily limit. Please try again tomorrow.",
|
|
||||||
to: envelope.from,
|
|
||||||
from: aiEmail,
|
|
||||||
});
|
|
||||||
|
|
||||||
return new NextResponse("Exceeded rate limit", { status: 200 }); // Don't return 429 to avoid triggering retry logic in SendGrid
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse email from mixed MIME type
|
|
||||||
const parsed: ParsedMail = await simpleParser(body.email as Source);
|
|
||||||
|
|
||||||
if (!parsed.text && !parsed.subject) {
|
|
||||||
await sendEmail({
|
|
||||||
subject: `Re: ${subject}`,
|
|
||||||
text: "Thanks for using Cal.ai! It looks like you forgot to include a message. Please try again.",
|
|
||||||
to: envelope.from,
|
|
||||||
from: aiEmail,
|
|
||||||
});
|
|
||||||
return new NextResponse("Email missing text and subject", { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const user = await prisma.user.findUnique({
|
|
||||||
select: {
|
|
||||||
email: true,
|
|
||||||
id: true,
|
|
||||||
username: true,
|
|
||||||
timeZone: true,
|
|
||||||
credentials: {
|
|
||||||
select: {
|
|
||||||
appId: true,
|
|
||||||
key: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
where: { email: envelope.from },
|
|
||||||
});
|
|
||||||
|
|
||||||
// body.dkim looks like {@domain-com.22222222.gappssmtp.com : pass}
|
|
||||||
const signature = (body.dkim as string).includes(" : pass");
|
|
||||||
|
|
||||||
// User is not a cal.com user or is using an unverified email.
|
|
||||||
if (!signature || !user) {
|
|
||||||
await sendEmail({
|
|
||||||
html: `Thanks for your interest in Cal.ai! To get started, Make sure you have a <a href="https://cal.com/signup" target="_blank">cal.com</a> account with this email address and then install Cal.ai here: <a href="https://go.cal.com/ai" target="_blank">go.cal.com/ai</a>.`,
|
|
||||||
subject: `Re: ${subject}`,
|
|
||||||
text: `Thanks for your interest in Cal.ai! To get started, Make sure you have a cal.com account with this email address. You can sign up for an account at: https://cal.com/signup`,
|
|
||||||
to: envelope.from,
|
|
||||||
from: aiEmail,
|
|
||||||
});
|
|
||||||
|
|
||||||
return new NextResponse("ok");
|
|
||||||
}
|
|
||||||
|
|
||||||
const credential = user.credentials.find((c) => c.appId === env.APP_ID)?.key;
|
|
||||||
|
|
||||||
// User has not installed the app from the app store. Direct them to install it.
|
|
||||||
if (!(credential as { apiKey: string })?.apiKey) {
|
|
||||||
const url = env.APP_URL;
|
|
||||||
|
|
||||||
await sendEmail({
|
|
||||||
html: `Thanks for using Cal.ai! To get started, the app must be installed. <a href=${url} target="_blank">Click this link</a> to install it.`,
|
|
||||||
subject: `Re: ${subject}`,
|
|
||||||
text: `Thanks for using Cal.ai! To get started, the app must be installed. Click this link to install the Cal.ai app: ${url}`,
|
|
||||||
to: envelope.from,
|
|
||||||
from: aiEmail,
|
|
||||||
});
|
|
||||||
|
|
||||||
return new NextResponse("ok");
|
|
||||||
}
|
|
||||||
|
|
||||||
const { apiKey } = credential as { apiKey: string };
|
|
||||||
|
|
||||||
// Pre-fetch data relevant to most bookings.
|
|
||||||
const [eventTypes, availability, users] = await Promise.all([
|
|
||||||
fetchEventTypes({
|
|
||||||
apiKey,
|
|
||||||
}),
|
|
||||||
fetchAvailability({
|
|
||||||
apiKey,
|
|
||||||
userId: user.id,
|
|
||||||
dateFrom: now(user.timeZone),
|
|
||||||
dateTo: now(user.timeZone),
|
|
||||||
}),
|
|
||||||
extractUsers(`${parsed.text} ${parsed.subject}`),
|
|
||||||
]);
|
|
||||||
|
|
||||||
if ("error" in availability) {
|
|
||||||
await sendEmail({
|
|
||||||
subject: `Re: ${subject}`,
|
|
||||||
text: "Sorry, there was an error fetching your availability. Please try again.",
|
|
||||||
to: user.email,
|
|
||||||
from: aiEmail,
|
|
||||||
});
|
|
||||||
console.error(availability.error);
|
|
||||||
return new NextResponse("Error fetching availability. Please try again.", { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
if ("error" in eventTypes) {
|
|
||||||
await sendEmail({
|
|
||||||
subject: `Re: ${subject}`,
|
|
||||||
text: "Sorry, there was an error fetching your event types. Please try again.",
|
|
||||||
to: user.email,
|
|
||||||
from: aiEmail,
|
|
||||||
});
|
|
||||||
console.error(eventTypes.error);
|
|
||||||
return new NextResponse("Error fetching event types. Please try again.", { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const { workingHours } = availability;
|
|
||||||
|
|
||||||
const appHost = getHostFromHeaders(request.headers);
|
|
||||||
|
|
||||||
// Hand off to long-running agent endpoint to handle the email. (don't await)
|
|
||||||
fetch(`${appHost}/api/agent?parseKey=${env.PARSE_KEY}`, {
|
|
||||||
body: JSON.stringify({
|
|
||||||
apiKey,
|
|
||||||
userId: user.id,
|
|
||||||
message: parsed.text || "",
|
|
||||||
subject: parsed.subject || "",
|
|
||||||
replyTo: aiEmail,
|
|
||||||
user: {
|
|
||||||
email: user.email,
|
|
||||||
eventTypes,
|
|
||||||
username: user.username,
|
|
||||||
timeZone: user.timeZone,
|
|
||||||
workingHours,
|
|
||||||
},
|
|
||||||
users,
|
|
||||||
}),
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
method: "POST",
|
|
||||||
});
|
|
||||||
|
|
||||||
await new Promise((r) => setTimeout(r, 1000));
|
|
||||||
|
|
||||||
return new NextResponse("ok");
|
|
||||||
};
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
import { createEnv } from "@t3-oss/env-nextjs";
|
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
export const env = createEnv({
|
|
||||||
/**
|
|
||||||
* Specify your client-side environment variables schema here. This way you can ensure the app
|
|
||||||
* isn't built with invalid env vars. To expose them to the client, prefix them with
|
|
||||||
* `NEXT_PUBLIC_`.
|
|
||||||
*/
|
|
||||||
client: {
|
|
||||||
// NEXT_PUBLIC_CLIENTVAR: z.string().min(1),
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g.
|
|
||||||
* middlewares) or client-side so we need to destruct manually.
|
|
||||||
*/
|
|
||||||
runtimeEnv: {
|
|
||||||
BACKEND_URL: process.env.BACKEND_URL,
|
|
||||||
FRONTEND_URL: process.env.FRONTEND_URL,
|
|
||||||
APP_ID: process.env.APP_ID,
|
|
||||||
APP_URL: process.env.APP_URL,
|
|
||||||
SENDER_DOMAIN: process.env.SENDER_DOMAIN,
|
|
||||||
PARSE_KEY: process.env.PARSE_KEY,
|
|
||||||
NODE_ENV: process.env.NODE_ENV,
|
|
||||||
OPENAI_API_KEY: process.env.OPENAI_API_KEY,
|
|
||||||
SENDGRID_API_KEY: process.env.SENDGRID_API_KEY,
|
|
||||||
DATABASE_URL: process.env.DATABASE_URL,
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Specify your server-side environment variables schema here. This way you can ensure the app
|
|
||||||
* isn't built with invalid env vars.
|
|
||||||
*/
|
|
||||||
server: {
|
|
||||||
BACKEND_URL: z.string().url(),
|
|
||||||
FRONTEND_URL: z.string().url(),
|
|
||||||
APP_ID: z.string().min(1),
|
|
||||||
APP_URL: z.string().url(),
|
|
||||||
SENDER_DOMAIN: z.string().min(1),
|
|
||||||
PARSE_KEY: z.string().min(1),
|
|
||||||
NODE_ENV: z.enum(["development", "test", "production"]),
|
|
||||||
OPENAI_API_KEY: z.string().min(1),
|
|
||||||
SENDGRID_API_KEY: z.string().min(1),
|
|
||||||
DATABASE_URL: z.string().url(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 125 KiB |
@@ -1,121 +0,0 @@
|
|||||||
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
import type { UserList } from "~/src/types/user";
|
|
||||||
|
|
||||||
import { env } from "../env.mjs";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a booking for a user by event type, times, and timezone.
|
|
||||||
*/
|
|
||||||
const createBooking = async ({
|
|
||||||
apiKey,
|
|
||||||
userId,
|
|
||||||
users,
|
|
||||||
eventTypeId,
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
timeZone,
|
|
||||||
language,
|
|
||||||
invite,
|
|
||||||
}: {
|
|
||||||
apiKey: string;
|
|
||||||
userId: number;
|
|
||||||
users: UserList;
|
|
||||||
eventTypeId: number;
|
|
||||||
start: string;
|
|
||||||
end: string;
|
|
||||||
timeZone: string;
|
|
||||||
language: string;
|
|
||||||
invite: number;
|
|
||||||
title?: string;
|
|
||||||
status?: string;
|
|
||||||
}): Promise<string | Error | { error: string }> => {
|
|
||||||
const params = {
|
|
||||||
apiKey,
|
|
||||||
userId: userId.toString(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const urlParams = new URLSearchParams(params);
|
|
||||||
|
|
||||||
const url = `${env.BACKEND_URL}/bookings?${urlParams.toString()}`;
|
|
||||||
|
|
||||||
const user = users.find((u) => u.id === invite);
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return { error: `User with id ${invite} not found to invite` };
|
|
||||||
}
|
|
||||||
|
|
||||||
const responses = {
|
|
||||||
id: invite.toString(),
|
|
||||||
name: user.username,
|
|
||||||
email: user.email,
|
|
||||||
};
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
body: JSON.stringify({
|
|
||||||
end,
|
|
||||||
eventTypeId,
|
|
||||||
language,
|
|
||||||
metadata: {},
|
|
||||||
responses,
|
|
||||||
start,
|
|
||||||
timeZone,
|
|
||||||
}),
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
method: "POST",
|
|
||||||
});
|
|
||||||
|
|
||||||
// Let GPT handle this. This will happen when wrong event type id is used.
|
|
||||||
// if (response.status === 401) throw new Error("Unauthorized");
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (response.status !== 200) {
|
|
||||||
return {
|
|
||||||
error: data.message,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return "Booking created";
|
|
||||||
};
|
|
||||||
|
|
||||||
const createBookingTool = (apiKey: string, userId: number, users: UserList) => {
|
|
||||||
return new DynamicStructuredTool({
|
|
||||||
description: "Creates a booking on the primary user's calendar.",
|
|
||||||
func: async ({ eventTypeId, start, end, timeZone, language, invite, title, status }) => {
|
|
||||||
return JSON.stringify(
|
|
||||||
await createBooking({
|
|
||||||
apiKey,
|
|
||||||
userId,
|
|
||||||
users,
|
|
||||||
end,
|
|
||||||
eventTypeId,
|
|
||||||
language,
|
|
||||||
invite,
|
|
||||||
start,
|
|
||||||
status,
|
|
||||||
timeZone,
|
|
||||||
title,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
},
|
|
||||||
name: "createBooking",
|
|
||||||
schema: z.object({
|
|
||||||
end: z
|
|
||||||
.string()
|
|
||||||
.describe("This should correspond to the event type's length, unless otherwise specified."),
|
|
||||||
eventTypeId: z.number(),
|
|
||||||
language: z.string(),
|
|
||||||
invite: z.number().describe("External user id to invite."),
|
|
||||||
start: z.string(),
|
|
||||||
status: z.string().optional().describe("ACCEPTED, PENDING, CANCELLED or REJECTED"),
|
|
||||||
timeZone: z.string(),
|
|
||||||
title: z.string().optional(),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export default createBookingTool;
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
import { env } from "../env.mjs";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cancels a booking for a user by ID with reason.
|
|
||||||
*/
|
|
||||||
const cancelBooking = async ({
|
|
||||||
apiKey,
|
|
||||||
id,
|
|
||||||
reason,
|
|
||||||
}: {
|
|
||||||
apiKey: string;
|
|
||||||
id: string;
|
|
||||||
reason: string;
|
|
||||||
}): Promise<string | { error: string }> => {
|
|
||||||
const params = {
|
|
||||||
apiKey,
|
|
||||||
};
|
|
||||||
|
|
||||||
const urlParams = new URLSearchParams(params);
|
|
||||||
|
|
||||||
const url = `${env.BACKEND_URL}/bookings/${id}/cancel?${urlParams.toString()}`;
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
body: JSON.stringify({ reason }),
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
method: "DELETE",
|
|
||||||
});
|
|
||||||
|
|
||||||
// Let GPT handle this. This will happen when wrong booking id is used.
|
|
||||||
// if (response.status === 401) throw new Error("Unauthorized");
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (response.status !== 200) {
|
|
||||||
return { error: data.message };
|
|
||||||
}
|
|
||||||
|
|
||||||
return "Booking cancelled";
|
|
||||||
};
|
|
||||||
|
|
||||||
const cancelBookingTool = (apiKey: string) => {
|
|
||||||
return new DynamicStructuredTool({
|
|
||||||
description: "Cancel a booking",
|
|
||||||
func: async ({ id, reason }) => {
|
|
||||||
return JSON.stringify(
|
|
||||||
await cancelBooking({
|
|
||||||
apiKey,
|
|
||||||
id,
|
|
||||||
reason,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
},
|
|
||||||
name: "cancelBooking",
|
|
||||||
schema: z.object({
|
|
||||||
id: z.string(),
|
|
||||||
reason: z.string(),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export default cancelBookingTool;
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
import { env } from "../env.mjs";
|
|
||||||
import type { Availability } from "../types/availability";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetches availability for a user by date range and event type.
|
|
||||||
*/
|
|
||||||
export const fetchAvailability = async ({
|
|
||||||
apiKey,
|
|
||||||
userId,
|
|
||||||
dateFrom,
|
|
||||||
dateTo,
|
|
||||||
}: {
|
|
||||||
apiKey: string;
|
|
||||||
userId: number;
|
|
||||||
dateFrom: string;
|
|
||||||
dateTo: string;
|
|
||||||
}): Promise<Partial<Availability> | { error: string }> => {
|
|
||||||
const params: { [k: string]: string } = {
|
|
||||||
apiKey,
|
|
||||||
userId: userId.toString(),
|
|
||||||
dateFrom,
|
|
||||||
dateTo,
|
|
||||||
};
|
|
||||||
|
|
||||||
const urlParams = new URLSearchParams(params);
|
|
||||||
|
|
||||||
const url = `${env.BACKEND_URL}/availability?${urlParams.toString()}`;
|
|
||||||
|
|
||||||
const response = await fetch(url);
|
|
||||||
|
|
||||||
if (response.status === 401) throw new Error("Unauthorized");
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (response.status !== 200) {
|
|
||||||
return { error: data.message };
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
busy: data.busy,
|
|
||||||
dateRanges: data.dateRanges,
|
|
||||||
timeZone: data.timeZone,
|
|
||||||
workingHours: data.workingHours,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const getAvailabilityTool = (apiKey: string) => {
|
|
||||||
return new DynamicStructuredTool({
|
|
||||||
description: "Get availability of users within range.",
|
|
||||||
func: async ({ userIds, dateFrom, dateTo }) => {
|
|
||||||
return JSON.stringify(
|
|
||||||
await Promise.all(
|
|
||||||
userIds.map(
|
|
||||||
async (userId) =>
|
|
||||||
await fetchAvailability({
|
|
||||||
userId: userId,
|
|
||||||
apiKey,
|
|
||||||
dateFrom,
|
|
||||||
dateTo,
|
|
||||||
})
|
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
},
|
|
||||||
name: "getAvailability",
|
|
||||||
schema: z.object({
|
|
||||||
userIds: z.array(z.number()).describe("The users to fetch availability for."),
|
|
||||||
dateFrom: z.string(),
|
|
||||||
dateTo: z.string(),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export default getAvailabilityTool;
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
import { env } from "../env.mjs";
|
|
||||||
import type { Booking } from "../types/booking";
|
|
||||||
import { BOOKING_STATUS } from "../types/booking";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetches bookings for a user by date range.
|
|
||||||
*/
|
|
||||||
const fetchBookings = async ({
|
|
||||||
apiKey,
|
|
||||||
userId,
|
|
||||||
from,
|
|
||||||
to,
|
|
||||||
}: {
|
|
||||||
apiKey: string;
|
|
||||||
userId: number;
|
|
||||||
from: string;
|
|
||||||
to: string;
|
|
||||||
}): Promise<Booking[] | { error: string }> => {
|
|
||||||
const params = {
|
|
||||||
apiKey,
|
|
||||||
userId: userId.toString(),
|
|
||||||
dateFrom: from,
|
|
||||||
dateTo: to,
|
|
||||||
};
|
|
||||||
|
|
||||||
const urlParams = new URLSearchParams(params);
|
|
||||||
|
|
||||||
const url = `${env.BACKEND_URL}/bookings?${urlParams.toString()}`;
|
|
||||||
|
|
||||||
const response = await fetch(url);
|
|
||||||
|
|
||||||
if (response.status === 401) throw new Error("Unauthorized");
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (response.status !== 200) {
|
|
||||||
return { error: data.message };
|
|
||||||
}
|
|
||||||
|
|
||||||
const bookings: Booking[] = data.bookings
|
|
||||||
.filter((booking: Booking) => {
|
|
||||||
const notCancelled = booking.status !== BOOKING_STATUS.CANCELLED;
|
|
||||||
|
|
||||||
return notCancelled;
|
|
||||||
})
|
|
||||||
.map(({ endTime, eventTypeId, id, startTime, status, title }: Booking) => ({
|
|
||||||
endTime,
|
|
||||||
eventTypeId,
|
|
||||||
id,
|
|
||||||
startTime,
|
|
||||||
status,
|
|
||||||
title,
|
|
||||||
}));
|
|
||||||
|
|
||||||
return bookings;
|
|
||||||
};
|
|
||||||
|
|
||||||
const getBookingsTool = (apiKey: string, userId: number) => {
|
|
||||||
return new DynamicStructuredTool({
|
|
||||||
description: "Get bookings for the primary user between two dates.",
|
|
||||||
func: async ({ from, to }) => {
|
|
||||||
return JSON.stringify(await fetchBookings({ apiKey, userId, from, to }));
|
|
||||||
},
|
|
||||||
name: "getBookings",
|
|
||||||
schema: z.object({
|
|
||||||
from: z.string().describe("ISO 8601 datetime string"),
|
|
||||||
to: z.string().describe("ISO 8601 datetime string"),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export default getBookingsTool;
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
import { env } from "../env.mjs";
|
|
||||||
import type { EventType } from "../types/eventType";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetches event types by user ID.
|
|
||||||
*/
|
|
||||||
export const fetchEventTypes = async ({ apiKey, userId }: { apiKey: string; userId?: number }) => {
|
|
||||||
const params: Record<string, string> = {
|
|
||||||
apiKey,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (userId) {
|
|
||||||
params["userId"] = userId.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
const urlParams = new URLSearchParams(params);
|
|
||||||
|
|
||||||
const url = `${env.BACKEND_URL}/event-types?${urlParams.toString()}`;
|
|
||||||
|
|
||||||
const response = await fetch(url);
|
|
||||||
|
|
||||||
if (response.status === 401) throw new Error("Unauthorized");
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (response.status !== 200) {
|
|
||||||
return { error: data.message };
|
|
||||||
}
|
|
||||||
|
|
||||||
return data.event_types.map((eventType: EventType) => ({
|
|
||||||
id: eventType.id,
|
|
||||||
slug: eventType.slug,
|
|
||||||
length: eventType.length,
|
|
||||||
title: eventType.title,
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
const getEventTypesTool = (apiKey: string) => {
|
|
||||||
return new DynamicStructuredTool({
|
|
||||||
description: "Get a user's event type IDs. Usually necessary to book a meeting.",
|
|
||||||
func: async ({ userId }) => {
|
|
||||||
return JSON.stringify(
|
|
||||||
await fetchEventTypes({
|
|
||||||
apiKey,
|
|
||||||
userId,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
},
|
|
||||||
name: "getEventTypes",
|
|
||||||
schema: z.object({
|
|
||||||
userId: z.number().optional().describe("The user ID. Defaults to the primary user's ID."),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export default getEventTypesTool;
|
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
import { env } from "~/src/env.mjs";
|
|
||||||
import type { User, UserList } from "~/src/types/user";
|
|
||||||
import sendEmail from "~/src/utils/sendEmail";
|
|
||||||
|
|
||||||
export const sendBookingEmail = async ({
|
|
||||||
user,
|
|
||||||
agentEmail,
|
|
||||||
subject,
|
|
||||||
to,
|
|
||||||
message,
|
|
||||||
eventTypeSlug,
|
|
||||||
slots,
|
|
||||||
date,
|
|
||||||
}: {
|
|
||||||
apiKey: string;
|
|
||||||
user: User;
|
|
||||||
users: UserList;
|
|
||||||
agentEmail: string;
|
|
||||||
subject: string;
|
|
||||||
to: string;
|
|
||||||
message: string;
|
|
||||||
eventTypeSlug: string;
|
|
||||||
slots?: {
|
|
||||||
time: string;
|
|
||||||
text: string;
|
|
||||||
}[];
|
|
||||||
date: {
|
|
||||||
date: string;
|
|
||||||
text: string;
|
|
||||||
};
|
|
||||||
}) => {
|
|
||||||
// const url = `${env.FRONTEND_URL}/${user.username}/${eventTypeSlug}?date=${date}`;
|
|
||||||
const timeUrls = slots?.map(({ time, text }) => {
|
|
||||||
return {
|
|
||||||
url: `${env.FRONTEND_URL}/${user.username}/${eventTypeSlug}?slot=${time}`,
|
|
||||||
text,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const dateUrl = {
|
|
||||||
url: `${env.FRONTEND_URL}/${user.username}/${eventTypeSlug}?date=${date.date}`,
|
|
||||||
text: date.text,
|
|
||||||
};
|
|
||||||
|
|
||||||
await sendEmail({
|
|
||||||
subject,
|
|
||||||
to,
|
|
||||||
cc: user.email,
|
|
||||||
from: agentEmail,
|
|
||||||
text: message
|
|
||||||
.split("[[[Slots]]]")
|
|
||||||
.join(timeUrls?.map(({ url, text }) => `${text}: ${url}`).join("\n"))
|
|
||||||
.split("[[[Link]]]")
|
|
||||||
.join(`${dateUrl.text}: ${dateUrl.url}`),
|
|
||||||
html: message
|
|
||||||
.split("\n")
|
|
||||||
.join("<br>")
|
|
||||||
.split("[[[Slots]]]")
|
|
||||||
.join(timeUrls?.map(({ url, text }) => `<a href="${url}">${text}</a>`).join("<br>"))
|
|
||||||
.split("[[[Link]]]")
|
|
||||||
.join(`<a href="${dateUrl.url}">${dateUrl.text}</a>`),
|
|
||||||
});
|
|
||||||
|
|
||||||
return "Booking link sent";
|
|
||||||
};
|
|
||||||
|
|
||||||
const sendBookingEmailTool = (apiKey: string, user: User, users: UserList, agentEmail: string) => {
|
|
||||||
return new DynamicStructuredTool({
|
|
||||||
description:
|
|
||||||
"Send a booking link via email. Useful for scheduling with non cal users. Be confident, suggesting a good date/time with a fallback to a link to select a date/time.",
|
|
||||||
func: async ({ message, subject, to, eventTypeSlug, slots, date }) => {
|
|
||||||
return JSON.stringify(
|
|
||||||
await sendBookingEmail({
|
|
||||||
apiKey,
|
|
||||||
user,
|
|
||||||
users,
|
|
||||||
agentEmail,
|
|
||||||
subject,
|
|
||||||
to,
|
|
||||||
message,
|
|
||||||
eventTypeSlug,
|
|
||||||
slots,
|
|
||||||
date,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
},
|
|
||||||
name: "sendBookingEmail",
|
|
||||||
|
|
||||||
schema: z.object({
|
|
||||||
message: z
|
|
||||||
.string()
|
|
||||||
.describe(
|
|
||||||
"A polite and professional email with an intro and signature at the end. Specify you are the AI booking assistant of the primary user. Use [[[Slots]]] and a fallback [[[Link]]] to inject good times and 'see all times' into messages"
|
|
||||||
),
|
|
||||||
subject: z.string(),
|
|
||||||
to: z
|
|
||||||
.string()
|
|
||||||
.describe("email address to send the booking link to. Primary user is automatically CC'd"),
|
|
||||||
eventTypeSlug: z.string().describe("the slug of the event type to book"),
|
|
||||||
slots: z
|
|
||||||
.array(
|
|
||||||
z.object({
|
|
||||||
time: z.string().describe("YYYY-MM-DDTHH:mm in UTC"),
|
|
||||||
text: z.string().describe("minimum readable label. Ex. 4pm."),
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.optional()
|
|
||||||
.describe("Time slots the external user can click"),
|
|
||||||
date: z
|
|
||||||
.object({
|
|
||||||
date: z.string().describe("YYYY-MM-DD"),
|
|
||||||
text: z.string().describe('"See all times" or similar'),
|
|
||||||
})
|
|
||||||
.describe(
|
|
||||||
"A booking link that allows the external user to select a date / time. Should be a fallback to time slots"
|
|
||||||
),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export default sendBookingEmailTool;
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
import { env } from "../env.mjs";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Edits a booking for a user by booking ID with new times, title, description, or status.
|
|
||||||
*/
|
|
||||||
const editBooking = async ({
|
|
||||||
apiKey,
|
|
||||||
userId,
|
|
||||||
id,
|
|
||||||
startTime, // In the docs it says start, but it's startTime: https://cal.com/docs/enterprise-features/api/api-reference/bookings#edit-an-existing-booking.
|
|
||||||
endTime, // Same here: it says end but it's endTime.
|
|
||||||
title,
|
|
||||||
description,
|
|
||||||
status,
|
|
||||||
}: {
|
|
||||||
apiKey: string;
|
|
||||||
userId: number;
|
|
||||||
id: string;
|
|
||||||
startTime?: string;
|
|
||||||
endTime?: string;
|
|
||||||
title?: string;
|
|
||||||
description?: string;
|
|
||||||
status?: string;
|
|
||||||
}): Promise<string | { error: string }> => {
|
|
||||||
const params = {
|
|
||||||
apiKey,
|
|
||||||
userId: userId.toString(),
|
|
||||||
};
|
|
||||||
const urlParams = new URLSearchParams(params);
|
|
||||||
|
|
||||||
const url = `${env.BACKEND_URL}/bookings/${id}?${urlParams.toString()}`;
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
body: JSON.stringify({ description, endTime, startTime, status, title }),
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
method: "PATCH",
|
|
||||||
});
|
|
||||||
|
|
||||||
// Let GPT handle this. This will happen when wrong booking id is used.
|
|
||||||
// if (response.status === 401) throw new Error("Unauthorized");
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (response.status !== 200) {
|
|
||||||
return { error: data.message };
|
|
||||||
}
|
|
||||||
|
|
||||||
return "Booking edited";
|
|
||||||
};
|
|
||||||
|
|
||||||
const editBookingTool = (apiKey: string, userId: number) => {
|
|
||||||
return new DynamicStructuredTool({
|
|
||||||
description: "Edit a booking",
|
|
||||||
func: async ({ description, endTime, id, startTime, status, title }) => {
|
|
||||||
return JSON.stringify(
|
|
||||||
await editBooking({
|
|
||||||
apiKey,
|
|
||||||
userId,
|
|
||||||
description,
|
|
||||||
endTime,
|
|
||||||
id,
|
|
||||||
startTime,
|
|
||||||
status,
|
|
||||||
title,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
},
|
|
||||||
name: "editBooking",
|
|
||||||
schema: z.object({
|
|
||||||
description: z.string().optional(),
|
|
||||||
endTime: z.string().optional(),
|
|
||||||
id: z.string(),
|
|
||||||
startTime: z.string().optional(),
|
|
||||||
status: z.string().optional(),
|
|
||||||
title: z.string().optional(),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export default editBookingTool;
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
export type Availability = {
|
|
||||||
busy: {
|
|
||||||
start: string;
|
|
||||||
end: string;
|
|
||||||
title?: string;
|
|
||||||
}[];
|
|
||||||
timeZone: string;
|
|
||||||
dateRanges: {
|
|
||||||
start: string;
|
|
||||||
end: string;
|
|
||||||
}[];
|
|
||||||
workingHours: {
|
|
||||||
days: number[];
|
|
||||||
startTime: number;
|
|
||||||
endTime: number;
|
|
||||||
userId: number;
|
|
||||||
}[];
|
|
||||||
dateOverrides: {
|
|
||||||
date: string;
|
|
||||||
startTime: number;
|
|
||||||
endTime: number;
|
|
||||||
userId: number;
|
|
||||||
};
|
|
||||||
currentSeats: number;
|
|
||||||
};
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
export enum BOOKING_STATUS {
|
|
||||||
ACCEPTED = "ACCEPTED",
|
|
||||||
PENDING = "PENDING",
|
|
||||||
CANCELLED = "CANCELLED",
|
|
||||||
REJECTED = "REJECTED",
|
|
||||||
}
|
|
||||||
|
|
||||||
export type Booking = {
|
|
||||||
id: number;
|
|
||||||
userId: number;
|
|
||||||
description: string | null;
|
|
||||||
eventTypeId: number;
|
|
||||||
uid: string;
|
|
||||||
title: string;
|
|
||||||
startTime: string;
|
|
||||||
endTime: string;
|
|
||||||
attendees: { email: string; name: string; timeZone: string; locale: string }[] | null;
|
|
||||||
user: { email: string; name: string; timeZone: string; locale: string }[] | null;
|
|
||||||
payment: { id: number; success: boolean; paymentOption: string }[];
|
|
||||||
metadata: object | null;
|
|
||||||
status: BOOKING_STATUS;
|
|
||||||
responses: { email: string; name: string; location: string } | null;
|
|
||||||
};
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
export type EventType = {
|
|
||||||
id: number;
|
|
||||||
title: string;
|
|
||||||
length: number;
|
|
||||||
metadata: object;
|
|
||||||
slug: string;
|
|
||||||
hosts: {
|
|
||||||
userId: number;
|
|
||||||
isFixed: boolean;
|
|
||||||
}[];
|
|
||||||
hidden: boolean;
|
|
||||||
// ...
|
|
||||||
};
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
import type { EventType } from "./eventType";
|
|
||||||
import type { WorkingHours } from "./workingHours";
|
|
||||||
|
|
||||||
export type User = {
|
|
||||||
id: number;
|
|
||||||
email: string;
|
|
||||||
username: string;
|
|
||||||
timeZone: string;
|
|
||||||
eventTypes: EventType[];
|
|
||||||
workingHours: WorkingHours[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type UserList = {
|
|
||||||
id?: number;
|
|
||||||
email?: string;
|
|
||||||
username?: string;
|
|
||||||
type: "fromUsername" | "fromEmail";
|
|
||||||
}[];
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
export type WorkingHours = {
|
|
||||||
days: number[];
|
|
||||||
startTime: number;
|
|
||||||
endTime: number;
|
|
||||||
};
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
import { ChatPromptTemplate } from "@langchain/core/prompts";
|
|
||||||
import { ChatOpenAI } from "@langchain/openai";
|
|
||||||
import { AgentExecutor, createOpenAIFunctionsAgent } from "langchain/agents";
|
|
||||||
|
|
||||||
import { env } from "../env.mjs";
|
|
||||||
import createBookingIfAvailable from "../tools/createBooking";
|
|
||||||
import deleteBooking from "../tools/deleteBooking";
|
|
||||||
import getAvailability from "../tools/getAvailability";
|
|
||||||
import getBookings from "../tools/getBookings";
|
|
||||||
import sendBookingEmail from "../tools/sendBookingEmail";
|
|
||||||
import updateBooking from "../tools/updateBooking";
|
|
||||||
import type { EventType } from "../types/eventType";
|
|
||||||
import type { User, UserList } from "../types/user";
|
|
||||||
import type { WorkingHours } from "../types/workingHours";
|
|
||||||
import now from "./now";
|
|
||||||
|
|
||||||
const gptModel = "gpt-4-0125-preview";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Core of the Cal.ai booking agent: a LangChain Agent Executor.
|
|
||||||
* Uses a toolchain to book meetings, list available slots, etc.
|
|
||||||
* Uses OpenAI functions to better enforce JSON-parsable output from the LLM.
|
|
||||||
*/
|
|
||||||
const agent = async (
|
|
||||||
input: string,
|
|
||||||
user: User,
|
|
||||||
users: UserList,
|
|
||||||
apiKey: string,
|
|
||||||
userId: number,
|
|
||||||
agentEmail: string
|
|
||||||
) => {
|
|
||||||
const tools = [
|
|
||||||
// getEventTypes(apiKey),
|
|
||||||
getAvailability(apiKey),
|
|
||||||
getBookings(apiKey, userId),
|
|
||||||
createBookingIfAvailable(apiKey, userId, users),
|
|
||||||
updateBooking(apiKey, userId),
|
|
||||||
deleteBooking(apiKey),
|
|
||||||
sendBookingEmail(apiKey, user, users, agentEmail),
|
|
||||||
];
|
|
||||||
|
|
||||||
const model = new ChatOpenAI({
|
|
||||||
modelName: gptModel,
|
|
||||||
openAIApiKey: env.OPENAI_API_KEY,
|
|
||||||
temperature: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initialize the agent executor with arguments.
|
|
||||||
*/
|
|
||||||
const prompt =
|
|
||||||
ChatPromptTemplate.fromTemplate(`You are Cal.ai - a bleeding edge scheduling assistant that interfaces via email.
|
|
||||||
Make sure your final answers are definitive, complete and well formatted.
|
|
||||||
Sometimes, tools return errors. In this case, try to handle the error intelligently or ask the user for more information.
|
|
||||||
Tools will always handle times in UTC, but times sent to users should be formatted per that user's timezone.
|
|
||||||
In responses to users, always summarize necessary context and open the door to follow ups. For example "I have booked your chat with @username for 3pm on Wednesday, December 20th, 2023 EST. Please let me know if you need to reschedule."
|
|
||||||
If you can't find a referenced user, ask the user for their email or @username. Make sure to specify that usernames require the @username format. Users don't know other users' userIds.
|
|
||||||
|
|
||||||
The primary user's id is: ${userId}
|
|
||||||
The primary user's username is: ${user.username}
|
|
||||||
The current time in the primary user's timezone is: ${now(user.timeZone, {
|
|
||||||
weekday: "long",
|
|
||||||
year: "numeric",
|
|
||||||
month: "long",
|
|
||||||
day: "numeric",
|
|
||||||
hour: "numeric",
|
|
||||||
minute: "numeric",
|
|
||||||
})}
|
|
||||||
The primary user's time zone is: ${user.timeZone}
|
|
||||||
The primary user's event types are: ${user.eventTypes
|
|
||||||
.map((e: EventType) => `ID: ${e.id}, Slug: ${e.slug}, Title: ${e.title}, Length: ${e.length};`)
|
|
||||||
.join("\n")}
|
|
||||||
The primary user's working hours are: ${user.workingHours
|
|
||||||
.map(
|
|
||||||
(w: WorkingHours) =>
|
|
||||||
`Days: ${w.days.join(", ")}, Start Time (minutes in UTC): ${
|
|
||||||
w.startTime
|
|
||||||
}, End Time (minutes in UTC): ${w.endTime};`
|
|
||||||
)
|
|
||||||
.join("\n")}
|
|
||||||
${
|
|
||||||
users.length
|
|
||||||
? `The email references the following @usernames and emails: ${users
|
|
||||||
.map(
|
|
||||||
(u) =>
|
|
||||||
`${
|
|
||||||
(u.id ? `, id: ${u.id}` : "id: (non user)") +
|
|
||||||
(u.username
|
|
||||||
? u.type === "fromUsername"
|
|
||||||
? `, username: @${u.username}`
|
|
||||||
: ", username: REDACTED"
|
|
||||||
: ", (no username)") +
|
|
||||||
(u.email
|
|
||||||
? u.type === "fromEmail"
|
|
||||||
? `, email: ${u.email}`
|
|
||||||
: ", email: REDACTED"
|
|
||||||
: ", (no email)")
|
|
||||||
};`
|
|
||||||
)
|
|
||||||
.join("\n")}`
|
|
||||||
: ""
|
|
||||||
}`);
|
|
||||||
const agent = await createOpenAIFunctionsAgent({
|
|
||||||
llm: model,
|
|
||||||
prompt,
|
|
||||||
tools,
|
|
||||||
});
|
|
||||||
|
|
||||||
const executor = new AgentExecutor({
|
|
||||||
agent,
|
|
||||||
tools,
|
|
||||||
returnIntermediateSteps: env.NODE_ENV === "development",
|
|
||||||
verbose: env.NODE_ENV === "development",
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await executor.invoke({ input });
|
|
||||||
const { output } = result;
|
|
||||||
|
|
||||||
return output;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default agent;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export const context = { apiKey: "", userId: "" };
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
import prisma from "@calcom/prisma";
|
|
||||||
|
|
||||||
import type { UserList } from "../types/user";
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Extracts usernames (@Example) and emails ([email protected]) from a string
|
|
||||||
*/
|
|
||||||
export const extractUsers = async (text: string) => {
|
|
||||||
const usernames = text
|
|
||||||
.match(/(?<![a-zA-Z0-9_.])@[a-zA-Z0-9_]+/g)
|
|
||||||
?.map((username) => username.slice(1).toLowerCase());
|
|
||||||
const emails = text
|
|
||||||
.match(/[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+/g)
|
|
||||||
?.map((email) => email.toLowerCase());
|
|
||||||
|
|
||||||
const dbUsersFromUsernames = usernames
|
|
||||||
? await prisma.user.findMany({
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
username: true,
|
|
||||||
email: true,
|
|
||||||
},
|
|
||||||
where: {
|
|
||||||
username: {
|
|
||||||
in: usernames,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
: [];
|
|
||||||
|
|
||||||
const usersFromUsernames = usernames
|
|
||||||
? usernames.map((username) => {
|
|
||||||
const user = dbUsersFromUsernames.find((u) => u.username === username);
|
|
||||||
return user
|
|
||||||
? {
|
|
||||||
username,
|
|
||||||
id: user.id,
|
|
||||||
email: user.email,
|
|
||||||
type: "fromUsername",
|
|
||||||
}
|
|
||||||
: {
|
|
||||||
username,
|
|
||||||
id: null,
|
|
||||||
email: null,
|
|
||||||
type: "fromUsername",
|
|
||||||
};
|
|
||||||
})
|
|
||||||
: [];
|
|
||||||
|
|
||||||
const dbUsersFromEmails = emails
|
|
||||||
? await prisma.user.findMany({
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
email: true,
|
|
||||||
username: true,
|
|
||||||
},
|
|
||||||
where: {
|
|
||||||
email: {
|
|
||||||
in: emails,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
: [];
|
|
||||||
|
|
||||||
const usersFromEmails = emails
|
|
||||||
? emails.map((email) => {
|
|
||||||
const user = dbUsersFromEmails.find((u) => u.email === email);
|
|
||||||
return user
|
|
||||||
? {
|
|
||||||
email,
|
|
||||||
id: user.id,
|
|
||||||
username: user.username,
|
|
||||||
type: "fromEmail",
|
|
||||||
}
|
|
||||||
: {
|
|
||||||
email,
|
|
||||||
id: null,
|
|
||||||
username: null,
|
|
||||||
type: "fromEmail",
|
|
||||||
};
|
|
||||||
})
|
|
||||||
: [];
|
|
||||||
|
|
||||||
return [...usersFromUsernames, ...usersFromEmails] as UserList;
|
|
||||||
};
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import type { NextRequest } from "next/server";
|
|
||||||
|
|
||||||
const getHostFromHeaders = (headers: NextRequest["headers"]): string => {
|
|
||||||
return `https://${headers.get("host")}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default getHostFromHeaders;
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
export default function now(timeZone: string, options: Intl.DateTimeFormatOptions = {}) {
|
|
||||||
return new Date().toLocaleString("en-US", {
|
|
||||||
timeZone,
|
|
||||||
...options,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
import mail from "@sendgrid/mail";
|
|
||||||
|
|
||||||
const sendgridAPIKey = process.env.SENDGRID_API_KEY as string;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Simply send an email by address, subject, and body.
|
|
||||||
*/
|
|
||||||
const send = async ({
|
|
||||||
subject,
|
|
||||||
to,
|
|
||||||
cc,
|
|
||||||
from,
|
|
||||||
text,
|
|
||||||
html,
|
|
||||||
}: {
|
|
||||||
subject: string;
|
|
||||||
to: string | string[];
|
|
||||||
cc?: string | string[];
|
|
||||||
from: string;
|
|
||||||
text: string;
|
|
||||||
html?: string;
|
|
||||||
}): Promise<boolean> => {
|
|
||||||
mail.setApiKey(sendgridAPIKey);
|
|
||||||
|
|
||||||
const msg = {
|
|
||||||
to,
|
|
||||||
cc,
|
|
||||||
from: {
|
|
||||||
email: from,
|
|
||||||
name: "Cal.ai",
|
|
||||||
},
|
|
||||||
text,
|
|
||||||
html,
|
|
||||||
subject,
|
|
||||||
};
|
|
||||||
|
|
||||||
const res = await mail.send(msg);
|
|
||||||
const success = !!res;
|
|
||||||
|
|
||||||
return success;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default send;
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import type { NextRequest } from "next/server";
|
|
||||||
|
|
||||||
import { env } from "../env.mjs";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verifies that the request contains the correct parse key.
|
|
||||||
* env.PARSE_KEY must be configured as a query param in the sendgrid inbound parse settings.
|
|
||||||
*/
|
|
||||||
export const verifyParseKey = (url: NextRequest["url"]) => {
|
|
||||||
const verified = new URL(url).searchParams.get("parseKey") === env.PARSE_KEY;
|
|
||||||
|
|
||||||
return verified;
|
|
||||||
};
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
{
|
|
||||||
"extends": "@calcom/tsconfig/nextjs.json",
|
|
||||||
"compilerOptions": {
|
|
||||||
"strict": true,
|
|
||||||
"jsx": "preserve",
|
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
|
||||||
"~/*": ["*"]
|
|
||||||
},
|
|
||||||
"plugins": [
|
|
||||||
{
|
|
||||||
"name": "next"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"include": [
|
|
||||||
"next-env.d.ts",
|
|
||||||
"**/*.ts",
|
|
||||||
"**/*.tsx",
|
|
||||||
".next/types/**/*.ts",
|
|
||||||
"../../packages/types/window.d.ts"
|
|
||||||
],
|
|
||||||
"exclude": ["node_modules"]
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { NextMiddleware } from "next-api-middleware";
|
import type { NextMiddleware } from "next-api-middleware";
|
||||||
|
|
||||||
import LicenseKeyService from "@calcom/ee/common/server/LicenseKeyService";
|
import { LicenseKeySingleton } from "@calcom/ee/common/server/LicenseKeyService";
|
||||||
import { hashAPIKey } from "@calcom/features/ee/api-keys/lib/apiKeys";
|
import { hashAPIKey } from "@calcom/features/ee/api-keys/lib/apiKeys";
|
||||||
import { IS_PRODUCTION } from "@calcom/lib/constants";
|
import { IS_PRODUCTION } from "@calcom/lib/constants";
|
||||||
import prisma from "@calcom/prisma";
|
import prisma from "@calcom/prisma";
|
||||||
@@ -18,7 +18,7 @@ export const dateNotInPast = function (date: Date) {
|
|||||||
|
|
||||||
// This verifies the apiKey and sets the user if it is valid.
|
// This verifies the apiKey and sets the user if it is valid.
|
||||||
export const verifyApiKey: NextMiddleware = async (req, res, next) => {
|
export const verifyApiKey: NextMiddleware = async (req, res, next) => {
|
||||||
const licenseKeyService = await LicenseKeyService.create();
|
const licenseKeyService = await LicenseKeySingleton.getInstance();
|
||||||
const hasValidLicense = await licenseKeyService.checkLicense();
|
const hasValidLicense = await licenseKeyService.checkLicense();
|
||||||
|
|
||||||
if (!hasValidLicense && IS_PRODUCTION) {
|
if (!hasValidLicense && IS_PRODUCTION) {
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ export const isAdminGuard = async (req: NextApiRequest) => {
|
|||||||
accepted: true,
|
accepted: true,
|
||||||
team: {
|
team: {
|
||||||
isOrganization: true,
|
isOrganization: true,
|
||||||
|
organizationSettings: {
|
||||||
|
isAdminAPIEnabled: true,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
OR: [{ role: MembershipRole.OWNER }, { role: MembershipRole.ADMIN }],
|
OR: [{ role: MembershipRole.OWNER }, { role: MembershipRole.ADMIN }],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { _BookingModel as Booking, _AttendeeModel, _UserModel, _PaymentModel } from "@calcom/prisma/zod";
|
import { _AttendeeModel, _BookingModel as Booking, _PaymentModel, _UserModel } from "@calcom/prisma/zod";
|
||||||
import { extendedBookingCreateBody, iso8601 } from "@calcom/prisma/zod-utils";
|
import { extendedBookingCreateBody, iso8601 } from "@calcom/prisma/zod-utils";
|
||||||
|
|
||||||
import { schemaQueryUserId } from "./shared/queryUserId";
|
import { schemaQueryUserId } from "./shared/queryUserId";
|
||||||
@@ -23,8 +23,11 @@ export const schemaBookingGetParams = z.object({
|
|||||||
dateTo: iso8601.optional(),
|
dateTo: iso8601.optional(),
|
||||||
order: z.enum(["asc", "desc"]).default("asc"),
|
order: z.enum(["asc", "desc"]).default("asc"),
|
||||||
sortBy: z.enum(["createdAt", "updatedAt"]).optional(),
|
sortBy: z.enum(["createdAt", "updatedAt"]).optional(),
|
||||||
|
status: z.enum(["upcoming"]).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export type Status = z.infer<typeof schemaBookingGetParams>["status"];
|
||||||
|
|
||||||
const schemaBookingEditParams = z
|
const schemaBookingEditParams = z
|
||||||
.object({
|
.object({
|
||||||
title: z.string().optional(),
|
title: z.string().optional(),
|
||||||
|
|||||||
@@ -63,6 +63,25 @@ import { schemaQuerySingleOrMultipleUserIds } from "~/lib/validations/shared/que
|
|||||||
* schema:
|
* schema:
|
||||||
* type: string
|
* type: string
|
||||||
* enum: [createdAt, updatedAt]
|
* enum: [createdAt, updatedAt]
|
||||||
|
* - in: query
|
||||||
|
* name: status
|
||||||
|
* required: false
|
||||||
|
* schema:
|
||||||
|
* type: string
|
||||||
|
* enum: [upcoming]
|
||||||
|
* description: Filter bookings by status, it will overwrite dateFrom and dateTo filters
|
||||||
|
* - in: query
|
||||||
|
* name: dateFrom
|
||||||
|
* required: false
|
||||||
|
* schema:
|
||||||
|
* type: string
|
||||||
|
* description: ISO 8601 date string to filter bookings by start time
|
||||||
|
* - in: query
|
||||||
|
* name: dateTo
|
||||||
|
* required: false
|
||||||
|
* schema:
|
||||||
|
* type: string
|
||||||
|
* description: ISO 8601 date string to filter bookings by end time
|
||||||
* operationId: listBookings
|
* operationId: listBookings
|
||||||
* tags:
|
* tags:
|
||||||
* - bookings
|
* - bookings
|
||||||
@@ -130,6 +149,7 @@ type GetAdminArgsType = {
|
|||||||
requestedUserIds: number[];
|
requestedUserIds: number[];
|
||||||
userId: number;
|
userId: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs the WHERE clause for Prisma booking findMany operation.
|
* Constructs the WHERE clause for Prisma booking findMany operation.
|
||||||
*
|
*
|
||||||
@@ -148,7 +168,9 @@ function buildWhereClause(
|
|||||||
) {
|
) {
|
||||||
const filterByAttendeeEmails = attendeeEmails.length > 0;
|
const filterByAttendeeEmails = attendeeEmails.length > 0;
|
||||||
const userFilter = userIds.length > 0 ? { userId: { in: userIds } } : !!userId ? { userId } : {};
|
const userFilter = userIds.length > 0 ? { userId: { in: userIds } } : !!userId ? { userId } : {};
|
||||||
|
|
||||||
let whereClause = {};
|
let whereClause = {};
|
||||||
|
|
||||||
if (filterByAttendeeEmails) {
|
if (filterByAttendeeEmails) {
|
||||||
whereClause = {
|
whereClause = {
|
||||||
AND: [
|
AND: [
|
||||||
@@ -177,9 +199,7 @@ function buildWhereClause(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return whereClause;
|
||||||
...whereClause,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function handler(req: NextApiRequest) {
|
export async function handler(req: NextApiRequest) {
|
||||||
@@ -189,7 +209,7 @@ export async function handler(req: NextApiRequest) {
|
|||||||
isOrganizationOwnerOrAdmin,
|
isOrganizationOwnerOrAdmin,
|
||||||
pagination: { take, skip },
|
pagination: { take, skip },
|
||||||
} = req;
|
} = req;
|
||||||
const { dateFrom, dateTo, order, sortBy } = schemaBookingGetParams.parse(req.query);
|
const { dateFrom, dateTo, order, sortBy, status } = schemaBookingGetParams.parse(req.query);
|
||||||
|
|
||||||
const args: Prisma.BookingFindManyArgs = {};
|
const args: Prisma.BookingFindManyArgs = {};
|
||||||
if (req.query.take && req.query.page) {
|
if (req.query.take && req.query.page) {
|
||||||
@@ -275,6 +295,19 @@ export async function handler(req: NextApiRequest) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (status) {
|
||||||
|
switch (status) {
|
||||||
|
case "upcoming":
|
||||||
|
args.where = {
|
||||||
|
...args.where,
|
||||||
|
startTime: { gte: new Date().toISOString() },
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new HttpError({ message: "Invalid status", statusCode: 400 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const data = await prisma.booking.findMany(args);
|
const data = await prisma.booking.findMany(args);
|
||||||
return { bookings: data.map((booking) => schemaBookingReadPublic.parse(booking)) };
|
return { bookings: data.map((booking) => schemaBookingReadPublic.parse(booking)) };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -278,8 +278,8 @@ async function postHandler(req: NextApiRequest) {
|
|||||||
|
|
||||||
let data: Prisma.EventTypeCreateArgs["data"] = {
|
let data: Prisma.EventTypeCreateArgs["data"] = {
|
||||||
...parsedBody,
|
...parsedBody,
|
||||||
userId,
|
userId: !!parsedBody.teamId ? null : userId,
|
||||||
users: { connect: { id: userId } },
|
users: !!parsedBody.teamId ? undefined : { connect: { id: userId } },
|
||||||
bookingLimits: bookingLimits === null ? Prisma.DbNull : bookingLimits,
|
bookingLimits: bookingLimits === null ? Prisma.DbNull : bookingLimits,
|
||||||
durationLimits: durationLimits === null ? Prisma.DbNull : durationLimits,
|
durationLimits: durationLimits === null ? Prisma.DbNull : durationLimits,
|
||||||
};
|
};
|
||||||
@@ -291,7 +291,7 @@ async function postHandler(req: NextApiRequest) {
|
|||||||
await checkUserMembership(req);
|
await checkUserMembership(req);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isSystemWideAdmin && parsedBody.userId) {
|
if (isSystemWideAdmin && parsedBody.userId && !parsedBody.teamId) {
|
||||||
data = { ...parsedBody, users: { connect: { id: parsedBody.userId } } };
|
data = { ...parsedBody, users: { connect: { id: parsedBody.userId } } };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -105,4 +105,87 @@ describe("GET /api/bookings", async () => {
|
|||||||
expect(responseData.bookings.find((b) => b.id === proUserBooking.id)).toBeUndefined();
|
expect(responseData.bookings.find((b) => b.id === proUserBooking.id)).toBeUndefined();
|
||||||
expect(groupedUsers.size).toBeGreaterThanOrEqual(2);
|
expect(groupedUsers.size).toBeGreaterThanOrEqual(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("Upcoming bookings feature", () => {
|
||||||
|
it("Returns only upcoming bookings when status=upcoming for regular user", async () => {
|
||||||
|
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||||
|
method: "GET",
|
||||||
|
query: {
|
||||||
|
status: "upcoming",
|
||||||
|
},
|
||||||
|
pagination: DefaultPagination,
|
||||||
|
});
|
||||||
|
|
||||||
|
req.userId = proUser.id;
|
||||||
|
|
||||||
|
const responseData = await handler(req);
|
||||||
|
responseData.bookings.forEach((booking) => {
|
||||||
|
expect(new Date(booking.startTime).getTime()).toBeGreaterThanOrEqual(new Date().getTime());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Returns all bookings when status not specified for regular user", async () => {
|
||||||
|
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||||
|
method: "GET",
|
||||||
|
pagination: DefaultPagination,
|
||||||
|
});
|
||||||
|
|
||||||
|
req.userId = proUser.id;
|
||||||
|
|
||||||
|
const responseData = await handler(req);
|
||||||
|
expect(responseData.bookings.find((b) => b.id === proUserBooking.id)).toBeDefined();
|
||||||
|
|
||||||
|
const { req: req2 } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||||
|
method: "GET",
|
||||||
|
pagination: DefaultPagination,
|
||||||
|
});
|
||||||
|
|
||||||
|
req2.userId = proUser.id;
|
||||||
|
|
||||||
|
const responseData2 = await handler(req2);
|
||||||
|
expect(responseData2.bookings.find((b) => b.id === proUserBooking.id)).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Returns only upcoming bookings when status=upcoming for system-wide admin", async () => {
|
||||||
|
const adminUser = await prisma.user.findFirstOrThrow({ where: { email: "[email protected]" } });
|
||||||
|
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||||
|
method: "GET",
|
||||||
|
query: {
|
||||||
|
status: "upcoming",
|
||||||
|
},
|
||||||
|
pagination: {
|
||||||
|
take: 100,
|
||||||
|
skip: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
req.isSystemWideAdmin = true;
|
||||||
|
req.userId = adminUser.id;
|
||||||
|
|
||||||
|
const responseData = await handler(req);
|
||||||
|
responseData.bookings.forEach((booking) => {
|
||||||
|
console.log(booking);
|
||||||
|
expect(new Date(booking.startTime).getTime()).toBeGreaterThanOrEqual(new Date().getTime());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Returns only upcoming bookings when status=upcoming for org admin", async () => {
|
||||||
|
const adminUser = await prisma.user.findFirstOrThrow({ where: { email: "[email protected]" } });
|
||||||
|
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||||
|
method: "GET",
|
||||||
|
query: {
|
||||||
|
status: "upcoming",
|
||||||
|
},
|
||||||
|
pagination: DefaultPagination,
|
||||||
|
});
|
||||||
|
|
||||||
|
req.userId = adminUser.id;
|
||||||
|
req.isOrganizationOwnerOrAdmin = true;
|
||||||
|
|
||||||
|
const responseData = await handler(req);
|
||||||
|
responseData.bookings.forEach((booking) => {
|
||||||
|
expect(new Date(booking.startTime).getTime()).toBeGreaterThanOrEqual(new Date().getTime());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
import prismaMock from "../../../../../../tests/libs/__mocks__/prismaMock";
|
||||||
|
|
||||||
|
import type { Request, Response } from "express";
|
||||||
|
import type { NextApiRequest, NextApiResponse } from "next";
|
||||||
|
import { createMocks } from "node-mocks-http";
|
||||||
|
import { describe, expect, test, vi, afterEach } from "vitest";
|
||||||
|
|
||||||
|
import { buildEventType } from "@calcom/lib/test/builder";
|
||||||
|
|
||||||
|
import handler from "../../../pages/api/event-types/_post";
|
||||||
|
import checkParentEventOwnership from "../../../pages/api/event-types/_utils/checkParentEventOwnership";
|
||||||
|
import checkTeamEventEditPermission from "../../../pages/api/event-types/_utils/checkTeamEventEditPermission";
|
||||||
|
import checkUserMembership from "../../../pages/api/event-types/_utils/checkUserMembership";
|
||||||
|
import ensureOnlyMembersAsHosts from "../../../pages/api/event-types/_utils/ensureOnlyMembersAsHosts";
|
||||||
|
import { canUserAccessTeamWithRole } from "../../../pages/api/teams/[teamId]/_auth-middleware";
|
||||||
|
|
||||||
|
type CustomNextApiRequest = NextApiRequest & Request;
|
||||||
|
type CustomNextApiResponse = NextApiResponse & Response;
|
||||||
|
|
||||||
|
const adminUserId = 1;
|
||||||
|
const memberUserId = 10;
|
||||||
|
|
||||||
|
vi.mock("../../../pages/api/teams/[teamId]/_auth-middleware", () => ({
|
||||||
|
canUserAccessTeamWithRole: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../../pages/api/event-types/_utils/checkUserMembership", () => ({
|
||||||
|
default: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("../../../pages/api/event-types/_utils/checkParentEventOwnership", () => ({
|
||||||
|
default: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("../../../pages/api/event-types/_utils/checkTeamEventEditPermission", () => ({
|
||||||
|
default: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("../../../pages/api/event-types/_utils/ensureOnlyMembersAsHosts", () => ({
|
||||||
|
default: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.resetAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("POST /api/event-types", () => {
|
||||||
|
describe("Errors", () => {
|
||||||
|
test("should throw 401 if a non-admin user tries to create an event type with userId", async () => {
|
||||||
|
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
title: "Tennis class",
|
||||||
|
slug: "tennis-class-{{$guid}}",
|
||||||
|
length: 60,
|
||||||
|
hidden: true,
|
||||||
|
userId: memberUserId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await handler(req, res);
|
||||||
|
|
||||||
|
expect(res.statusCode).toBe(401);
|
||||||
|
expect(JSON.parse(res._getData()).message).toBe("ADMIN required for `userId`");
|
||||||
|
});
|
||||||
|
test("should throw 401 if not system-wide admin and user cannot access teamId with required roles", async () => {
|
||||||
|
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
title: "Tennis class",
|
||||||
|
slug: "tennis-class-{{$guid}}",
|
||||||
|
length: 60,
|
||||||
|
hidden: true,
|
||||||
|
teamId: 9999,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
req.userId = memberUserId;
|
||||||
|
vi.mocked(canUserAccessTeamWithRole).mockImplementationOnce(async () => false);
|
||||||
|
|
||||||
|
await handler(req, res);
|
||||||
|
|
||||||
|
expect(res.statusCode).toBe(401);
|
||||||
|
expect(JSON.parse(res._getData()).message).toBe("ADMIN required for `teamId`");
|
||||||
|
});
|
||||||
|
test("should throw 400 if system-wide admin but neither userId nor teamId provided", async () => {
|
||||||
|
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
title: "Tennis class",
|
||||||
|
slug: "tennis-class-{{$guid}}",
|
||||||
|
length: 60,
|
||||||
|
hidden: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
req.isSystemWideAdmin = true;
|
||||||
|
await handler(req, res);
|
||||||
|
|
||||||
|
expect(res.statusCode).toBe(400);
|
||||||
|
expect(JSON.parse(res._getData()).message).toBe("`userId` or `teamId` required");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Success", () => {
|
||||||
|
test("should call checkParentEventOwnership and checkUserMembership if parentId is present", async () => {
|
||||||
|
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
title: "Tennis class",
|
||||||
|
slug: "tennis-class-{{$guid}}",
|
||||||
|
length: 60,
|
||||||
|
hidden: true,
|
||||||
|
userId: memberUserId,
|
||||||
|
parentId: 9999,
|
||||||
|
teamId: 9999,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
req.isSystemWideAdmin = true;
|
||||||
|
req.userId = adminUserId;
|
||||||
|
|
||||||
|
vi.mocked(canUserAccessTeamWithRole).mockImplementationOnce(async () => false);
|
||||||
|
|
||||||
|
await handler(req, res);
|
||||||
|
expect(checkParentEventOwnership).toHaveBeenCalled();
|
||||||
|
expect(checkUserMembership).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should create event type successfully if all conditions are met", async () => {
|
||||||
|
const eventTypeTest = buildEventType();
|
||||||
|
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
title: "test title",
|
||||||
|
slug: "test-slug",
|
||||||
|
length: 60,
|
||||||
|
hidden: true,
|
||||||
|
userId: memberUserId,
|
||||||
|
parentId: 9999,
|
||||||
|
teamId: 9999,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
req.isSystemWideAdmin = true;
|
||||||
|
req.userId = adminUserId;
|
||||||
|
|
||||||
|
vi.mocked(canUserAccessTeamWithRole).mockImplementationOnce(async () => true);
|
||||||
|
vi.mocked(checkParentEventOwnership).mockImplementationOnce(async () => undefined);
|
||||||
|
vi.mocked(checkUserMembership).mockImplementationOnce(async () => undefined);
|
||||||
|
vi.mocked(checkTeamEventEditPermission).mockImplementationOnce(async () => undefined);
|
||||||
|
vi.mocked(ensureOnlyMembersAsHosts).mockImplementationOnce(async () => undefined);
|
||||||
|
|
||||||
|
prismaMock.eventType.create.mockResolvedValue(eventTypeTest);
|
||||||
|
|
||||||
|
await handler(req, res);
|
||||||
|
const data = JSON.parse(res._getData());
|
||||||
|
|
||||||
|
expect(prismaMock.eventType.create).toHaveBeenCalledTimes(1);
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
expect(data.message).toBe("Event type created successfully");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -58,7 +58,7 @@ describe("isAdmin guard", () => {
|
|||||||
expect(scope).toBe(ScopeOfAdmin.SystemWide);
|
expect(scope).toBe(ScopeOfAdmin.SystemWide);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("Returns org-wide admin when user is set as such", async () => {
|
it("Returns org-wide admin when user is set as such & admin API access is granted", async () => {
|
||||||
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: {},
|
body: {},
|
||||||
@@ -67,10 +67,21 @@ describe("isAdmin guard", () => {
|
|||||||
const adminUser = await prisma.user.findFirstOrThrow({ where: { email: "[email protected]" } });
|
const adminUser = await prisma.user.findFirstOrThrow({ where: { email: "[email protected]" } });
|
||||||
|
|
||||||
req.userId = adminUser.id;
|
req.userId = adminUser.id;
|
||||||
|
|
||||||
const { isAdmin, scope } = await isAdminGuard(req);
|
const { isAdmin, scope } = await isAdminGuard(req);
|
||||||
|
|
||||||
expect(isAdmin).toBe(true);
|
expect(isAdmin).toBe(true);
|
||||||
expect(scope).toBe(ScopeOfAdmin.OrgOwnerOrAdmin);
|
expect(scope).toBe(ScopeOfAdmin.OrgOwnerOrAdmin);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("Returns no admin when user is set as org admin but admin API access is revoked", async () => {
|
||||||
|
const { req } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
|
||||||
|
method: "POST",
|
||||||
|
body: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
const adminUser = await prisma.user.findFirstOrThrow({ where: { email: "[email protected]" } });
|
||||||
|
|
||||||
|
req.userId = adminUser.id;
|
||||||
|
const { isAdmin } = await isAdminGuard(req);
|
||||||
|
expect(isAdmin).toBe(false);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
|
<a href="http://nestjs.com/" target="blank"><img src="https://github.com/user-attachments/assets/ce7c2ecf-6097-469a-8512-c846a9fb665d" height="200" alt="Nest Logo" /></a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
|
|
||||||
## Description
|
## Description
|
||||||
|
|
||||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
Cal.com is using the [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
|||||||
@@ -25,8 +25,8 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@calcom/platform-constants": "*",
|
"@calcom/platform-constants": "*",
|
||||||
|
"@calcom/platform-libraries": "npm:@calcom/[email protected]",
|
||||||
"@calcom/platform-libraries-0.0.2": "npm:@calcom/[email protected]",
|
"@calcom/platform-libraries-0.0.2": "npm:@calcom/[email protected]",
|
||||||
"@calcom/platform-libraries-0.0.22": "npm:@calcom/[email protected]",
|
|
||||||
"@calcom/platform-types": "*",
|
"@calcom/platform-types": "*",
|
||||||
"@calcom/platform-utils": "*",
|
"@calcom/platform-utils": "*",
|
||||||
"@calcom/prisma": "*",
|
"@calcom/prisma": "*",
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { bootstrap } from "@/app";
|
import { bootstrap } from "@/app";
|
||||||
import { AppModule } from "@/app.module";
|
import { AppModule } from "@/app.module";
|
||||||
|
import { CreateBookingInput } from "@/ee/bookings/inputs/create-booking.input";
|
||||||
import { GetBookingOutput } from "@/ee/bookings/outputs/get-booking.output";
|
import { GetBookingOutput } from "@/ee/bookings/outputs/get-booking.output";
|
||||||
import { GetBookingsOutput } from "@/ee/bookings/outputs/get-bookings.output";
|
import { GetBookingsOutput } from "@/ee/bookings/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";
|
||||||
@@ -19,7 +20,7 @@ import { UserRepositoryFixture } from "test/fixtures/repository/users.repository
|
|||||||
import { withApiAuth } from "test/utils/withApiAuth";
|
import { withApiAuth } from "test/utils/withApiAuth";
|
||||||
|
|
||||||
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
|
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
|
||||||
import { handleNewBooking } from "@calcom/platform-libraries-0.0.22";
|
import { handleNewBooking } from "@calcom/platform-libraries";
|
||||||
import { ApiSuccessResponse, ApiResponse } from "@calcom/platform-types";
|
import { ApiSuccessResponse, ApiResponse } from "@calcom/platform-types";
|
||||||
|
|
||||||
describe("Bookings Endpoints", () => {
|
describe("Bookings Endpoints", () => {
|
||||||
@@ -90,7 +91,10 @@ describe("Bookings Endpoints", () => {
|
|||||||
const bookingTimeZone = "Europe/London";
|
const bookingTimeZone = "Europe/London";
|
||||||
const bookingLanguage = "en";
|
const bookingLanguage = "en";
|
||||||
const bookingHashedLink = "";
|
const bookingHashedLink = "";
|
||||||
const bookingMetadata = {};
|
const bookingMetadata = {
|
||||||
|
timeFormat: "12",
|
||||||
|
meetingType: "organizer-phone",
|
||||||
|
};
|
||||||
const bookingResponses = {
|
const bookingResponses = {
|
||||||
name: "tester",
|
name: "tester",
|
||||||
email: "[email protected]",
|
email: "[email protected]",
|
||||||
@@ -102,7 +106,7 @@ describe("Bookings Endpoints", () => {
|
|||||||
guests: [],
|
guests: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
const body = {
|
const body: CreateBookingInput = {
|
||||||
start: bookingStart,
|
start: bookingStart,
|
||||||
end: bookingEnd,
|
end: bookingEnd,
|
||||||
eventTypeId: bookingEventTypeId,
|
eventTypeId: bookingEventTypeId,
|
||||||
@@ -135,6 +139,64 @@ describe("Bookings Endpoints", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("should reschedule a booking", () => {
|
||||||
|
it("should reschedule with updated start time, end time & metadata", async () => {
|
||||||
|
const newBookingStart = "2040-05-21T12:30:00.000Z";
|
||||||
|
const newBookingEnd = "2040-05-21T13:30:00.000Z";
|
||||||
|
const bookingEventTypeId = eventTypeId;
|
||||||
|
const bookingTimeZone = "Europe/London";
|
||||||
|
const bookingLanguage = "en";
|
||||||
|
const bookingHashedLink = "";
|
||||||
|
const newBookingMetadata = {
|
||||||
|
timeFormat: "24",
|
||||||
|
meetingType: "attendee-phone",
|
||||||
|
};
|
||||||
|
const bookingResponses = {
|
||||||
|
name: "tester",
|
||||||
|
email: "[email protected]",
|
||||||
|
location: {
|
||||||
|
value: "link",
|
||||||
|
optionValue: "",
|
||||||
|
},
|
||||||
|
notes: "test",
|
||||||
|
guests: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const body: CreateBookingInput = {
|
||||||
|
rescheduleUid: createdBooking.uid,
|
||||||
|
start: newBookingStart,
|
||||||
|
end: newBookingEnd,
|
||||||
|
eventTypeId: bookingEventTypeId,
|
||||||
|
timeZone: bookingTimeZone,
|
||||||
|
language: bookingLanguage,
|
||||||
|
metadata: newBookingMetadata,
|
||||||
|
hashedLink: bookingHashedLink,
|
||||||
|
responses: bookingResponses,
|
||||||
|
};
|
||||||
|
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.post("/v2/bookings")
|
||||||
|
.send(body)
|
||||||
|
.expect(201)
|
||||||
|
.then(async (response) => {
|
||||||
|
const responseBody: ApiSuccessResponse<Awaited<ReturnType<typeof handleNewBooking>>> =
|
||||||
|
response.body;
|
||||||
|
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||||
|
expect(responseBody.data).toBeDefined();
|
||||||
|
expect(responseBody.data.userPrimaryEmail).toBeDefined();
|
||||||
|
expect(responseBody.data.userPrimaryEmail).toEqual(userEmail);
|
||||||
|
expect(responseBody.data.id).toBeDefined();
|
||||||
|
expect(responseBody.data.uid).toBeDefined();
|
||||||
|
expect(responseBody.data.startTime).toEqual(newBookingStart);
|
||||||
|
expect(responseBody.data.eventTypeId).toEqual(bookingEventTypeId);
|
||||||
|
expect(responseBody.data.user.timeZone).toEqual(bookingTimeZone);
|
||||||
|
expect(responseBody.data.metadata).toEqual(newBookingMetadata);
|
||||||
|
|
||||||
|
createdBooking = responseBody.data;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it("should get bookings", async () => {
|
it("should get bookings", async () => {
|
||||||
return request(app.getHttpServer())
|
return request(app.getHttpServer())
|
||||||
.get("/v2/bookings?filters[status]=upcoming")
|
.get("/v2/bookings?filters[status]=upcoming")
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ import {
|
|||||||
getBookingInfo,
|
getBookingInfo,
|
||||||
handleCancelBooking,
|
handleCancelBooking,
|
||||||
getBookingForReschedule,
|
getBookingForReschedule,
|
||||||
} from "@calcom/platform-libraries-0.0.22";
|
} from "@calcom/platform-libraries";
|
||||||
import { GetBookingsInput, CancelBookingInput, Status } from "@calcom/platform-types";
|
import { GetBookingsInput, CancelBookingInput, Status } from "@calcom/platform-types";
|
||||||
import { ApiResponse } from "@calcom/platform-types";
|
import { ApiResponse } from "@calcom/platform-types";
|
||||||
import { PrismaClient } from "@calcom/prisma";
|
import { PrismaClient } from "@calcom/prisma";
|
||||||
@@ -211,6 +211,7 @@ export class BookingsController {
|
|||||||
@Permissions([BOOKING_WRITE])
|
@Permissions([BOOKING_WRITE])
|
||||||
@UseGuards(ApiAuthGuard)
|
@UseGuards(ApiAuthGuard)
|
||||||
async markNoShow(
|
async markNoShow(
|
||||||
|
@GetUser("id") userId: number,
|
||||||
@Body() body: MarkNoShowInput,
|
@Body() body: MarkNoShowInput,
|
||||||
@Param("bookingUid") bookingUid: string
|
@Param("bookingUid") bookingUid: string
|
||||||
): Promise<MarkNoShowOutput> {
|
): Promise<MarkNoShowOutput> {
|
||||||
@@ -219,6 +220,7 @@ export class BookingsController {
|
|||||||
bookingUid: bookingUid,
|
bookingUid: bookingUid,
|
||||||
attendees: body.attendees,
|
attendees: body.attendees,
|
||||||
noShowHost: body.noShowHost,
|
noShowHost: body.noShowHost,
|
||||||
|
userId,
|
||||||
});
|
});
|
||||||
|
|
||||||
return { status: SUCCESS_STATUS, data: markNoShowResponse };
|
return { status: SUCCESS_STATUS, data: markNoShowResponse };
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { CreateBookingInput } from "@/ee/bookings/inputs/create-booking.input";
|
import { CreateBookingInput } from "@/ee/bookings/inputs/create-booking.input";
|
||||||
import { IsBoolean, IsNumber, IsOptional } from "class-validator";
|
import { IsBoolean, IsNumber, IsOptional } from "class-validator";
|
||||||
|
|
||||||
import type { AppsStatus } from "@calcom/platform-libraries-0.0.22";
|
import type { AppsStatus } from "@calcom/platform-libraries";
|
||||||
|
|
||||||
export class CreateRecurringBookingInput extends CreateBookingInput {
|
export class CreateRecurringBookingInput extends CreateBookingInput {
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
|
|||||||
@@ -20,10 +20,6 @@ class HandleMarkNoShowData {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
noShowHost?: boolean;
|
noShowHost?: boolean;
|
||||||
|
|
||||||
@IsString()
|
|
||||||
@IsOptional()
|
|
||||||
messageKey?: string;
|
|
||||||
|
|
||||||
@ValidateNested()
|
@ValidateNested()
|
||||||
@Type(() => Attendee)
|
@Type(() => Attendee)
|
||||||
@IsArray()
|
@IsArray()
|
||||||
|
|||||||
@@ -105,7 +105,7 @@ class Primary {
|
|||||||
credentialId!: number;
|
credentialId!: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
class Calendar {
|
export class Calendar {
|
||||||
@IsEmail()
|
@IsEmail()
|
||||||
externalId!: string;
|
externalId!: string;
|
||||||
|
|
||||||
@@ -135,7 +135,7 @@ class Calendar {
|
|||||||
credentialId!: number;
|
credentialId!: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
class ConnectedCalendar {
|
export class ConnectedCalendar {
|
||||||
@ValidateNested()
|
@ValidateNested()
|
||||||
@IsObject()
|
@IsObject()
|
||||||
integration!: Integration;
|
integration!: Integration;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { BadRequestException, UnauthorizedException } from "@nestjs/common";
|
|||||||
import { Injectable } from "@nestjs/common";
|
import { Injectable } from "@nestjs/common";
|
||||||
|
|
||||||
import { SUCCESS_STATUS, APPLE_CALENDAR_TYPE, APPLE_CALENDAR_ID } from "@calcom/platform-constants";
|
import { SUCCESS_STATUS, APPLE_CALENDAR_TYPE, APPLE_CALENDAR_ID } from "@calcom/platform-constants";
|
||||||
import { symmetricEncrypt, CalendarService } from "@calcom/platform-libraries-0.0.22";
|
import { symmetricEncrypt, CalendarService } from "@calcom/platform-libraries";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AppleCalendarService implements CredentialSyncCalendarApp {
|
export class AppleCalendarService implements CredentialSyncCalendarApp {
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import { User } from "@prisma/client";
|
|||||||
import { DateTime } from "luxon";
|
import { DateTime } from "luxon";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { getConnectedDestinationCalendars, getBusyCalendarTimes } from "@calcom/platform-libraries-0.0.22";
|
import { getConnectedDestinationCalendars, getBusyCalendarTimes } from "@calcom/platform-libraries";
|
||||||
import { Calendar } from "@calcom/platform-types";
|
import { Calendar } from "@calcom/platform-types";
|
||||||
import { PrismaClient } from "@calcom/prisma";
|
import { PrismaClient } from "@calcom/prisma";
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -35,7 +35,7 @@ import {
|
|||||||
EventTypesPublic,
|
EventTypesPublic,
|
||||||
eventTypeBookingFields,
|
eventTypeBookingFields,
|
||||||
eventTypeLocations,
|
eventTypeLocations,
|
||||||
} from "@calcom/platform-libraries-0.0.22";
|
} from "@calcom/platform-libraries";
|
||||||
import { ApiSuccessResponse } from "@calcom/platform-types";
|
import { ApiSuccessResponse } from "@calcom/platform-types";
|
||||||
|
|
||||||
describe("Event types Endpoints", () => {
|
describe("Event types Endpoints", () => {
|
||||||
|
|||||||
-1
@@ -40,7 +40,6 @@ import { ApiTags as DocsTags } from "@nestjs/swagger";
|
|||||||
|
|
||||||
import { EVENT_TYPE_READ, EVENT_TYPE_WRITE, SUCCESS_STATUS } from "@calcom/platform-constants";
|
import { EVENT_TYPE_READ, EVENT_TYPE_WRITE, SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||||
import { getPublicEvent, getEventTypesByViewer } from "@calcom/platform-libraries-0.0.2";
|
import { getPublicEvent, getEventTypesByViewer } from "@calcom/platform-libraries-0.0.2";
|
||||||
|
|
||||||
import { PrismaClient } from "@calcom/prisma";
|
import { PrismaClient } from "@calcom/prisma";
|
||||||
|
|
||||||
@Controller({
|
@Controller({
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
|||||||
import { UserWithProfile } from "@/modules/users/users.repository";
|
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||||
import { Injectable } from "@nestjs/common";
|
import { Injectable } from "@nestjs/common";
|
||||||
|
|
||||||
import { getEventTypeById } from "@calcom/platform-libraries-0.0.22";
|
import { getEventTypeById } from "@calcom/platform-libraries";
|
||||||
import type { PrismaClient } from "@calcom/prisma";
|
import type { PrismaClient } from "@calcom/prisma";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@ import {
|
|||||||
updateEventType,
|
updateEventType,
|
||||||
EventTypesPublic,
|
EventTypesPublic,
|
||||||
getEventTypesPublic,
|
getEventTypesPublic,
|
||||||
} from "@calcom/platform-libraries-0.0.22";
|
} from "@calcom/platform-libraries";
|
||||||
import { EventType } from "@calcom/prisma/client";
|
import { EventType } from "@calcom/prisma/client";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
|
|||||||
+327
@@ -1,5 +1,6 @@
|
|||||||
import { bootstrap } from "@/app";
|
import { bootstrap } from "@/app";
|
||||||
import { AppModule } from "@/app.module";
|
import { AppModule } from "@/app.module";
|
||||||
|
import { CreateEventTypeInput_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/inputs/create-event-type.input";
|
||||||
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 { HttpExceptionFilter } from "@/filters/http-exception.filter";
|
import { HttpExceptionFilter } from "@/filters/http-exception.filter";
|
||||||
import { PrismaExceptionFilter } from "@/filters/prisma-exception.filter";
|
import { PrismaExceptionFilter } from "@/filters/prisma-exception.filter";
|
||||||
@@ -25,6 +26,7 @@ import {
|
|||||||
EventTypeOutput_2024_06_14,
|
EventTypeOutput_2024_06_14,
|
||||||
UpdateEventTypeInput_2024_06_14,
|
UpdateEventTypeInput_2024_06_14,
|
||||||
} from "@calcom/platform-types";
|
} from "@calcom/platform-types";
|
||||||
|
import { SchedulingType } from "@calcom/prisma/enums";
|
||||||
|
|
||||||
describe("Event types Endpoints", () => {
|
describe("Event types Endpoints", () => {
|
||||||
describe("Not authenticated", () => {
|
describe("Not authenticated", () => {
|
||||||
@@ -380,4 +382,329 @@ describe("Event types Endpoints", () => {
|
|||||||
await app.close();
|
await app.close();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("Handle legacy event-types booking fields", () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
|
||||||
|
let oAuthClient: PlatformOAuthClient;
|
||||||
|
let organization: Team;
|
||||||
|
let userRepositoryFixture: UserRepositoryFixture;
|
||||||
|
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
|
||||||
|
let teamRepositoryFixture: TeamRepositoryFixture;
|
||||||
|
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
|
||||||
|
|
||||||
|
const userEmail = "[email protected]";
|
||||||
|
const name = "bob-the-builder";
|
||||||
|
const username = name;
|
||||||
|
let user: User;
|
||||||
|
let legacyEventTypeId1: number;
|
||||||
|
let legacyEventTypeId2: number;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleRef = await withApiAuth(
|
||||||
|
userEmail,
|
||||||
|
Test.createTestingModule({
|
||||||
|
providers: [PrismaExceptionFilter, HttpExceptionFilter],
|
||||||
|
imports: [AppModule, UsersModule, EventTypesModule_2024_06_14, TokensModule],
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.overrideGuard(PermissionsGuard)
|
||||||
|
.useValue({
|
||||||
|
canActivate: () => true,
|
||||||
|
})
|
||||||
|
.compile();
|
||||||
|
|
||||||
|
app = moduleRef.createNestApplication();
|
||||||
|
bootstrap(app as NestExpressApplication);
|
||||||
|
|
||||||
|
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
||||||
|
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||||
|
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
||||||
|
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
|
||||||
|
|
||||||
|
organization = await teamRepositoryFixture.create({ name: "organization" });
|
||||||
|
oAuthClient = await createOAuthClient(organization.id);
|
||||||
|
user = await userRepositoryFixture.create({
|
||||||
|
email: userEmail,
|
||||||
|
name,
|
||||||
|
username,
|
||||||
|
});
|
||||||
|
|
||||||
|
await app.init();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function createOAuthClient(organizationId: number) {
|
||||||
|
const data = {
|
||||||
|
logo: "logo-url",
|
||||||
|
name: "name",
|
||||||
|
redirectUris: ["redirect-uri"],
|
||||||
|
permissions: 32,
|
||||||
|
};
|
||||||
|
const secret = "secret";
|
||||||
|
|
||||||
|
const client = await oauthClientRepositoryFixture.create(organizationId, data, secret);
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
it("should be defined", () => {
|
||||||
|
expect(oauthClientRepositoryFixture).toBeDefined();
|
||||||
|
expect(userRepositoryFixture).toBeDefined();
|
||||||
|
expect(oAuthClient).toBeDefined();
|
||||||
|
expect(user).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should not allow creating an event type with input of event-types version 2024_04_15", async () => {
|
||||||
|
const body: CreateEventTypeInput_2024_04_15 = {
|
||||||
|
title: "Coding class",
|
||||||
|
slug: "coding-class",
|
||||||
|
description: "Let's learn how to code like a pro.",
|
||||||
|
length: 60,
|
||||||
|
locations: [{ type: "integrations:daily" }],
|
||||||
|
};
|
||||||
|
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.post("/api/v2/event-types")
|
||||||
|
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_14)
|
||||||
|
.send(body)
|
||||||
|
.expect(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return empty bookingFields if system fields are the only one in database", async () => {
|
||||||
|
const legacyEventTypeInput = {
|
||||||
|
title: "legacy event type",
|
||||||
|
description: "legacy event type description",
|
||||||
|
length: 40,
|
||||||
|
hidden: false,
|
||||||
|
slug: "legacy-event-type",
|
||||||
|
locations: [],
|
||||||
|
schedulingType: SchedulingType.ROUND_ROBIN,
|
||||||
|
bookingFields: [
|
||||||
|
{
|
||||||
|
name: "name",
|
||||||
|
type: "name",
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system",
|
||||||
|
required: true,
|
||||||
|
defaultLabel: "your_name",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "email",
|
||||||
|
type: "email",
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system",
|
||||||
|
required: true,
|
||||||
|
defaultLabel: "email_address",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "location",
|
||||||
|
type: "radioInput",
|
||||||
|
label: "",
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system",
|
||||||
|
required: false,
|
||||||
|
placeholder: "",
|
||||||
|
defaultLabel: "location",
|
||||||
|
getOptionsAt: "locations",
|
||||||
|
optionsInputs: {
|
||||||
|
phone: { type: "phone", required: true, placeholder: "" },
|
||||||
|
attendeeInPerson: { type: "address", required: true, placeholder: "" },
|
||||||
|
},
|
||||||
|
hideWhenJustOneOption: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "title",
|
||||||
|
type: "text",
|
||||||
|
hidden: true,
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system-but-optional",
|
||||||
|
required: true,
|
||||||
|
defaultLabel: "what_is_this_meeting_about",
|
||||||
|
defaultPlaceholder: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "notes",
|
||||||
|
type: "textarea",
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system-but-optional",
|
||||||
|
required: false,
|
||||||
|
defaultLabel: "additional_notes",
|
||||||
|
defaultPlaceholder: "share_additional_notes",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "guests",
|
||||||
|
type: "multiemail",
|
||||||
|
hidden: false,
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system-but-optional",
|
||||||
|
required: false,
|
||||||
|
defaultLabel: "additional_guests",
|
||||||
|
defaultPlaceholder: "email",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "rescheduleReason",
|
||||||
|
type: "textarea",
|
||||||
|
views: [{ id: "reschedule", label: "Reschedule View" }],
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system-but-optional",
|
||||||
|
required: false,
|
||||||
|
defaultLabel: "reason_for_reschedule",
|
||||||
|
defaultPlaceholder: "reschedule_placeholder",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const legacyEventType = await eventTypesRepositoryFixture.create(legacyEventTypeInput, user.id);
|
||||||
|
legacyEventTypeId1 = legacyEventType.id;
|
||||||
|
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get(`/api/v2/event-types/${legacyEventTypeId1}`)
|
||||||
|
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_14)
|
||||||
|
.expect(200)
|
||||||
|
.then(async (response) => {
|
||||||
|
const responseBody: ApiSuccessResponse<EventTypeOutput_2024_06_14> = response.body;
|
||||||
|
const fetchedEventType = responseBody.data;
|
||||||
|
expect(fetchedEventType.bookingFields).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return user created bookingFields among system fields in the database", async () => {
|
||||||
|
const userDefinedBookingField = {
|
||||||
|
name: "team",
|
||||||
|
type: "textarea",
|
||||||
|
label: "your team",
|
||||||
|
sources: [
|
||||||
|
{
|
||||||
|
id: "user",
|
||||||
|
type: "user",
|
||||||
|
label: "User",
|
||||||
|
fieldRequired: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
editable: "user",
|
||||||
|
required: true,
|
||||||
|
placeholder: "FC Barcelona",
|
||||||
|
};
|
||||||
|
|
||||||
|
const legacyEventTypeInput = {
|
||||||
|
title: "legacy event type two",
|
||||||
|
description: "legacy event type description two",
|
||||||
|
length: 40,
|
||||||
|
hidden: false,
|
||||||
|
slug: "legacy-event-type-two",
|
||||||
|
locations: [],
|
||||||
|
schedulingType: SchedulingType.ROUND_ROBIN,
|
||||||
|
bookingFields: [
|
||||||
|
userDefinedBookingField,
|
||||||
|
{
|
||||||
|
name: "name",
|
||||||
|
type: "name",
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system",
|
||||||
|
required: true,
|
||||||
|
defaultLabel: "your_name",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "email",
|
||||||
|
type: "email",
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system",
|
||||||
|
required: true,
|
||||||
|
defaultLabel: "email_address",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "location",
|
||||||
|
type: "radioInput",
|
||||||
|
label: "",
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system",
|
||||||
|
required: false,
|
||||||
|
placeholder: "",
|
||||||
|
defaultLabel: "location",
|
||||||
|
getOptionsAt: "locations",
|
||||||
|
optionsInputs: {
|
||||||
|
phone: { type: "phone", required: true, placeholder: "" },
|
||||||
|
attendeeInPerson: { type: "address", required: true, placeholder: "" },
|
||||||
|
},
|
||||||
|
hideWhenJustOneOption: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "title",
|
||||||
|
type: "text",
|
||||||
|
hidden: true,
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system-but-optional",
|
||||||
|
required: true,
|
||||||
|
defaultLabel: "what_is_this_meeting_about",
|
||||||
|
defaultPlaceholder: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "notes",
|
||||||
|
type: "textarea",
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system-but-optional",
|
||||||
|
required: false,
|
||||||
|
defaultLabel: "additional_notes",
|
||||||
|
defaultPlaceholder: "share_additional_notes",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "guests",
|
||||||
|
type: "multiemail",
|
||||||
|
hidden: false,
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system-but-optional",
|
||||||
|
required: false,
|
||||||
|
defaultLabel: "additional_guests",
|
||||||
|
defaultPlaceholder: "email",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "rescheduleReason",
|
||||||
|
type: "textarea",
|
||||||
|
views: [{ id: "reschedule", label: "Reschedule View" }],
|
||||||
|
sources: [{ id: "default", type: "default", label: "Default" }],
|
||||||
|
editable: "system-but-optional",
|
||||||
|
required: false,
|
||||||
|
defaultLabel: "reason_for_reschedule",
|
||||||
|
defaultPlaceholder: "reschedule_placeholder",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const legacyEventType = await eventTypesRepositoryFixture.create(legacyEventTypeInput, user.id);
|
||||||
|
legacyEventTypeId2 = legacyEventType.id;
|
||||||
|
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get(`/api/v2/event-types/${legacyEventTypeId2}`)
|
||||||
|
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_14)
|
||||||
|
.expect(200)
|
||||||
|
.then(async (response) => {
|
||||||
|
const responseBody: ApiSuccessResponse<EventTypeOutput_2024_06_14> = response.body;
|
||||||
|
const fetchedEventType = responseBody.data;
|
||||||
|
|
||||||
|
expect(fetchedEventType.bookingFields).toEqual([
|
||||||
|
{
|
||||||
|
type: userDefinedBookingField.type,
|
||||||
|
slug: userDefinedBookingField.name,
|
||||||
|
label: userDefinedBookingField.label,
|
||||||
|
required: userDefinedBookingField.required,
|
||||||
|
placeholder: userDefinedBookingField.placeholder,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await oauthClientRepositoryFixture.delete(oAuthClient.id);
|
||||||
|
await teamRepositoryFixture.delete(organization.id);
|
||||||
|
try {
|
||||||
|
await eventTypesRepositoryFixture.delete(legacyEventTypeId1);
|
||||||
|
await eventTypesRepositoryFixture.delete(legacyEventTypeId2);
|
||||||
|
} catch (e) {
|
||||||
|
// Event type might have been deleted by the test
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await userRepositoryFixture.delete(user.id);
|
||||||
|
} catch (e) {
|
||||||
|
// User might have been deleted by the test
|
||||||
|
}
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
getEventTypeById,
|
getEventTypeById,
|
||||||
transformApiEventTypeBookingFields,
|
transformApiEventTypeBookingFields,
|
||||||
transformApiEventTypeLocations,
|
transformApiEventTypeLocations,
|
||||||
} from "@calcom/platform-libraries-0.0.22";
|
} from "@calcom/platform-libraries";
|
||||||
import { CreateEventTypeInput_2024_06_14 } from "@calcom/platform-types";
|
import { CreateEventTypeInput_2024_06_14 } from "@calcom/platform-types";
|
||||||
import type { PrismaClient } from "@calcom/prisma";
|
import type { PrismaClient } from "@calcom/prisma";
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -10,9 +10,9 @@ import { UsersService } from "@/modules/users/services/users.service";
|
|||||||
import { UserWithProfile, UsersRepository } from "@/modules/users/users.repository";
|
import { UserWithProfile, UsersRepository } from "@/modules/users/users.repository";
|
||||||
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
|
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
|
||||||
|
|
||||||
import { createEventType, updateEventType } from "@calcom/platform-libraries-0.0.22";
|
import { createEventType, updateEventType } from "@calcom/platform-libraries";
|
||||||
import { getEventTypesPublic, EventTypesPublic } from "@calcom/platform-libraries-0.0.22";
|
import { getEventTypesPublic, EventTypesPublic } from "@calcom/platform-libraries";
|
||||||
import { dynamicEvent } from "@calcom/platform-libraries-0.0.22";
|
import { dynamicEvent } from "@calcom/platform-libraries";
|
||||||
import {
|
import {
|
||||||
CreateEventTypeInput_2024_06_14,
|
CreateEventTypeInput_2024_06_14,
|
||||||
UpdateEventTypeInput_2024_06_14,
|
UpdateEventTypeInput_2024_06_14,
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ import { Injectable } from "@nestjs/common";
|
|||||||
import {
|
import {
|
||||||
transformApiEventTypeBookingFields,
|
transformApiEventTypeBookingFields,
|
||||||
transformApiEventTypeLocations,
|
transformApiEventTypeLocations,
|
||||||
} from "@calcom/platform-libraries-0.0.22";
|
} from "@calcom/platform-libraries";
|
||||||
import { CreateEventTypeInput_2024_06_14, UpdateEventTypeInput_2024_06_14 } from "@calcom/platform-types";
|
import { CreateEventTypeInput_2024_06_14, UpdateEventTypeInput_2024_06_14 } from "@calcom/platform-types";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
|
|||||||
+9
-4
@@ -9,7 +9,9 @@ import {
|
|||||||
parseRecurringEvent,
|
parseRecurringEvent,
|
||||||
TransformedLocationsSchema,
|
TransformedLocationsSchema,
|
||||||
BookingFieldsSchema,
|
BookingFieldsSchema,
|
||||||
} from "@calcom/platform-libraries-0.0.22";
|
SystemField,
|
||||||
|
UserField,
|
||||||
|
} from "@calcom/platform-libraries";
|
||||||
|
|
||||||
type EventTypeRelations = { users: User[]; schedule: Schedule | null };
|
type EventTypeRelations = { users: User[]; schedule: Schedule | null };
|
||||||
type DatabaseEventType = EventType & EventTypeRelations;
|
type DatabaseEventType = EventType & EventTypeRelations;
|
||||||
@@ -72,7 +74,9 @@ export class OutputEventTypesService_2024_06_14 {
|
|||||||
} = databaseEventType;
|
} = databaseEventType;
|
||||||
|
|
||||||
const locations = this.transformLocations(databaseEventType.locations);
|
const locations = this.transformLocations(databaseEventType.locations);
|
||||||
const bookingFields = this.transformBookingFields(databaseEventType.bookingFields);
|
const bookingFields = databaseEventType.bookingFields
|
||||||
|
? this.transformBookingFields(BookingFieldsSchema.parse(databaseEventType.bookingFields))
|
||||||
|
: [];
|
||||||
const recurringEvent = this.transformRecurringEvent(databaseEventType.recurringEvent);
|
const recurringEvent = this.transformRecurringEvent(databaseEventType.recurringEvent);
|
||||||
const metadata = this.transformMetadata(databaseEventType.metadata) || {};
|
const metadata = this.transformMetadata(databaseEventType.metadata) || {};
|
||||||
const users = this.transformUsers(databaseEventType.users);
|
const users = this.transformUsers(databaseEventType.users);
|
||||||
@@ -113,9 +117,10 @@ export class OutputEventTypesService_2024_06_14 {
|
|||||||
return getResponseEventTypeLocations(TransformedLocationsSchema.parse(locations));
|
return getResponseEventTypeLocations(TransformedLocationsSchema.parse(locations));
|
||||||
}
|
}
|
||||||
|
|
||||||
transformBookingFields(inputBookingFields: any) {
|
transformBookingFields(inputBookingFields: (SystemField | UserField)[] | null) {
|
||||||
if (!inputBookingFields) return [];
|
if (!inputBookingFields) return [];
|
||||||
return getResponseEventTypeBookingFields(BookingFieldsSchema.parse(inputBookingFields));
|
const userFields = inputBookingFields.filter((field) => field.editable === "user") as UserField[];
|
||||||
|
return getResponseEventTypeBookingFields(userFields);
|
||||||
}
|
}
|
||||||
|
|
||||||
transformRecurringEvent(recurringEvent: any) {
|
transformRecurringEvent(recurringEvent: any) {
|
||||||
|
|||||||
@@ -9,8 +9,10 @@ import { UsersModule } from "@/modules/users/users.module";
|
|||||||
import { INestApplication } from "@nestjs/common";
|
import { INestApplication } from "@nestjs/common";
|
||||||
import { NestExpressApplication } from "@nestjs/platform-express";
|
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||||
import { Test } from "@nestjs/testing";
|
import { Test } from "@nestjs/testing";
|
||||||
import { User } from "@prisma/client";
|
import { User, Team } from "@prisma/client";
|
||||||
import * as request from "supertest";
|
import * as request from "supertest";
|
||||||
|
import { OrganizationRepositoryFixture } from "test/fixtures/repository/organization.repository.fixture";
|
||||||
|
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
|
||||||
import { SchedulesRepositoryFixture } from "test/fixtures/repository/schedules.repository.fixture";
|
import { SchedulesRepositoryFixture } from "test/fixtures/repository/schedules.repository.fixture";
|
||||||
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||||
import { withApiAuth } from "test/utils/withApiAuth";
|
import { withApiAuth } from "test/utils/withApiAuth";
|
||||||
@@ -25,9 +27,11 @@ describe("Me Endpoints", () => {
|
|||||||
|
|
||||||
let userRepositoryFixture: UserRepositoryFixture;
|
let userRepositoryFixture: UserRepositoryFixture;
|
||||||
let schedulesRepositoryFixture: SchedulesRepositoryFixture;
|
let schedulesRepositoryFixture: SchedulesRepositoryFixture;
|
||||||
|
let profilesRepositoryFixture: ProfileRepositoryFixture;
|
||||||
|
let organizationsRepositoryFixture: OrganizationRepositoryFixture;
|
||||||
const userEmail = "[email protected]";
|
const userEmail = "[email protected]";
|
||||||
let user: User;
|
let user: User;
|
||||||
|
let org: Team;
|
||||||
|
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
const moduleRef = await withApiAuth(
|
const moduleRef = await withApiAuth(
|
||||||
@@ -43,6 +47,9 @@ describe("Me Endpoints", () => {
|
|||||||
.compile();
|
.compile();
|
||||||
|
|
||||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||||
|
organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);
|
||||||
|
profilesRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
||||||
|
|
||||||
schedulesRepositoryFixture = new SchedulesRepositoryFixture(moduleRef);
|
schedulesRepositoryFixture = new SchedulesRepositoryFixture(moduleRef);
|
||||||
|
|
||||||
user = await userRepositoryFixture.create({
|
user = await userRepositoryFixture.create({
|
||||||
@@ -50,6 +57,20 @@ describe("Me Endpoints", () => {
|
|||||||
username: userEmail,
|
username: userEmail,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
org = await organizationsRepositoryFixture.create({
|
||||||
|
name: "Test org team",
|
||||||
|
isOrganization: true,
|
||||||
|
isPlatform: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await profilesRepositoryFixture.create({
|
||||||
|
uid: "asd-asd",
|
||||||
|
username: userEmail,
|
||||||
|
user: { connect: { id: user.id } },
|
||||||
|
organization: { connect: { id: org.id } },
|
||||||
|
movedFromUser: { connect: { id: user.id } },
|
||||||
|
});
|
||||||
|
|
||||||
app = moduleRef.createNestApplication();
|
app = moduleRef.createNestApplication();
|
||||||
bootstrap(app as NestExpressApplication);
|
bootstrap(app as NestExpressApplication);
|
||||||
|
|
||||||
@@ -75,6 +96,8 @@ describe("Me Endpoints", () => {
|
|||||||
expect(responseBody.data.defaultScheduleId).toEqual(user.defaultScheduleId);
|
expect(responseBody.data.defaultScheduleId).toEqual(user.defaultScheduleId);
|
||||||
expect(responseBody.data.weekStart).toEqual(user.weekStart);
|
expect(responseBody.data.weekStart).toEqual(user.weekStart);
|
||||||
expect(responseBody.data.timeZone).toEqual(user.timeZone);
|
expect(responseBody.data.timeZone).toEqual(user.timeZone);
|
||||||
|
expect(responseBody.data.organization?.isPlatform).toEqual(true);
|
||||||
|
expect(responseBody.data.organization?.id).toEqual(org.id);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -138,6 +161,7 @@ describe("Me Endpoints", () => {
|
|||||||
|
|
||||||
afterAll(async () => {
|
afterAll(async () => {
|
||||||
await userRepositoryFixture.deleteByEmail(user.email);
|
await userRepositoryFixture.deleteByEmail(user.email);
|
||||||
|
await organizationsRepositoryFixture.delete(org.id);
|
||||||
await app.close();
|
await app.close();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -29,8 +29,19 @@ export class MeController {
|
|||||||
@Get("/")
|
@Get("/")
|
||||||
@Permissions([PROFILE_READ])
|
@Permissions([PROFILE_READ])
|
||||||
async getMe(@GetUser() user: UserWithProfile): Promise<GetMeOutput> {
|
async getMe(@GetUser() user: UserWithProfile): Promise<GetMeOutput> {
|
||||||
const me = userSchemaResponse.parse(user);
|
const organization = user?.movedToProfile?.organization;
|
||||||
|
const me = userSchemaResponse.parse(
|
||||||
|
organization
|
||||||
|
? {
|
||||||
|
...user,
|
||||||
|
organizationId: organization.id,
|
||||||
|
organization: {
|
||||||
|
id: organization.id,
|
||||||
|
isPlatform: organization.isPlatform,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: user
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
status: SUCCESS_STATUS,
|
status: SUCCESS_STATUS,
|
||||||
data: me,
|
data: me,
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
import { IsInt, IsEmail, IsOptional, IsString } from "class-validator";
|
import { Type } from "class-transformer";
|
||||||
|
import { IsInt, IsEmail, IsOptional, IsString, ValidateNested } from "class-validator";
|
||||||
|
|
||||||
|
export class MeOrgOutput {
|
||||||
|
isPlatform!: boolean;
|
||||||
|
|
||||||
|
id!: number;
|
||||||
|
}
|
||||||
export class MeOutput {
|
export class MeOutput {
|
||||||
@IsInt()
|
@IsInt()
|
||||||
id!: number;
|
id!: number;
|
||||||
@@ -25,4 +31,9 @@ export class MeOutput {
|
|||||||
|
|
||||||
@IsInt()
|
@IsInt()
|
||||||
organizationId!: number | null;
|
organizationId!: number | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => MeOrgOutput)
|
||||||
|
organization?: MeOrgOutput;
|
||||||
}
|
}
|
||||||
+1
-4
@@ -1,9 +1,6 @@
|
|||||||
import { Injectable } from "@nestjs/common";
|
import { Injectable } from "@nestjs/common";
|
||||||
|
|
||||||
import {
|
import { transformApiScheduleOverrides, transformApiScheduleAvailability } from "@calcom/platform-libraries";
|
||||||
transformApiScheduleOverrides,
|
|
||||||
transformApiScheduleAvailability,
|
|
||||||
} from "@calcom/platform-libraries-0.0.22";
|
|
||||||
import { CreateScheduleInput_2024_06_11, ScheduleAvailabilityInput_2024_06_11 } from "@calcom/platform-types";
|
import { CreateScheduleInput_2024_06_11, ScheduleAvailabilityInput_2024_06_11 } from "@calcom/platform-types";
|
||||||
import { ScheduleOverrideInput_2024_06_11 } from "@calcom/platform-types";
|
import { ScheduleOverrideInput_2024_06_11 } from "@calcom/platform-types";
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { ArgumentsHost, Catch, ExceptionFilter, Logger } from "@nestjs/common";
|
|||||||
import { Request } from "express";
|
import { Request } from "express";
|
||||||
|
|
||||||
import { ERROR_STATUS } from "@calcom/platform-constants";
|
import { ERROR_STATUS } from "@calcom/platform-constants";
|
||||||
import { TRPCError } from "@calcom/platform-libraries-0.0.22";
|
import { TRPCError } from "@calcom/platform-libraries";
|
||||||
import { Response } from "@calcom/platform-types";
|
import { Response } from "@calcom/platform-types";
|
||||||
|
|
||||||
@Catch(TRPCError)
|
@Catch(TRPCError)
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
|
||||||
|
import { RedisService } from "@/modules/redis/redis.service";
|
||||||
|
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||||
|
import { Request } from "express";
|
||||||
|
|
||||||
|
import { Team } from "@calcom/prisma/client";
|
||||||
|
|
||||||
|
type CachedData = {
|
||||||
|
org?: Team;
|
||||||
|
canAccess?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class IsAdminAPIEnabledGuard implements CanActivate {
|
||||||
|
constructor(
|
||||||
|
private organizationsRepository: OrganizationsRepository,
|
||||||
|
private readonly redisService: RedisService
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
|
let canAccess = false;
|
||||||
|
const request = context.switchToHttp().getRequest<Request & { organization: Team }>();
|
||||||
|
const organizationId: string = request.params.orgId;
|
||||||
|
|
||||||
|
if (!organizationId) {
|
||||||
|
throw new ForbiddenException("No organization id found in request params.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const REDIS_CACHE_KEY = `apiv2:org:${organizationId}:guard:isAdminAccess`;
|
||||||
|
const cachedData = await this.redisService.redis.get(REDIS_CACHE_KEY);
|
||||||
|
|
||||||
|
if (cachedData) {
|
||||||
|
const { org: cachedOrg, canAccess: cachedCanAccess } = JSON.parse(cachedData) as CachedData;
|
||||||
|
if (cachedOrg?.id === Number(organizationId) && cachedCanAccess !== undefined) {
|
||||||
|
request.organization = cachedOrg;
|
||||||
|
return cachedCanAccess;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const org = await this.organizationsRepository.findById(Number(organizationId));
|
||||||
|
|
||||||
|
if (org?.isOrganization && !org?.isPlatform) {
|
||||||
|
const adminAPIAccessIsEnabledInOrg = await this.organizationsRepository.fetchOrgAdminApiStatus(
|
||||||
|
Number(organizationId)
|
||||||
|
);
|
||||||
|
if (!adminAPIAccessIsEnabledInOrg) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
`Organization does not have Admin API access, please contact https://cal.com/sales to upgrade`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
canAccess = true;
|
||||||
|
org &&
|
||||||
|
(await this.redisService.redis.set(
|
||||||
|
REDIS_CACHE_KEY,
|
||||||
|
JSON.stringify({ org: org, canAccess } satisfies CachedData),
|
||||||
|
"EX",
|
||||||
|
300
|
||||||
|
));
|
||||||
|
return canAccess;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import { TokensRepository } from "@/modules/tokens/tokens.repository";
|
|||||||
import { Injectable, CanActivate, ExecutionContext } from "@nestjs/common";
|
import { Injectable, CanActivate, ExecutionContext } from "@nestjs/common";
|
||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { Reflector } from "@nestjs/core";
|
import { Reflector } from "@nestjs/core";
|
||||||
|
import { getToken } from "next-auth/jwt";
|
||||||
|
|
||||||
import { hasPermissions } from "@calcom/platform-utils";
|
import { hasPermissions } from "@calcom/platform-utils";
|
||||||
|
|
||||||
@@ -24,6 +25,12 @@ export class PermissionsGuard implements CanActivate {
|
|||||||
|
|
||||||
const request = context.switchToHttp().getRequest();
|
const request = context.switchToHttp().getRequest();
|
||||||
const authString = request.get("Authorization")?.replace("Bearer ", "");
|
const authString = request.get("Authorization")?.replace("Bearer ", "");
|
||||||
|
const nextAuthSecret = this.config.get("next.authSecret", { infer: true });
|
||||||
|
const nextAuthToken = await getToken({ req: request, secret: nextAuthSecret });
|
||||||
|
|
||||||
|
if (nextAuthToken) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
if (!authString) {
|
if (!authString) {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { Injectable, InternalServerErrorException, UnauthorizedException } from
|
|||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { PassportStrategy } from "@nestjs/passport";
|
import { PassportStrategy } from "@nestjs/passport";
|
||||||
import type { Request } from "express";
|
import type { Request } from "express";
|
||||||
|
import { getToken } from "next-auth/jwt";
|
||||||
|
|
||||||
import { INVALID_ACCESS_TOKEN, X_CAL_CLIENT_ID, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
|
import { INVALID_ACCESS_TOKEN, X_CAL_CLIENT_ID, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
|
||||||
|
|
||||||
@@ -45,6 +46,13 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
|
|||||||
return await this.authenticateBearerToken(bearerToken, requestOrigin);
|
return await this.authenticateBearerToken(bearerToken, requestOrigin);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const nextAuthSecret = this.config.get("next.authSecret", { infer: true });
|
||||||
|
const nextAuthToken = await getToken({ req: request, secret: nextAuthSecret });
|
||||||
|
|
||||||
|
if (nextAuthToken) {
|
||||||
|
return await this.authenticateNextAuth(nextAuthToken);
|
||||||
|
}
|
||||||
|
|
||||||
throw new UnauthorizedException(
|
throw new UnauthorizedException(
|
||||||
"No authentication method provided. Either pass an API key as 'Bearer' header or OAuth client credentials as 'x-cal-secret-key' and 'x-cal-client-id' headers"
|
"No authentication method provided. Either pass an API key as 'Bearer' header or OAuth client credentials as 'x-cal-secret-key' and 'x-cal-client-id' headers"
|
||||||
);
|
);
|
||||||
@@ -58,6 +66,11 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async authenticateNextAuth(token: { email?: string | null }) {
|
||||||
|
const user = await this.nextAuthStrategy(token);
|
||||||
|
return this.success(user);
|
||||||
|
}
|
||||||
|
|
||||||
async authenticateOAuthClient(oAuthClientId: string, oAuthClientSecret: string) {
|
async authenticateOAuthClient(oAuthClientId: string, oAuthClientSecret: string) {
|
||||||
const user = await this.oAuthClientStrategy(oAuthClientId, oAuthClientSecret);
|
const user = await this.oAuthClientStrategy(oAuthClientId, oAuthClientSecret);
|
||||||
return this.success(user);
|
return this.success(user);
|
||||||
@@ -163,4 +176,17 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
|
|||||||
const user: UserWithProfile | null = await this.userRepository.findByIdWithProfile(ownerId);
|
const user: UserWithProfile | null = await this.userRepository.findByIdWithProfile(ownerId);
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async nextAuthStrategy(token: { email?: string | null }) {
|
||||||
|
if (!token.email) {
|
||||||
|
throw new UnauthorizedException("Email not found in the authentication token.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await this.userRepository.findByEmailWithProfile(token.email);
|
||||||
|
if (!user) {
|
||||||
|
throw new UnauthorizedException("User associated with the authentication token email not found.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+171
@@ -0,0 +1,171 @@
|
|||||||
|
import { bootstrap } from "@/app";
|
||||||
|
import { AppModule } from "@/app.module";
|
||||||
|
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
|
||||||
|
import { HttpExceptionFilter } from "@/filters/http-exception.filter";
|
||||||
|
import { PrismaExceptionFilter } from "@/filters/prisma-exception.filter";
|
||||||
|
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
|
||||||
|
import { DestinationCalendarsOutputResponseDto } from "@/modules/destination-calendars/outputs/destination-calendars.output";
|
||||||
|
import { TokensModule } from "@/modules/tokens/tokens.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 { PlatformOAuthClient, Team, User, Credential } from "@prisma/client";
|
||||||
|
import * as request from "supertest";
|
||||||
|
import { CredentialsRepositoryFixture } from "test/fixtures/repository/credentials.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 { APPLE_CALENDAR_TYPE, APPLE_CALENDAR_ID } from "@calcom/platform-constants";
|
||||||
|
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||||
|
|
||||||
|
const CLIENT_REDIRECT_URI = "http://localhost:5555";
|
||||||
|
|
||||||
|
describe("Platform Destination Calendar Endpoints", () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
|
||||||
|
let oAuthClient: PlatformOAuthClient;
|
||||||
|
let organization: Team;
|
||||||
|
let userRepositoryFixture: UserRepositoryFixture;
|
||||||
|
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
|
||||||
|
let teamRepositoryFixture: TeamRepositoryFixture;
|
||||||
|
let tokensRepositoryFixture: TokensRepositoryFixture;
|
||||||
|
let credentialsRepositoryFixture: CredentialsRepositoryFixture;
|
||||||
|
let appleCalendarCredentials: Credential;
|
||||||
|
let user: User;
|
||||||
|
let accessTokenSecret: string;
|
||||||
|
let refreshTokenSecret: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleRef = await Test.createTestingModule({
|
||||||
|
providers: [PrismaExceptionFilter, HttpExceptionFilter],
|
||||||
|
imports: [AppModule, UsersModule, TokensModule],
|
||||||
|
})
|
||||||
|
.overrideGuard(PermissionsGuard)
|
||||||
|
.useValue({
|
||||||
|
canActivate: () => true,
|
||||||
|
})
|
||||||
|
|
||||||
|
.compile();
|
||||||
|
|
||||||
|
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
||||||
|
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||||
|
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
||||||
|
tokensRepositoryFixture = new TokensRepositoryFixture(moduleRef);
|
||||||
|
credentialsRepositoryFixture = new CredentialsRepositoryFixture(moduleRef);
|
||||||
|
organization = await teamRepositoryFixture.create({ name: "organization" });
|
||||||
|
oAuthClient = await createOAuthClient(organization.id);
|
||||||
|
user = await userRepositoryFixture.createOAuthManagedUser("[email protected]", oAuthClient.id);
|
||||||
|
const tokens = await tokensRepositoryFixture.createTokens(user.id, oAuthClient.id);
|
||||||
|
accessTokenSecret = tokens.accessToken;
|
||||||
|
refreshTokenSecret = tokens.refreshToken;
|
||||||
|
appleCalendarCredentials = await credentialsRepositoryFixture.create(
|
||||||
|
APPLE_CALENDAR_TYPE,
|
||||||
|
{},
|
||||||
|
user.id,
|
||||||
|
APPLE_CALENDAR_ID
|
||||||
|
);
|
||||||
|
jest.spyOn(CalendarsService.prototype, "getCalendars").mockReturnValue(
|
||||||
|
Promise.resolve({
|
||||||
|
connectedCalendars: [
|
||||||
|
{
|
||||||
|
integration: {
|
||||||
|
installed: false,
|
||||||
|
type: "apple_calendar",
|
||||||
|
title: "",
|
||||||
|
name: "",
|
||||||
|
description: "",
|
||||||
|
variant: "calendar",
|
||||||
|
slug: "",
|
||||||
|
locationOption: null,
|
||||||
|
categories: ["calendar"],
|
||||||
|
logo: "",
|
||||||
|
publisher: "",
|
||||||
|
url: "",
|
||||||
|
email: "",
|
||||||
|
},
|
||||||
|
calendars: {
|
||||||
|
externalId:
|
||||||
|
"https://caldav.icloud.com/20961146906/calendars/83C4F9A1-F1D0-41C7-8FC3-0B$9AE22E813/",
|
||||||
|
readOnly: false,
|
||||||
|
integration: "apple_calendar",
|
||||||
|
credentialId: appleCalendarCredentials.id,
|
||||||
|
primary: true,
|
||||||
|
email: user.email,
|
||||||
|
},
|
||||||
|
error: { message: "" },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
);
|
||||||
|
app = moduleRef.createNestApplication();
|
||||||
|
bootstrap(app as NestExpressApplication);
|
||||||
|
await app.init();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function createOAuthClient(organizationId: number) {
|
||||||
|
const data = {
|
||||||
|
logo: "logo-url",
|
||||||
|
name: "name",
|
||||||
|
redirectUris: [CLIENT_REDIRECT_URI],
|
||||||
|
permissions: 32,
|
||||||
|
};
|
||||||
|
const secret = "secret";
|
||||||
|
|
||||||
|
const client = await oauthClientRepositoryFixture.create(organizationId, data, secret);
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
it("should be defined", () => {
|
||||||
|
expect(oauthClientRepositoryFixture).toBeDefined();
|
||||||
|
expect(userRepositoryFixture).toBeDefined();
|
||||||
|
expect(oAuthClient).toBeDefined();
|
||||||
|
expect(accessTokenSecret).toBeDefined();
|
||||||
|
expect(refreshTokenSecret).toBeDefined();
|
||||||
|
expect(user).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it(`POST /v2/destination-calendars: it should respond with a 200 returning back the user updated destination calendar`, async () => {
|
||||||
|
const body = {
|
||||||
|
integration: appleCalendarCredentials.type,
|
||||||
|
externalId: "https://caldav.icloud.com/20961146906/calendars/83C4F9A1-F1D0-41C7-8FC3-0B$9AE22E813/",
|
||||||
|
};
|
||||||
|
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.put("/v2/destination-calendars")
|
||||||
|
.set("Authorization", `Bearer ${accessTokenSecret}`)
|
||||||
|
.send(body)
|
||||||
|
.expect(200)
|
||||||
|
.then(async (response) => {
|
||||||
|
const responseBody: DestinationCalendarsOutputResponseDto = response.body;
|
||||||
|
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||||
|
expect(responseBody.data).toBeDefined();
|
||||||
|
expect(responseBody.data.credentialId).toEqual(appleCalendarCredentials.id);
|
||||||
|
expect(responseBody.data.integration).toEqual(body.integration);
|
||||||
|
expect(responseBody.data.externalId).toEqual(body.externalId);
|
||||||
|
expect(responseBody.data.userId).toEqual(user.id);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it(`POST /v2/destination-calendars: should fail 400 if calendar type is invalid`, async () => {
|
||||||
|
const body = {
|
||||||
|
integration: "not-supported-calendar",
|
||||||
|
externalId: "https://caldav.icloud.com/20961146906/calendars/83C4F9A1-F1D0-41C7-8FC3-0B$9AE22E813/",
|
||||||
|
};
|
||||||
|
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.put("/v2/destination-calendars")
|
||||||
|
.set("Authorization", `Bearer ${accessTokenSecret}`)
|
||||||
|
.send(body)
|
||||||
|
.expect(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await oauthClientRepositoryFixture.delete(oAuthClient.id);
|
||||||
|
await teamRepositoryFixture.delete(organization.id);
|
||||||
|
await userRepositoryFixture.deleteByEmail(user.email);
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
|
||||||
|
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
|
||||||
|
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
|
||||||
|
import { DestinationCalendarsInputBodyDto } from "@/modules/destination-calendars/inputs/destination-calendars.input";
|
||||||
|
import {
|
||||||
|
DestinationCalendarsOutputDto,
|
||||||
|
DestinationCalendarsOutputResponseDto,
|
||||||
|
} from "@/modules/destination-calendars/outputs/destination-calendars.output";
|
||||||
|
import { DestinationCalendarsService } from "@/modules/destination-calendars/services/destination-calendars.service";
|
||||||
|
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||||
|
import { Body, Controller, Put, UseGuards } from "@nestjs/common";
|
||||||
|
import { ApiTags as DocsTags } from "@nestjs/swagger";
|
||||||
|
import { plainToClass } from "class-transformer";
|
||||||
|
|
||||||
|
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||||
|
|
||||||
|
@Controller({
|
||||||
|
path: "/v2/destination-calendars",
|
||||||
|
version: API_VERSIONS_VALUES,
|
||||||
|
})
|
||||||
|
@DocsTags("Destination-Calendars")
|
||||||
|
export class DestinationCalendarsController {
|
||||||
|
constructor(private readonly destinationCalendarsService: DestinationCalendarsService) {}
|
||||||
|
|
||||||
|
@Put("/")
|
||||||
|
@UseGuards(ApiAuthGuard)
|
||||||
|
@DocsTags("Select a third party destination calendar where events will be created")
|
||||||
|
async updateDestinationCalendars(
|
||||||
|
@Body() input: DestinationCalendarsInputBodyDto,
|
||||||
|
@GetUser() user: UserWithProfile
|
||||||
|
): Promise<DestinationCalendarsOutputResponseDto> {
|
||||||
|
const { integration, externalId } = input;
|
||||||
|
const updatedDestinationCalendar = await this.destinationCalendarsService.updateDestinationCalendars(
|
||||||
|
integration,
|
||||||
|
externalId,
|
||||||
|
user.id
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
status: SUCCESS_STATUS,
|
||||||
|
data: plainToClass(DestinationCalendarsOutputDto, updatedDestinationCalendar, {
|
||||||
|
strategy: "excludeAll",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { CalendarsRepository } from "@/ee/calendars/calendars.repository";
|
||||||
|
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
|
||||||
|
import { AppsRepository } from "@/modules/apps/apps.repository";
|
||||||
|
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
|
||||||
|
import { DestinationCalendarsController } from "@/modules/destination-calendars/controllers/destination-calendars.controller";
|
||||||
|
import { DestinationCalendarsRepository } from "@/modules/destination-calendars/destination-calendars.repository";
|
||||||
|
import { DestinationCalendarsService } from "@/modules/destination-calendars/services/destination-calendars.service";
|
||||||
|
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||||
|
import { UsersRepository } from "@/modules/users/users.repository";
|
||||||
|
import { Module } from "@nestjs/common";
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [PrismaModule],
|
||||||
|
providers: [
|
||||||
|
CalendarsRepository,
|
||||||
|
CalendarsService,
|
||||||
|
DestinationCalendarsService,
|
||||||
|
DestinationCalendarsRepository,
|
||||||
|
UsersRepository,
|
||||||
|
CredentialsRepository,
|
||||||
|
AppsRepository,
|
||||||
|
],
|
||||||
|
controllers: [DestinationCalendarsController],
|
||||||
|
exports: [DestinationCalendarsRepository],
|
||||||
|
})
|
||||||
|
export class DestinationCalendarsModule {}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class DestinationCalendarsRepository {
|
||||||
|
constructor(private readonly dbWrite: PrismaWriteService) {}
|
||||||
|
|
||||||
|
async updateCalendar(
|
||||||
|
integration: string,
|
||||||
|
externalId: string,
|
||||||
|
credentialId: number,
|
||||||
|
userId: number,
|
||||||
|
primaryEmail: string | null
|
||||||
|
) {
|
||||||
|
return await this.dbWrite.prisma.destinationCalendar.upsert({
|
||||||
|
update: {
|
||||||
|
integration,
|
||||||
|
externalId,
|
||||||
|
credentialId,
|
||||||
|
primaryEmail,
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
integration,
|
||||||
|
externalId,
|
||||||
|
credentialId,
|
||||||
|
primaryEmail,
|
||||||
|
userId,
|
||||||
|
},
|
||||||
|
where: {
|
||||||
|
userId: userId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { ApiProperty } from "@nestjs/swagger";
|
||||||
|
import { Expose } from "class-transformer";
|
||||||
|
import { IsString, IsEnum } from "class-validator";
|
||||||
|
|
||||||
|
import {
|
||||||
|
APPLE_CALENDAR_TYPE,
|
||||||
|
GOOGLE_CALENDAR_TYPE,
|
||||||
|
OFFICE_365_CALENDAR_TYPE,
|
||||||
|
} from "@calcom/platform-constants";
|
||||||
|
|
||||||
|
export class DestinationCalendarsInputBodyDto {
|
||||||
|
@IsString()
|
||||||
|
@Expose()
|
||||||
|
@ApiProperty({
|
||||||
|
example: APPLE_CALENDAR_TYPE,
|
||||||
|
description: "The calendar service you want to integrate, as returned by the /calendars endpoint",
|
||||||
|
enum: [APPLE_CALENDAR_TYPE, GOOGLE_CALENDAR_TYPE, OFFICE_365_CALENDAR_TYPE],
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
@IsEnum([APPLE_CALENDAR_TYPE, GOOGLE_CALENDAR_TYPE, OFFICE_365_CALENDAR_TYPE])
|
||||||
|
readonly integration!:
|
||||||
|
| typeof APPLE_CALENDAR_TYPE
|
||||||
|
| typeof GOOGLE_CALENDAR_TYPE
|
||||||
|
| typeof OFFICE_365_CALENDAR_TYPE;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@Expose()
|
||||||
|
@ApiProperty({
|
||||||
|
example: "https://caldav.icloud.com/26962146906/calendars/1644422A-1945-4438-BBC0-4F0Q23A57R7S/",
|
||||||
|
description:
|
||||||
|
"Unique identifier used to represent the specfic calendar, as returned by the /calendars endpoint",
|
||||||
|
type: "string",
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
readonly externalId!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { ApiProperty } from "@nestjs/swagger";
|
||||||
|
import { Expose, Type } from "class-transformer";
|
||||||
|
import { IsInt, IsString, ValidateNested, IsEnum } from "class-validator";
|
||||||
|
|
||||||
|
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||||
|
|
||||||
|
export class DestinationCalendarsOutputDto {
|
||||||
|
@IsInt()
|
||||||
|
@Expose()
|
||||||
|
readonly userId!: number;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@Expose()
|
||||||
|
readonly integration!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@Expose()
|
||||||
|
readonly externalId!: string;
|
||||||
|
|
||||||
|
@IsInt()
|
||||||
|
@Expose()
|
||||||
|
readonly credentialId!: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class DestinationCalendarsOutputResponseDto {
|
||||||
|
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
|
||||||
|
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
|
||||||
|
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
|
||||||
|
|
||||||
|
@Expose()
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => DestinationCalendarsOutputDto)
|
||||||
|
data!: DestinationCalendarsOutputDto;
|
||||||
|
}
|
||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
import { ConnectedCalendar, Calendar } from "@/ee/calendars/outputs/connected-calendars.output";
|
||||||
|
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
|
||||||
|
import { DestinationCalendarsRepository } from "@/modules/destination-calendars/destination-calendars.repository";
|
||||||
|
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class DestinationCalendarsService {
|
||||||
|
constructor(
|
||||||
|
private readonly calendarsService: CalendarsService,
|
||||||
|
private readonly destinationCalendarsRepository: DestinationCalendarsRepository
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async updateDestinationCalendars(integration: string, externalId: string, userId: number) {
|
||||||
|
const userCalendars = await this.calendarsService.getCalendars(userId);
|
||||||
|
const allCalendars = userCalendars.connectedCalendars
|
||||||
|
.map((cal: ConnectedCalendar) => cal.calendars ?? [])
|
||||||
|
.flat();
|
||||||
|
const credentialId = allCalendars.find(
|
||||||
|
(cal: Calendar) =>
|
||||||
|
cal.externalId === externalId && cal.integration === integration && cal.readOnly === false
|
||||||
|
)?.credentialId;
|
||||||
|
|
||||||
|
if (!credentialId) {
|
||||||
|
throw new NotFoundException(`Could not find calendar ${externalId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const primaryEmail =
|
||||||
|
allCalendars.find((cal: Calendar) => cal.primary && cal.credentialId === credentialId)?.email ?? null;
|
||||||
|
|
||||||
|
const {
|
||||||
|
integration: updatedCalendarIntegration,
|
||||||
|
externalId: updatedCalendarExternalId,
|
||||||
|
credentialId: updatedCalendarCredentialId,
|
||||||
|
userId: updatedCalendarUserId,
|
||||||
|
} = await this.destinationCalendarsRepository.updateCalendar(
|
||||||
|
integration,
|
||||||
|
externalId,
|
||||||
|
credentialId,
|
||||||
|
userId,
|
||||||
|
primaryEmail
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
userId: updatedCalendarUserId,
|
||||||
|
integration: updatedCalendarIntegration,
|
||||||
|
externalId: updatedCalendarExternalId,
|
||||||
|
credentialId: updatedCalendarCredentialId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Injectable } from "@nestjs/common";
|
import { Injectable } from "@nestjs/common";
|
||||||
|
|
||||||
import { sendSignupToOrganizationEmail, getTranslation } from "@calcom/platform-libraries-0.0.22";
|
import { sendSignupToOrganizationEmail, getTranslation } from "@calcom/platform-libraries";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class EmailService {
|
export class EmailService {
|
||||||
|
|||||||
@@ -1,14 +1,24 @@
|
|||||||
import { PlatformEndpointsModule } from "@/ee/platform-endpoints-module";
|
import { PlatformEndpointsModule } from "@/ee/platform-endpoints-module";
|
||||||
import { BillingModule } from "@/modules/billing/billing.module";
|
import { BillingModule } from "@/modules/billing/billing.module";
|
||||||
|
import { DestinationCalendarsModule } from "@/modules/destination-calendars/destination-calendars.module";
|
||||||
import { OAuthClientModule } from "@/modules/oauth-clients/oauth-client.module";
|
import { OAuthClientModule } from "@/modules/oauth-clients/oauth-client.module";
|
||||||
import { TimezoneModule } from "@/modules/timezones/timezones.module";
|
import { TimezoneModule } from "@/modules/timezones/timezones.module";
|
||||||
import type { MiddlewareConsumer, NestModule } from "@nestjs/common";
|
import type { MiddlewareConsumer, NestModule } from "@nestjs/common";
|
||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
|
|
||||||
import { UsersModule } from "./users/users.module";
|
import { UsersModule } from "./users/users.module";
|
||||||
|
import { WebhooksModule } from "./webhooks/webhooks.module";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [OAuthClientModule, BillingModule, PlatformEndpointsModule, TimezoneModule, UsersModule],
|
imports: [
|
||||||
|
OAuthClientModule,
|
||||||
|
BillingModule,
|
||||||
|
PlatformEndpointsModule,
|
||||||
|
TimezoneModule,
|
||||||
|
UsersModule,
|
||||||
|
WebhooksModule,
|
||||||
|
DestinationCalendarsModule,
|
||||||
|
],
|
||||||
})
|
})
|
||||||
export class EndpointsModule implements NestModule {
|
export class EndpointsModule implements NestModule {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
|
|||||||
+295
@@ -0,0 +1,295 @@
|
|||||||
|
import { bootstrap } from "@/app";
|
||||||
|
import { AppModule } from "@/app.module";
|
||||||
|
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||||
|
import { TokensModule } from "@/modules/tokens/tokens.module";
|
||||||
|
import { UsersModule } from "@/modules/users/users.module";
|
||||||
|
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||||
|
import { CreateWebhookInputDto, UpdateWebhookInputDto } from "@/modules/webhooks/inputs/webhook.input";
|
||||||
|
import {
|
||||||
|
EventTypeWebhookOutputResponseDto,
|
||||||
|
EventTypeWebhooksOutputResponseDto,
|
||||||
|
} from "@/modules/webhooks/outputs/event-type-webhook.output";
|
||||||
|
import { DeleteManyWebhooksOutputResponseDto } from "@/modules/webhooks/outputs/webhook.output";
|
||||||
|
import { INestApplication } from "@nestjs/common";
|
||||||
|
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||||
|
import { Test } from "@nestjs/testing";
|
||||||
|
import * as request from "supertest";
|
||||||
|
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
|
||||||
|
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||||
|
import { WebhookRepositoryFixture } from "test/fixtures/repository/webhooks.repository.fixture";
|
||||||
|
import { withApiAuth } from "test/utils/withApiAuth";
|
||||||
|
|
||||||
|
import { EventType, Webhook } from "@calcom/prisma/client";
|
||||||
|
|
||||||
|
describe("EventTypes WebhooksController (e2e)", () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
const userEmail = "[email protected]";
|
||||||
|
let user: UserWithProfile;
|
||||||
|
let otherUser: UserWithProfile;
|
||||||
|
let eventType: EventType;
|
||||||
|
let eventType2: EventType;
|
||||||
|
let otherEventType: EventType;
|
||||||
|
|
||||||
|
let eventTypeRepositoryFixture: EventTypesRepositoryFixture;
|
||||||
|
let userRepositoryFixture: UserRepositoryFixture;
|
||||||
|
let webhookRepositoryFixture: WebhookRepositoryFixture;
|
||||||
|
|
||||||
|
let webhook: EventTypeWebhookOutputResponseDto["data"];
|
||||||
|
let webhook2: Webhook;
|
||||||
|
let otherWebhook: Webhook;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleRef = await withApiAuth(
|
||||||
|
userEmail,
|
||||||
|
Test.createTestingModule({
|
||||||
|
imports: [AppModule, PrismaModule, UsersModule, TokensModule],
|
||||||
|
})
|
||||||
|
).compile();
|
||||||
|
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||||
|
webhookRepositoryFixture = new WebhookRepositoryFixture(moduleRef);
|
||||||
|
eventTypeRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
|
||||||
|
|
||||||
|
user = await userRepositoryFixture.create({
|
||||||
|
email: userEmail,
|
||||||
|
username: userEmail,
|
||||||
|
});
|
||||||
|
|
||||||
|
otherUser = await userRepositoryFixture.create({
|
||||||
|
email: "[email protected]",
|
||||||
|
username: "[email protected]",
|
||||||
|
});
|
||||||
|
|
||||||
|
eventType = await eventTypeRepositoryFixture.create(
|
||||||
|
{
|
||||||
|
title: "Event Type 1",
|
||||||
|
slug: "webhook-event-type-1",
|
||||||
|
length: 60,
|
||||||
|
},
|
||||||
|
user.id
|
||||||
|
);
|
||||||
|
|
||||||
|
eventType2 = await eventTypeRepositoryFixture.create(
|
||||||
|
{
|
||||||
|
title: "Event Type 2",
|
||||||
|
slug: "webhook-event-type-2",
|
||||||
|
length: 60,
|
||||||
|
},
|
||||||
|
user.id
|
||||||
|
);
|
||||||
|
|
||||||
|
otherEventType = await eventTypeRepositoryFixture.create(
|
||||||
|
{
|
||||||
|
title: "Other Event Type ",
|
||||||
|
slug: "other-webhook-event-type",
|
||||||
|
length: 60,
|
||||||
|
},
|
||||||
|
otherUser.id
|
||||||
|
);
|
||||||
|
|
||||||
|
otherWebhook = await webhookRepositoryFixture.create({
|
||||||
|
id: "2mdfnn24",
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
eventTriggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
active: true,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
});
|
||||||
|
app = moduleRef.createNestApplication();
|
||||||
|
bootstrap(app as NestExpressApplication);
|
||||||
|
|
||||||
|
await app.init();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
userRepositoryFixture.deleteByEmail(user.email);
|
||||||
|
userRepositoryFixture.deleteByEmail(otherUser.email);
|
||||||
|
webhookRepositoryFixture.delete(otherWebhook.id);
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/webhooks (POST)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.post(`/v2/event-types/${eventType.id}/webhooks`)
|
||||||
|
.send({
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
triggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
active: true,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
} satisfies CreateWebhookInputDto)
|
||||||
|
.expect(201)
|
||||||
|
.then(async (res) => {
|
||||||
|
expect(res.body).toMatchObject({
|
||||||
|
status: "success",
|
||||||
|
data: {
|
||||||
|
id: expect.any(String),
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
triggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
active: true,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
eventTypeId: eventType.id,
|
||||||
|
},
|
||||||
|
} satisfies EventTypeWebhookOutputResponseDto);
|
||||||
|
webhook = res.body.data;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/webhooks (POST)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.post(`/v2/event-types/${eventType2.id}/webhooks`)
|
||||||
|
.send({
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
triggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
active: true,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
} satisfies CreateWebhookInputDto)
|
||||||
|
.expect(201)
|
||||||
|
.then(async (res) => {
|
||||||
|
expect(res.body).toMatchObject({
|
||||||
|
status: "success",
|
||||||
|
data: {
|
||||||
|
id: expect.any(String),
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
triggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
active: true,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
eventTypeId: eventType2.id,
|
||||||
|
},
|
||||||
|
} satisfies EventTypeWebhookOutputResponseDto);
|
||||||
|
webhook2 = res.body.data;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/webhooks (POST) should fail to create a webhook for an event-type that does not belong to user", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.post(`/v2/event-types/${otherEventType.id}/webhooks`)
|
||||||
|
.send({
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
triggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
active: true,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
} satisfies CreateWebhookInputDto)
|
||||||
|
.expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/event-types/:eventTypeId/webhooks/:webhookId (PATCH)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.patch(`/v2/event-types/${eventType.id}/webhooks/${webhook.id}`)
|
||||||
|
.send({
|
||||||
|
active: false,
|
||||||
|
} satisfies UpdateWebhookInputDto)
|
||||||
|
.expect(200)
|
||||||
|
.then((res) => {
|
||||||
|
expect(res.body.data.active).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/event-types/:eventTypeId/webhooks/:webhookId (PATCH) should fail to patch a webhook for an event-type that does not belong to user", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.patch(`/v2/event-types/${otherEventType.id}/webhooks/${otherWebhook.id}`)
|
||||||
|
.send({
|
||||||
|
active: false,
|
||||||
|
} satisfies UpdateWebhookInputDto)
|
||||||
|
.expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/event-types/:eventTypeId/webhooks/:webhookId (GET)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get(`/v2/event-types/${eventType.id}/webhooks/${webhook.id}`)
|
||||||
|
.expect(200)
|
||||||
|
.then((res) => {
|
||||||
|
expect(res.body).toMatchObject({
|
||||||
|
status: "success",
|
||||||
|
data: {
|
||||||
|
id: expect.any(String),
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
triggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
active: false,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
eventTypeId: eventType.id,
|
||||||
|
},
|
||||||
|
} satisfies EventTypeWebhookOutputResponseDto);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/event-types/:eventTypeId/webhooks/:webhookId (GET) should fail to get a webhook that does not exist", () => {
|
||||||
|
return request(app.getHttpServer()).get(`/v2/event-types/${eventType.id}/webhooks/90284`).expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/event-types/:eventTypeId/webhooks/:webhookId (GET) should fail to get a webhook of an eventType that does not belong to user", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get(`/v2/event-types/${otherEventType.id}/webhooks/${otherWebhook.id}`)
|
||||||
|
.expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/event-types/:eventTypeId/webhooks/:webhookId (GET) should fail to get a webhook that does not belong to the eventType", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get(`/v2/event-types/${eventType.id}/webhooks/${otherWebhook.id}`)
|
||||||
|
.expect(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/webhooks (GET)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get(`/v2/event-types/${eventType.id}/webhooks`)
|
||||||
|
.expect(200)
|
||||||
|
.then((res) => {
|
||||||
|
const responseBody = res.body as EventTypeWebhooksOutputResponseDto;
|
||||||
|
responseBody.data.forEach((webhook) => {
|
||||||
|
expect(webhook.eventTypeId).toBe(eventType.id);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/event-types/:eventTypeId/webhooks (GET)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get(`/v2/event-types/${eventType2.id}/webhooks`)
|
||||||
|
.expect(200)
|
||||||
|
.then((res) => {
|
||||||
|
const responseBody = res.body as EventTypeWebhooksOutputResponseDto;
|
||||||
|
responseBody.data.forEach((webhook) => {
|
||||||
|
expect(webhook.eventTypeId).toBe(eventType2.id);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/event-types/:eventTypeId/webhooks/:webhookId (DELETE)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.delete(`/v2/event-types/${eventType.id}/webhooks/${webhook.id}`)
|
||||||
|
.expect(200)
|
||||||
|
.then((res) => {
|
||||||
|
expect(res.body).toMatchObject({
|
||||||
|
status: "success",
|
||||||
|
data: {
|
||||||
|
id: expect.any(String),
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
triggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
active: false,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
eventTypeId: eventType.id,
|
||||||
|
},
|
||||||
|
} satisfies EventTypeWebhookOutputResponseDto);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/event-types/:eventTypeId/webhooks (DELETE)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.delete(`/v2/event-types/${eventType2.id}/webhooks`)
|
||||||
|
.expect(200)
|
||||||
|
.then((res) => {
|
||||||
|
expect(res.body).toMatchObject({
|
||||||
|
status: "success",
|
||||||
|
data: "1 webhooks deleted",
|
||||||
|
} satisfies DeleteManyWebhooksOutputResponseDto);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/event-types/:eventTypeId/webhooks/:webhookId (DELETE) shoud fail to delete a webhook that does not exist", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.delete(`/v2/event-types/${eventType.id}/webhooks/1234453`)
|
||||||
|
.expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/event-types/:eventTypeId/webhooks/:webhookId (DELETE) shoud fail to delete a webhook that does not belong to user", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.delete(`/v2/event-types/${otherEventType.id}/webhooks/${otherWebhook.id}`)
|
||||||
|
.expect(403);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
|
||||||
|
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
|
||||||
|
import { GetWebhook } from "@/modules/webhooks/decorators/get-webhook-decorator";
|
||||||
|
import { IsUserEventTypeWebhookGuard } from "@/modules/webhooks/guards/is-user-event-type-webhook-guard";
|
||||||
|
import { CreateWebhookInputDto, UpdateWebhookInputDto } from "@/modules/webhooks/inputs/webhook.input";
|
||||||
|
import {
|
||||||
|
EventTypeWebhookOutputResponseDto,
|
||||||
|
EventTypeWebhookOutputDto,
|
||||||
|
EventTypeWebhooksOutputResponseDto,
|
||||||
|
} from "@/modules/webhooks/outputs/event-type-webhook.output";
|
||||||
|
import { DeleteManyWebhooksOutputResponseDto } from "@/modules/webhooks/outputs/webhook.output";
|
||||||
|
import { PartialWebhookInputPipe, WebhookInputPipe } from "@/modules/webhooks/pipes/WebhookInputPipe";
|
||||||
|
import { WebhookOutputPipe } from "@/modules/webhooks/pipes/WebhookOutputPipe";
|
||||||
|
import { EventTypeWebhooksService } from "@/modules/webhooks/services/event-type-webhooks.service";
|
||||||
|
import { WebhooksService } from "@/modules/webhooks/services/webhooks.service";
|
||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
Post,
|
||||||
|
Body,
|
||||||
|
UseGuards,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Query,
|
||||||
|
Delete,
|
||||||
|
Patch,
|
||||||
|
ParseIntPipe,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import { ApiOperation, ApiTags } from "@nestjs/swagger";
|
||||||
|
import { Webhook } from "@prisma/client";
|
||||||
|
import { plainToClass } from "class-transformer";
|
||||||
|
|
||||||
|
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||||
|
import { SkipTakePagination } from "@calcom/platform-types";
|
||||||
|
|
||||||
|
@Controller({
|
||||||
|
path: "/v2/event-types/:eventTypeId/webhooks",
|
||||||
|
version: API_VERSIONS_VALUES,
|
||||||
|
})
|
||||||
|
@UseGuards(ApiAuthGuard, IsUserEventTypeWebhookGuard)
|
||||||
|
@ApiTags("Users' EventTypes Webhooks")
|
||||||
|
export class EventTypeWebhooksController {
|
||||||
|
constructor(
|
||||||
|
private readonly webhooksService: WebhooksService,
|
||||||
|
private readonly eventTypeWebhooksService: EventTypeWebhooksService
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Post("/")
|
||||||
|
@ApiOperation({ summary: "Create a webhook for an event-type" })
|
||||||
|
async createEventTypeWebhook(
|
||||||
|
@Body() body: CreateWebhookInputDto,
|
||||||
|
@Param("eventTypeId", ParseIntPipe) eventTypeId: number
|
||||||
|
): Promise<EventTypeWebhookOutputResponseDto> {
|
||||||
|
const webhook = await this.eventTypeWebhooksService.createEventTypeWebhook(
|
||||||
|
eventTypeId,
|
||||||
|
new WebhookInputPipe().transform(body)
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
status: SUCCESS_STATUS,
|
||||||
|
data: plainToClass(EventTypeWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
|
||||||
|
strategy: "excludeAll",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch("/:webhookId")
|
||||||
|
@ApiOperation({ summary: "Update a webhook of an event-type" })
|
||||||
|
async updateEventTypeWebhook(
|
||||||
|
@Body() body: UpdateWebhookInputDto,
|
||||||
|
@Param("webhookId") webhookId: string
|
||||||
|
): Promise<EventTypeWebhookOutputResponseDto> {
|
||||||
|
const webhook = await this.webhooksService.updateWebhook(
|
||||||
|
webhookId,
|
||||||
|
new PartialWebhookInputPipe().transform(body)
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
status: SUCCESS_STATUS,
|
||||||
|
data: plainToClass(EventTypeWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
|
||||||
|
strategy: "excludeAll",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("/:webhookId")
|
||||||
|
@ApiOperation({ summary: "Get a webhook of an event-type" })
|
||||||
|
async getEventTypeWebhook(@GetWebhook() webhook: Webhook): Promise<EventTypeWebhookOutputResponseDto> {
|
||||||
|
return {
|
||||||
|
status: SUCCESS_STATUS,
|
||||||
|
data: plainToClass(EventTypeWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
|
||||||
|
strategy: "excludeAll",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("/")
|
||||||
|
@ApiOperation({ summary: "Get all webhooks of an event-type" })
|
||||||
|
async getEventTypeWebhooks(
|
||||||
|
@Param("eventTypeId", ParseIntPipe) eventTypeId: number,
|
||||||
|
@Query() pagination: SkipTakePagination
|
||||||
|
): Promise<EventTypeWebhooksOutputResponseDto> {
|
||||||
|
const webhooks = await this.eventTypeWebhooksService.getEventTypeWebhooksPaginated(
|
||||||
|
eventTypeId,
|
||||||
|
pagination.skip ?? 0,
|
||||||
|
pagination.take ?? 250
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
status: SUCCESS_STATUS,
|
||||||
|
data: webhooks.map((webhook) =>
|
||||||
|
plainToClass(EventTypeWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
|
||||||
|
strategy: "excludeAll",
|
||||||
|
})
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete("/:webhookId")
|
||||||
|
@ApiOperation({ summary: "Delete a webhook of an event-type" })
|
||||||
|
async deleteEventTypeWebhook(@GetWebhook() webhook: Webhook): Promise<EventTypeWebhookOutputResponseDto> {
|
||||||
|
await this.webhooksService.deleteWebhook(webhook.id);
|
||||||
|
return {
|
||||||
|
status: SUCCESS_STATUS,
|
||||||
|
data: plainToClass(EventTypeWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
|
||||||
|
strategy: "excludeAll",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete("/")
|
||||||
|
@ApiOperation({ summary: "Delete all webhooks of an event-type" })
|
||||||
|
async deleteAllEventTypeWebhooks(
|
||||||
|
@Param("eventTypeId", ParseIntPipe) eventTypeId: number
|
||||||
|
): Promise<DeleteManyWebhooksOutputResponseDto> {
|
||||||
|
const data = await this.eventTypeWebhooksService.deleteAllEventTypeWebhooks(eventTypeId);
|
||||||
|
return { status: SUCCESS_STATUS, data: `${data.count} webhooks deleted` };
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-2
@@ -112,9 +112,16 @@ describe("OAuth Client Users Endpoints", () => {
|
|||||||
|
|
||||||
await profilesRepositoryFixture.create({
|
await profilesRepositoryFixture.create({
|
||||||
uid: "asd-asd",
|
uid: "asd-asd",
|
||||||
username: userEmail,
|
username: platformAdminEmail,
|
||||||
user: { connect: { id: platformAdmin.id } },
|
|
||||||
organization: { connect: { id: organization.id } },
|
organization: { connect: { id: organization.id } },
|
||||||
|
movedFromUser: {
|
||||||
|
connect: {
|
||||||
|
id: platformAdmin.id,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
user: {
|
||||||
|
connect: { id: platformAdmin.id },
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
await app.init();
|
await app.init();
|
||||||
|
|||||||
+2
-1
@@ -6,6 +6,7 @@ import { GetManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-
|
|||||||
import { GetManagedUsersOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/get-managed-users.output";
|
import { GetManagedUsersOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/get-managed-users.output";
|
||||||
import { ManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/managed-user.output";
|
import { ManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/managed-user.output";
|
||||||
import { KeysResponseDto } from "@/modules/oauth-clients/controllers/oauth-flow/responses/KeysResponse.dto";
|
import { KeysResponseDto } from "@/modules/oauth-clients/controllers/oauth-flow/responses/KeysResponse.dto";
|
||||||
|
import { OAuthClientGuard } from "@/modules/oauth-clients/guards/oauth-client-guard";
|
||||||
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
||||||
import { OAuthClientUsersService } from "@/modules/oauth-clients/services/oauth-clients-users.service";
|
import { OAuthClientUsersService } from "@/modules/oauth-clients/services/oauth-clients-users.service";
|
||||||
import { TokensRepository } from "@/modules/tokens/tokens.repository";
|
import { TokensRepository } from "@/modules/tokens/tokens.repository";
|
||||||
@@ -37,7 +38,7 @@ import { Pagination } from "@calcom/platform-types";
|
|||||||
path: "/v2/oauth-clients/:clientId/users",
|
path: "/v2/oauth-clients/:clientId/users",
|
||||||
version: API_VERSIONS_VALUES,
|
version: API_VERSIONS_VALUES,
|
||||||
})
|
})
|
||||||
@UseGuards(ApiAuthGuard)
|
@UseGuards(ApiAuthGuard, OAuthClientGuard)
|
||||||
@DocsTags("Managed users")
|
@DocsTags("Managed users")
|
||||||
export class OAuthClientUsersController {
|
export class OAuthClientUsersController {
|
||||||
private readonly logger = new Logger("UserController");
|
private readonly logger = new Logger("UserController");
|
||||||
|
|||||||
+281
@@ -0,0 +1,281 @@
|
|||||||
|
import { bootstrap } from "@/app";
|
||||||
|
import { AppModule } from "@/app.module";
|
||||||
|
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||||
|
import { TokensModule } from "@/modules/tokens/tokens.module";
|
||||||
|
import { UsersModule } from "@/modules/users/users.module";
|
||||||
|
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||||
|
import { CreateWebhookInputDto, UpdateWebhookInputDto } from "@/modules/webhooks/inputs/webhook.input";
|
||||||
|
import {
|
||||||
|
OAuthClientWebhooksOutputResponseDto,
|
||||||
|
OAuthClientWebhookOutputResponseDto,
|
||||||
|
} from "@/modules/webhooks/outputs/oauth-client-webhook.output";
|
||||||
|
import { INestApplication } from "@nestjs/common";
|
||||||
|
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||||
|
import { Test } from "@nestjs/testing";
|
||||||
|
import * as request from "supertest";
|
||||||
|
import { PlatformBillingRepositoryFixture } from "test/fixtures/repository/billing.repository.fixture";
|
||||||
|
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
||||||
|
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
|
||||||
|
import { OrganizationRepositoryFixture } from "test/fixtures/repository/organization.repository.fixture";
|
||||||
|
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
|
||||||
|
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||||
|
import { WebhookRepositoryFixture } from "test/fixtures/repository/webhooks.repository.fixture";
|
||||||
|
import { withNextAuth } from "test/utils/withNextAuth";
|
||||||
|
|
||||||
|
import { PlatformOAuthClient, Team, Webhook } from "@calcom/prisma/client";
|
||||||
|
|
||||||
|
describe("EventTypes WebhooksController (e2e)", () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
const userEmail = "[email protected]";
|
||||||
|
const otherUserEmail = "[email protected]";
|
||||||
|
let user: UserWithProfile;
|
||||||
|
let otherUser: UserWithProfile;
|
||||||
|
let oAuthClient: PlatformOAuthClient;
|
||||||
|
let otherOAuthClient: PlatformOAuthClient;
|
||||||
|
let org: Team;
|
||||||
|
let otherOrg: Team;
|
||||||
|
let oAuthClientRepositoryFixture: OAuthClientRepositoryFixture;
|
||||||
|
let userRepositoryFixture: UserRepositoryFixture;
|
||||||
|
let webhookRepositoryFixture: WebhookRepositoryFixture;
|
||||||
|
let otherOAuthClientWebhook: Webhook;
|
||||||
|
let membershipRepositoryFixture: MembershipRepositoryFixture;
|
||||||
|
let profileRepositoryFixture: ProfileRepositoryFixture;
|
||||||
|
let orgRepositoryFixture: OrganizationRepositoryFixture;
|
||||||
|
let platformBillingRepositoryFixture: PlatformBillingRepositoryFixture;
|
||||||
|
|
||||||
|
let webhook: OAuthClientWebhookOutputResponseDto["data"];
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleRef = await withNextAuth(
|
||||||
|
userEmail,
|
||||||
|
Test.createTestingModule({
|
||||||
|
imports: [AppModule, PrismaModule, UsersModule, TokensModule],
|
||||||
|
})
|
||||||
|
).compile();
|
||||||
|
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||||
|
webhookRepositoryFixture = new WebhookRepositoryFixture(moduleRef);
|
||||||
|
oAuthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
||||||
|
orgRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);
|
||||||
|
platformBillingRepositoryFixture = new PlatformBillingRepositoryFixture(moduleRef);
|
||||||
|
membershipRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
||||||
|
profileRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
||||||
|
user = await userRepositoryFixture.create({
|
||||||
|
email: userEmail,
|
||||||
|
username: userEmail,
|
||||||
|
});
|
||||||
|
otherUser = await userRepositoryFixture.create({
|
||||||
|
email: otherUserEmail,
|
||||||
|
username: otherUserEmail,
|
||||||
|
});
|
||||||
|
|
||||||
|
org = await orgRepositoryFixture.create({
|
||||||
|
name: "apiOrg",
|
||||||
|
isOrganization: true,
|
||||||
|
metadata: {
|
||||||
|
isOrganization: true,
|
||||||
|
orgAutoAcceptEmail: "api.com",
|
||||||
|
isOrganizationVerified: true,
|
||||||
|
isOrganizationConfigured: true,
|
||||||
|
},
|
||||||
|
isPlatform: true,
|
||||||
|
});
|
||||||
|
otherOrg = await orgRepositoryFixture.create({
|
||||||
|
name: "otherOrg",
|
||||||
|
isOrganization: true,
|
||||||
|
metadata: {
|
||||||
|
isOrganization: true,
|
||||||
|
orgAutoAcceptEmail: "api.com",
|
||||||
|
isOrganizationVerified: true,
|
||||||
|
isOrganizationConfigured: true,
|
||||||
|
},
|
||||||
|
isPlatform: true,
|
||||||
|
});
|
||||||
|
await platformBillingRepositoryFixture.create(org.id);
|
||||||
|
await platformBillingRepositoryFixture.create(otherOrg.id);
|
||||||
|
await membershipRepositoryFixture.create({
|
||||||
|
role: "OWNER",
|
||||||
|
user: { connect: { id: user.id } },
|
||||||
|
team: { connect: { id: org.id } },
|
||||||
|
accepted: true,
|
||||||
|
});
|
||||||
|
await membershipRepositoryFixture.create({
|
||||||
|
role: "OWNER",
|
||||||
|
user: { connect: { id: otherUser.id } },
|
||||||
|
team: { connect: { id: otherOrg.id } },
|
||||||
|
accepted: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await profileRepositoryFixture.create({
|
||||||
|
uid: `usr-${user.id}`,
|
||||||
|
username: userEmail,
|
||||||
|
organization: {
|
||||||
|
connect: {
|
||||||
|
id: org.id,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
movedFromUser: {
|
||||||
|
connect: {
|
||||||
|
id: user.id,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
user: {
|
||||||
|
connect: { id: user.id },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await profileRepositoryFixture.create({
|
||||||
|
uid: `usr-${otherUser.id}`,
|
||||||
|
username: otherUserEmail,
|
||||||
|
organization: {
|
||||||
|
connect: {
|
||||||
|
id: otherOrg.id,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
movedFromUser: {
|
||||||
|
connect: {
|
||||||
|
id: otherUser.id,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
user: {
|
||||||
|
connect: { id: otherUser.id },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
logo: "logo-url",
|
||||||
|
name: "name",
|
||||||
|
redirectUris: ["redirect-uri"],
|
||||||
|
permissions: 32,
|
||||||
|
};
|
||||||
|
const secret = "secret";
|
||||||
|
oAuthClient = await oAuthClientRepositoryFixture.create(org.id, data, secret);
|
||||||
|
otherOAuthClient = await oAuthClientRepositoryFixture.create(otherOrg.id, data, secret);
|
||||||
|
otherOAuthClientWebhook = await webhookRepositoryFixture.create({
|
||||||
|
id: "123abc-123abc-123abc-123abc",
|
||||||
|
active: true,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
eventTriggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
platformOAuthClient: { connect: { id: otherOAuthClient.id } },
|
||||||
|
});
|
||||||
|
|
||||||
|
app = moduleRef.createNestApplication();
|
||||||
|
bootstrap(app as NestExpressApplication);
|
||||||
|
|
||||||
|
await app.init();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await userRepositoryFixture.deleteByEmail(user.email);
|
||||||
|
await orgRepositoryFixture.delete(org.id);
|
||||||
|
await userRepositoryFixture.deleteByEmail(otherUser.email);
|
||||||
|
await orgRepositoryFixture.delete(otherOrg.id);
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/webhooks (POST)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.post(`/v2/oauth-clients/${oAuthClient.id}/webhooks`)
|
||||||
|
.send({
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
triggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
active: true,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
} satisfies CreateWebhookInputDto)
|
||||||
|
.expect(201)
|
||||||
|
.then(async (res) => {
|
||||||
|
expect(res.body).toMatchObject({
|
||||||
|
status: "success",
|
||||||
|
data: {
|
||||||
|
id: expect.any(String),
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
active: true,
|
||||||
|
oAuthClientId: oAuthClient.id,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
triggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
},
|
||||||
|
} satisfies OAuthClientWebhookOutputResponseDto);
|
||||||
|
webhook = res.body.data;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/oauth-clients/:oAuthClientId/webhooks/:webhookId (PATCH)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.patch(`/v2/oauth-clients/${oAuthClient.id}/webhooks/${webhook.id}`)
|
||||||
|
.send({
|
||||||
|
active: false,
|
||||||
|
} satisfies UpdateWebhookInputDto)
|
||||||
|
.expect(200)
|
||||||
|
.then((res) => {
|
||||||
|
expect(res.body.data.active).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/oauth-clients/:oAuthClientId/webhooks/:webhookId (GET)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get(`/v2/oauth-clients/${oAuthClient.id}/webhooks/${webhook.id}`)
|
||||||
|
.expect(200)
|
||||||
|
.then((res) => {
|
||||||
|
expect(res.body).toMatchObject({
|
||||||
|
status: "success",
|
||||||
|
data: {
|
||||||
|
id: expect.any(String),
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
triggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
active: false,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
oAuthClientId: oAuthClient.id,
|
||||||
|
},
|
||||||
|
} satisfies OAuthClientWebhookOutputResponseDto);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/oauth-clients/:oAuthClientId/webhooks/:webhookId (GET) should fail to get a webhook that does not exist", () => {
|
||||||
|
return request(app.getHttpServer()).get(`/v2/oauth-clients/${oAuthClient.id}/webhooks/90284`).expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/webhooks (GET)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get(`/v2/oauth-clients/${oAuthClient.id}/webhooks`)
|
||||||
|
.expect(200)
|
||||||
|
.then((res) => {
|
||||||
|
const responseBody = res.body as OAuthClientWebhooksOutputResponseDto;
|
||||||
|
responseBody.data.forEach((webhook) => {
|
||||||
|
expect(webhook.oAuthClientId).toBe(oAuthClient.id);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it("/webhooks (GET) should fail to get webhooks of oauth client that doesn't belong to you", () => {
|
||||||
|
return request(app.getHttpServer()).get(`/v2/oauth-clients/${otherOAuthClient.id}/webhooks`).expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/oauth-clients/:oAuthClientId/webhooks/:webhookId (DELETE)", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.delete(`/v2/oauth-clients/${oAuthClient.id}/webhooks/${webhook.id}`)
|
||||||
|
.expect(200)
|
||||||
|
.then((res) => {
|
||||||
|
expect(res.body).toMatchObject({
|
||||||
|
status: "success",
|
||||||
|
data: {
|
||||||
|
id: expect.any(String),
|
||||||
|
subscriberUrl: "https://example.com",
|
||||||
|
triggers: ["BOOKING_CREATED", "BOOKING_RESCHEDULED", "BOOKING_CANCELLED"],
|
||||||
|
active: false,
|
||||||
|
payloadTemplate: "string",
|
||||||
|
oAuthClientId: oAuthClient.id,
|
||||||
|
},
|
||||||
|
} satisfies OAuthClientWebhookOutputResponseDto);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/oauth-clients/:oAuthClientId/webhooks/:webhookId (DELETE) should fail to delete webhooks of an oauth client that doesn't belong to you", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.delete(`/v2/oauth-clients/${otherOAuthClient.id}/webhooks/${otherOAuthClientWebhook.id}`)
|
||||||
|
.expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/oauth-clients/:oAuthClientId/webhooks/:webhookId (DELETE) shoud fail to delete a webhook that does not exist", () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.delete(`/v2/oauth-clients/${oAuthClient.id}/webhooks/1234453`)
|
||||||
|
.expect(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
+140
@@ -0,0 +1,140 @@
|
|||||||
|
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
|
||||||
|
import { MembershipRoles } from "@/modules/auth/decorators/roles/membership-roles.decorator";
|
||||||
|
import { NextAuthGuard } from "@/modules/auth/guards/next-auth/next-auth.guard";
|
||||||
|
import { OrganizationRolesGuard } from "@/modules/auth/guards/organization-roles/organization-roles.guard";
|
||||||
|
import { GetWebhook } from "@/modules/webhooks/decorators/get-webhook-decorator";
|
||||||
|
import { IsOAuthClientWebhookGuard } from "@/modules/webhooks/guards/is-oauth-client-webhook-guard";
|
||||||
|
import { CreateWebhookInputDto, UpdateWebhookInputDto } from "@/modules/webhooks/inputs/webhook.input";
|
||||||
|
import {
|
||||||
|
OAuthClientWebhookOutputResponseDto,
|
||||||
|
OAuthClientWebhookOutputDto,
|
||||||
|
OAuthClientWebhooksOutputResponseDto,
|
||||||
|
} from "@/modules/webhooks/outputs/oauth-client-webhook.output";
|
||||||
|
import { DeleteManyWebhooksOutputResponseDto } from "@/modules/webhooks/outputs/webhook.output";
|
||||||
|
import { PartialWebhookInputPipe, WebhookInputPipe } from "@/modules/webhooks/pipes/WebhookInputPipe";
|
||||||
|
import { WebhookOutputPipe } from "@/modules/webhooks/pipes/WebhookOutputPipe";
|
||||||
|
import { OAuthClientWebhooksService } from "@/modules/webhooks/services/oauth-clients-webhooks.service";
|
||||||
|
import { WebhooksService } from "@/modules/webhooks/services/webhooks.service";
|
||||||
|
import { Controller, Post, Body, UseGuards, Get, Param, Query, Delete, Patch } from "@nestjs/common";
|
||||||
|
import { ApiOperation, ApiTags } from "@nestjs/swagger";
|
||||||
|
import { Webhook, MembershipRole } from "@prisma/client";
|
||||||
|
import { plainToClass } from "class-transformer";
|
||||||
|
|
||||||
|
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||||
|
import { SkipTakePagination } from "@calcom/platform-types";
|
||||||
|
|
||||||
|
import { OAuthClientGuard } from "../../guards/oauth-client-guard";
|
||||||
|
|
||||||
|
@Controller({
|
||||||
|
path: "/v2/oauth-clients/:clientId/webhooks",
|
||||||
|
version: API_VERSIONS_VALUES,
|
||||||
|
})
|
||||||
|
@UseGuards(NextAuthGuard, OrganizationRolesGuard, OAuthClientGuard)
|
||||||
|
@ApiTags("OAuthClients Webhooks")
|
||||||
|
export class OAuthClientWebhooksController {
|
||||||
|
constructor(
|
||||||
|
private readonly webhooksService: WebhooksService,
|
||||||
|
private readonly oAuthClientWebhooksService: OAuthClientWebhooksService
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Post("/")
|
||||||
|
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER])
|
||||||
|
@ApiOperation({ summary: "Create a webhook for an oAuthClient" })
|
||||||
|
async createOAuthClientWebhook(
|
||||||
|
@Body() body: CreateWebhookInputDto,
|
||||||
|
@Param("clientId") oAuthClientId: string
|
||||||
|
): Promise<OAuthClientWebhookOutputResponseDto> {
|
||||||
|
const webhook = await this.oAuthClientWebhooksService.createOAuthClientWebhook(
|
||||||
|
oAuthClientId,
|
||||||
|
new WebhookInputPipe().transform(body)
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
status: SUCCESS_STATUS,
|
||||||
|
data: plainToClass(OAuthClientWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
|
||||||
|
strategy: "excludeAll",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch("/:webhookId")
|
||||||
|
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER])
|
||||||
|
@ApiOperation({ summary: "Update a webhook of an oAuthClient" })
|
||||||
|
@UseGuards(IsOAuthClientWebhookGuard)
|
||||||
|
async updateOAuthClientWebhook(
|
||||||
|
@Body() body: UpdateWebhookInputDto,
|
||||||
|
@Param("webhookId") webhookId: string
|
||||||
|
): Promise<OAuthClientWebhookOutputResponseDto> {
|
||||||
|
const webhook = await this.webhooksService.updateWebhook(
|
||||||
|
webhookId,
|
||||||
|
new PartialWebhookInputPipe().transform(body)
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
status: SUCCESS_STATUS,
|
||||||
|
data: plainToClass(OAuthClientWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
|
||||||
|
strategy: "excludeAll",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("/:webhookId")
|
||||||
|
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER])
|
||||||
|
@ApiOperation({ summary: "Get a webhook of an oAuthClient" })
|
||||||
|
@UseGuards(IsOAuthClientWebhookGuard)
|
||||||
|
async getOAuthClientWebhook(@GetWebhook() webhook: Webhook): Promise<OAuthClientWebhookOutputResponseDto> {
|
||||||
|
return {
|
||||||
|
status: SUCCESS_STATUS,
|
||||||
|
data: plainToClass(OAuthClientWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
|
||||||
|
strategy: "excludeAll",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("/")
|
||||||
|
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER])
|
||||||
|
@ApiOperation({ summary: "Get all webhooks of an oAuthClient" })
|
||||||
|
async getOAuthClientWebhooks(
|
||||||
|
@Param("clientId") oAuthClientId: string,
|
||||||
|
@Query() pagination: SkipTakePagination
|
||||||
|
): Promise<OAuthClientWebhooksOutputResponseDto> {
|
||||||
|
const webhooks = await this.oAuthClientWebhooksService.getOAuthClientWebhooksPaginated(
|
||||||
|
oAuthClientId,
|
||||||
|
pagination.skip ?? 0,
|
||||||
|
pagination.take ?? 250
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
status: SUCCESS_STATUS,
|
||||||
|
data: webhooks.map((webhook) =>
|
||||||
|
plainToClass(OAuthClientWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
|
||||||
|
strategy: "excludeAll",
|
||||||
|
})
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete("/:webhookId")
|
||||||
|
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER])
|
||||||
|
@ApiOperation({ summary: "Delete a webhook of an oAuthClient" })
|
||||||
|
@UseGuards(IsOAuthClientWebhookGuard)
|
||||||
|
async deleteOAuthClientWebhook(
|
||||||
|
@GetWebhook() webhook: Webhook
|
||||||
|
): Promise<OAuthClientWebhookOutputResponseDto> {
|
||||||
|
await this.webhooksService.deleteWebhook(webhook.id);
|
||||||
|
return {
|
||||||
|
status: SUCCESS_STATUS,
|
||||||
|
data: plainToClass(OAuthClientWebhookOutputDto, new WebhookOutputPipe().transform(webhook), {
|
||||||
|
strategy: "excludeAll",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete("/")
|
||||||
|
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER])
|
||||||
|
@ApiOperation({ summary: "Delete all webhooks of an oAuthClient" })
|
||||||
|
async deleteAllOAuthClientWebhooks(
|
||||||
|
@Param("clientId") oAuthClientId: string
|
||||||
|
): Promise<DeleteManyWebhooksOutputResponseDto> {
|
||||||
|
const data = await this.oAuthClientWebhooksService.deleteAllOAuthClientWebhooks(oAuthClientId);
|
||||||
|
return { status: SUCCESS_STATUS, data: `${data.count} webhooks deleted` };
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-2
@@ -9,6 +9,7 @@ import { ManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-cli
|
|||||||
import { CreateOAuthClientResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/CreateOAuthClientResponse.dto";
|
import { CreateOAuthClientResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/CreateOAuthClientResponse.dto";
|
||||||
import { GetOAuthClientResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/GetOAuthClientResponse.dto";
|
import { GetOAuthClientResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/GetOAuthClientResponse.dto";
|
||||||
import { GetOAuthClientsResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/GetOAuthClientsResponse.dto";
|
import { GetOAuthClientsResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/GetOAuthClientsResponse.dto";
|
||||||
|
import { OAuthClientGuard } from "@/modules/oauth-clients/guards/oauth-client-guard";
|
||||||
import { UpdateOAuthClientInput } from "@/modules/oauth-clients/inputs/update-oauth-client.input";
|
import { UpdateOAuthClientInput } from "@/modules/oauth-clients/inputs/update-oauth-client.input";
|
||||||
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
||||||
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
|
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
|
||||||
@@ -36,8 +37,7 @@ import {
|
|||||||
ApiOperation as DocsOperation,
|
ApiOperation as DocsOperation,
|
||||||
ApiCreatedResponse as DocsCreatedResponse,
|
ApiCreatedResponse as DocsCreatedResponse,
|
||||||
} from "@nestjs/swagger";
|
} from "@nestjs/swagger";
|
||||||
import { MembershipRole } from "@prisma/client";
|
import { User, MembershipRole } from "@prisma/client";
|
||||||
import { User } from "@prisma/client";
|
|
||||||
|
|
||||||
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||||
import { CreateOAuthClientInput } from "@calcom/platform-types";
|
import { CreateOAuthClientInput } from "@calcom/platform-types";
|
||||||
@@ -85,6 +85,7 @@ export class OAuthClientsController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const { id, secret } = await this.oauthClientRepository.createOAuthClient(organizationId, body);
|
const { id, secret } = await this.oauthClientRepository.createOAuthClient(organizationId, body);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
status: SUCCESS_STATUS,
|
status: SUCCESS_STATUS,
|
||||||
data: {
|
data: {
|
||||||
@@ -109,11 +110,13 @@ export class OAuthClientsController {
|
|||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER])
|
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER])
|
||||||
@DocsOperation({ description: AUTH_DOCUMENTATION })
|
@DocsOperation({ description: AUTH_DOCUMENTATION })
|
||||||
|
@UseGuards(OAuthClientGuard)
|
||||||
async getOAuthClientById(@Param("clientId") clientId: string): Promise<GetOAuthClientResponseDto> {
|
async getOAuthClientById(@Param("clientId") clientId: string): Promise<GetOAuthClientResponseDto> {
|
||||||
const client = await this.oauthClientRepository.getOAuthClient(clientId);
|
const client = await this.oauthClientRepository.getOAuthClient(clientId);
|
||||||
if (!client) {
|
if (!client) {
|
||||||
throw new NotFoundException(`OAuth client with ID ${clientId} not found`);
|
throw new NotFoundException(`OAuth client with ID ${clientId} not found`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { status: SUCCESS_STATUS, data: client };
|
return { status: SUCCESS_STATUS, data: client };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,6 +124,7 @@ export class OAuthClientsController {
|
|||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER])
|
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER])
|
||||||
@DocsOperation({ description: AUTH_DOCUMENTATION })
|
@DocsOperation({ description: AUTH_DOCUMENTATION })
|
||||||
|
@UseGuards(OAuthClientGuard)
|
||||||
async getOAuthClientManagedUsersById(
|
async getOAuthClientManagedUsersById(
|
||||||
@Param("clientId") clientId: string,
|
@Param("clientId") clientId: string,
|
||||||
@Query() queryParams: Pagination
|
@Query() queryParams: Pagination
|
||||||
@@ -139,12 +143,14 @@ export class OAuthClientsController {
|
|||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER])
|
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER])
|
||||||
@DocsOperation({ description: AUTH_DOCUMENTATION })
|
@DocsOperation({ description: AUTH_DOCUMENTATION })
|
||||||
|
@UseGuards(OAuthClientGuard)
|
||||||
async updateOAuthClient(
|
async updateOAuthClient(
|
||||||
@Param("clientId") clientId: string,
|
@Param("clientId") clientId: string,
|
||||||
@Body() body: UpdateOAuthClientInput
|
@Body() body: UpdateOAuthClientInput
|
||||||
): Promise<GetOAuthClientResponseDto> {
|
): Promise<GetOAuthClientResponseDto> {
|
||||||
this.logger.log(`For client ${clientId} updating OAuth Client with data: ${JSON.stringify(body)}`);
|
this.logger.log(`For client ${clientId} updating OAuth Client with data: ${JSON.stringify(body)}`);
|
||||||
const client = await this.oauthClientRepository.updateOAuthClient(clientId, body);
|
const client = await this.oauthClientRepository.updateOAuthClient(clientId, body);
|
||||||
|
|
||||||
return { status: SUCCESS_STATUS, data: client };
|
return { status: SUCCESS_STATUS, data: client };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,6 +158,7 @@ export class OAuthClientsController {
|
|||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER])
|
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER])
|
||||||
@DocsOperation({ description: AUTH_DOCUMENTATION })
|
@DocsOperation({ description: AUTH_DOCUMENTATION })
|
||||||
|
@UseGuards(OAuthClientGuard)
|
||||||
async deleteOAuthClient(@Param("clientId") clientId: string): Promise<GetOAuthClientResponseDto> {
|
async deleteOAuthClient(@Param("clientId") clientId: string): Promise<GetOAuthClientResponseDto> {
|
||||||
this.logger.log(`Deleting OAuth Client with ID: ${clientId}`);
|
this.logger.log(`Deleting OAuth Client with ID: ${clientId}`);
|
||||||
const client = await this.oauthClientRepository.deleteOAuthClient(clientId);
|
const client = await this.oauthClientRepository.deleteOAuthClient(clientId);
|
||||||
|
|||||||
+4
-2
@@ -15,6 +15,7 @@ import { Test, TestingModule } from "@nestjs/testing";
|
|||||||
import { PlatformOAuthClient, Team, User } from "@prisma/client";
|
import { PlatformOAuthClient, Team, User } from "@prisma/client";
|
||||||
import * as request from "supertest";
|
import * as request from "supertest";
|
||||||
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
|
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
|
||||||
|
import { OrganizationRepositoryFixture } from "test/fixtures/repository/organization.repository.fixture";
|
||||||
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
|
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
|
||||||
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
|
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
|
||||||
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||||
@@ -57,7 +58,7 @@ describe("OAuthFlow Endpoints", () => {
|
|||||||
let app: INestApplication;
|
let app: INestApplication;
|
||||||
|
|
||||||
let usersRepositoryFixtures: UserRepositoryFixture;
|
let usersRepositoryFixtures: UserRepositoryFixture;
|
||||||
let organizationsRepositoryFixture: TeamRepositoryFixture;
|
let organizationsRepositoryFixture: OrganizationRepositoryFixture;
|
||||||
let oAuthClientsRepositoryFixture: OAuthClientRepositoryFixture;
|
let oAuthClientsRepositoryFixture: OAuthClientRepositoryFixture;
|
||||||
let profilesRepositoryFixture: ProfileRepositoryFixture;
|
let profilesRepositoryFixture: ProfileRepositoryFixture;
|
||||||
|
|
||||||
@@ -83,7 +84,7 @@ describe("OAuthFlow Endpoints", () => {
|
|||||||
await app.init();
|
await app.init();
|
||||||
|
|
||||||
oAuthClientsRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
oAuthClientsRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
||||||
organizationsRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);
|
||||||
usersRepositoryFixtures = new UserRepositoryFixture(moduleRef);
|
usersRepositoryFixtures = new UserRepositoryFixture(moduleRef);
|
||||||
profilesRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
profilesRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
||||||
|
|
||||||
@@ -96,6 +97,7 @@ describe("OAuthFlow Endpoints", () => {
|
|||||||
uid: "asd-asd",
|
uid: "asd-asd",
|
||||||
username: userEmail,
|
username: userEmail,
|
||||||
user: { connect: { id: user.id } },
|
user: { connect: { id: user.id } },
|
||||||
|
movedFromUser: { connect: { id: user.id } },
|
||||||
organization: { connect: { id: organization.id } },
|
organization: { connect: { id: organization.id } },
|
||||||
});
|
});
|
||||||
oAuthClient = await createOAuthClient(organization.id);
|
oAuthClient = await createOAuthClient(organization.id);
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { GetUserReturnType } from "@/modules/auth/decorators/get-user/get-user.decorator";
|
||||||
|
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
||||||
|
import {
|
||||||
|
Injectable,
|
||||||
|
CanActivate,
|
||||||
|
ExecutionContext,
|
||||||
|
ForbiddenException,
|
||||||
|
NotFoundException,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import { Request } from "express";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class OAuthClientGuard implements CanActivate {
|
||||||
|
constructor(private oAuthClientRepository: OAuthClientRepository) {}
|
||||||
|
|
||||||
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
|
const request = context.switchToHttp().getRequest<Request & { user: GetUserReturnType }>();
|
||||||
|
const user: GetUserReturnType = request.user;
|
||||||
|
const organizationId = user?.movedToProfile?.organizationId || user?.organizationId;
|
||||||
|
const oAuthClientId = request.params.clientId;
|
||||||
|
|
||||||
|
if (!oAuthClientId) {
|
||||||
|
throw new ForbiddenException("No OAuth client associated with the request.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user || !organizationId) {
|
||||||
|
throw new ForbiddenException("No organization associated with the user.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const oAuthClient = await this.oAuthClientRepository.getOAuthClient(oAuthClientId);
|
||||||
|
|
||||||
|
if (!oAuthClient) {
|
||||||
|
throw new NotFoundException("OAuth client not found.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Boolean(user.isSystemAdmin || oAuthClient.organizationId === organizationId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,7 +8,7 @@ import { UsersRepository } from "@/modules/users/users.repository";
|
|||||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||||
import { User } from "@prisma/client";
|
import { User } from "@prisma/client";
|
||||||
|
|
||||||
import { createNewUsersConnectToOrgIfExists, slugify } from "@calcom/platform-libraries-0.0.22";
|
import { createNewUsersConnectToOrgIfExists, slugify } from "@calcom/platform-libraries";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class OAuthClientUsersService {
|
export class OAuthClientUsersService {
|
||||||
|
|||||||
+7
-6
@@ -4,6 +4,7 @@ import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
|
|||||||
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";
|
||||||
|
import { IsAdminAPIEnabledGuard } from "@/modules/auth/guards/organizations/is-admin-api-enabled.guard";
|
||||||
import { IsOrgGuard } from "@/modules/auth/guards/organizations/is-org.guard";
|
import { IsOrgGuard } from "@/modules/auth/guards/organizations/is-org.guard";
|
||||||
import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard";
|
import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard";
|
||||||
import { IsTeamInOrg } from "@/modules/auth/guards/teams/is-team-in-org.guard";
|
import { IsTeamInOrg } from "@/modules/auth/guards/teams/is-team-in-org.guard";
|
||||||
@@ -49,7 +50,7 @@ export class OrganizationsEventTypesController {
|
|||||||
|
|
||||||
@Roles("TEAM_ADMIN")
|
@Roles("TEAM_ADMIN")
|
||||||
@PlatformPlan("ESSENTIALS")
|
@PlatformPlan("ESSENTIALS")
|
||||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard)
|
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||||
@Post("/teams/:teamId/event-types")
|
@Post("/teams/:teamId/event-types")
|
||||||
async createTeamEventType(
|
async createTeamEventType(
|
||||||
@GetUser() user: UserWithProfile,
|
@GetUser() user: UserWithProfile,
|
||||||
@@ -72,7 +73,7 @@ export class OrganizationsEventTypesController {
|
|||||||
|
|
||||||
@Roles("TEAM_ADMIN")
|
@Roles("TEAM_ADMIN")
|
||||||
@PlatformPlan("ESSENTIALS")
|
@PlatformPlan("ESSENTIALS")
|
||||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard)
|
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||||
@Get("/teams/:teamId/event-types/:eventTypeId")
|
@Get("/teams/:teamId/event-types/:eventTypeId")
|
||||||
async getTeamEventType(
|
async getTeamEventType(
|
||||||
@Param("teamId", ParseIntPipe) teamId: number,
|
@Param("teamId", ParseIntPipe) teamId: number,
|
||||||
@@ -90,7 +91,7 @@ export class OrganizationsEventTypesController {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@UseGuards(IsOrgGuard, IsTeamInOrg)
|
@UseGuards(IsOrgGuard, IsTeamInOrg, IsAdminAPIEnabledGuard)
|
||||||
@Get("/teams/:teamId/event-types")
|
@Get("/teams/:teamId/event-types")
|
||||||
async getTeamEventTypes(
|
async getTeamEventTypes(
|
||||||
@Param("teamId", ParseIntPipe) teamId: number,
|
@Param("teamId", ParseIntPipe) teamId: number,
|
||||||
@@ -116,7 +117,7 @@ export class OrganizationsEventTypesController {
|
|||||||
|
|
||||||
@Roles("TEAM_ADMIN")
|
@Roles("TEAM_ADMIN")
|
||||||
@PlatformPlan("ESSENTIALS")
|
@PlatformPlan("ESSENTIALS")
|
||||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, PlatformPlanGuard)
|
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||||
@Get("/teams/event-types")
|
@Get("/teams/event-types")
|
||||||
async getTeamsEventTypes(
|
async getTeamsEventTypes(
|
||||||
@Param("orgId", ParseIntPipe) orgId: number,
|
@Param("orgId", ParseIntPipe) orgId: number,
|
||||||
@@ -133,7 +134,7 @@ export class OrganizationsEventTypesController {
|
|||||||
|
|
||||||
@Roles("TEAM_ADMIN")
|
@Roles("TEAM_ADMIN")
|
||||||
@PlatformPlan("ESSENTIALS")
|
@PlatformPlan("ESSENTIALS")
|
||||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard)
|
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||||
@Patch("/teams/:teamId/event-types/:eventTypeId")
|
@Patch("/teams/:teamId/event-types/:eventTypeId")
|
||||||
async updateTeamEventType(
|
async updateTeamEventType(
|
||||||
@Param("teamId", ParseIntPipe) teamId: number,
|
@Param("teamId", ParseIntPipe) teamId: number,
|
||||||
@@ -156,7 +157,7 @@ export class OrganizationsEventTypesController {
|
|||||||
|
|
||||||
@Roles("TEAM_ADMIN")
|
@Roles("TEAM_ADMIN")
|
||||||
@PlatformPlan("ESSENTIALS")
|
@PlatformPlan("ESSENTIALS")
|
||||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard)
|
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||||
@Delete("/teams/:teamId/event-types/:eventTypeId")
|
@Delete("/teams/:teamId/event-types/:eventTypeId")
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async deleteTeamEventType(
|
async deleteTeamEventType(
|
||||||
|
|||||||
+3
-2
@@ -10,6 +10,7 @@ import { User } from "@prisma/client";
|
|||||||
import * as request from "supertest";
|
import * as request from "supertest";
|
||||||
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
|
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
|
||||||
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
||||||
|
import { OrganizationRepositoryFixture } from "test/fixtures/repository/organization.repository.fixture";
|
||||||
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
|
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
|
||||||
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
|
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
|
||||||
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||||
@@ -30,7 +31,7 @@ describe("Organizations Event Types Endpoints", () => {
|
|||||||
let app: INestApplication;
|
let app: INestApplication;
|
||||||
|
|
||||||
let userRepositoryFixture: UserRepositoryFixture;
|
let userRepositoryFixture: UserRepositoryFixture;
|
||||||
let organizationsRepositoryFixture: TeamRepositoryFixture;
|
let organizationsRepositoryFixture: OrganizationRepositoryFixture;
|
||||||
let teamsRepositoryFixture: TeamRepositoryFixture;
|
let teamsRepositoryFixture: TeamRepositoryFixture;
|
||||||
let membershipsRepositoryFixture: MembershipRepositoryFixture;
|
let membershipsRepositoryFixture: MembershipRepositoryFixture;
|
||||||
let profileRepositoryFixture: ProfileRepositoryFixture;
|
let profileRepositoryFixture: ProfileRepositoryFixture;
|
||||||
@@ -63,7 +64,7 @@ describe("Organizations Event Types Endpoints", () => {
|
|||||||
).compile();
|
).compile();
|
||||||
|
|
||||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||||
organizationsRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);
|
||||||
teamsRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
teamsRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
||||||
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
||||||
profileRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
profileRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
||||||
|
|||||||
+5
-4
@@ -11,6 +11,7 @@ import { Test } from "@nestjs/testing";
|
|||||||
import { User } from "@prisma/client";
|
import { User } from "@prisma/client";
|
||||||
import * as request from "supertest";
|
import * as request from "supertest";
|
||||||
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
||||||
|
import { OrganizationRepositoryFixture } from "test/fixtures/repository/organization.repository.fixture";
|
||||||
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
|
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
|
||||||
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||||
import { withApiAuth } from "test/utils/withApiAuth";
|
import { withApiAuth } from "test/utils/withApiAuth";
|
||||||
@@ -24,7 +25,7 @@ describe("Organizations Memberships Endpoints", () => {
|
|||||||
let app: INestApplication;
|
let app: INestApplication;
|
||||||
|
|
||||||
let userRepositoryFixture: UserRepositoryFixture;
|
let userRepositoryFixture: UserRepositoryFixture;
|
||||||
let organizationsRepositoryFixture: TeamRepositoryFixture;
|
let organizationsRepositoryFixture: OrganizationRepositoryFixture;
|
||||||
let membershipsRepositoryFixture: MembershipRepositoryFixture;
|
let membershipsRepositoryFixture: MembershipRepositoryFixture;
|
||||||
|
|
||||||
let org: Team;
|
let org: Team;
|
||||||
@@ -51,7 +52,7 @@ describe("Organizations Memberships Endpoints", () => {
|
|||||||
).compile();
|
).compile();
|
||||||
|
|
||||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||||
organizationsRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);
|
||||||
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
||||||
|
|
||||||
user = await userRepositoryFixture.create({
|
user = await userRepositoryFixture.create({
|
||||||
@@ -210,7 +211,7 @@ describe("Organizations Memberships Endpoints", () => {
|
|||||||
let app: INestApplication;
|
let app: INestApplication;
|
||||||
|
|
||||||
let userRepositoryFixture: UserRepositoryFixture;
|
let userRepositoryFixture: UserRepositoryFixture;
|
||||||
let organizationsRepositoryFixture: TeamRepositoryFixture;
|
let organizationsRepositoryFixture: OrganizationRepositoryFixture;
|
||||||
let membershipsRepositoryFixture: MembershipRepositoryFixture;
|
let membershipsRepositoryFixture: MembershipRepositoryFixture;
|
||||||
|
|
||||||
let org: Team;
|
let org: Team;
|
||||||
@@ -228,7 +229,7 @@ describe("Organizations Memberships Endpoints", () => {
|
|||||||
).compile();
|
).compile();
|
||||||
|
|
||||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||||
organizationsRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);
|
||||||
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
||||||
|
|
||||||
user = await userRepositoryFixture.create({
|
user = await userRepositoryFixture.create({
|
||||||
|
|||||||
Loaded 100 of 592 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user