Compare commits

...
Author SHA1 Message Date
emrysal 5854de3c23 chore: release v5.5.0
Post release / release (push) Canceled after 0s
2025-07-15 09:57:23 +00:00
Eunjae LeeandDevin AI 967442892a feat: convert InsightsBookingService to use Prisma.sql raw queries (#22345)
* fix: use raw query at InsightsBookingService

* feat: convert InsightsBookingService to use Prisma.sql raw queries

- Convert auth conditions from Prisma object notation to Prisma.sql
- Convert filter conditions from Prisma object notation to Prisma.sql
- Update return types from Prisma.BookingTimeStatusDenormalizedWhereInput to Prisma.Sql
- Fix type error in isOrgOwnerOrAdmin method
- Follow same pattern as InsightsRoutingService conversion

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* feat: convert InsightsBookingService to use Prisma.sql raw queries

- Convert auth conditions from Prisma object notation to Prisma.sql
- Convert filter conditions from Prisma object notation to Prisma.sql
- Update return types from Prisma.BookingTimeStatusDenormalizedWhereInput to Prisma.Sql
- Fix type error in isOrgOwnerOrAdmin method
- Follow same pattern as InsightsRoutingService conversion

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: update InsightsBookingService integration tests for Prisma.sql format

- Replace Prisma object notation expectations with Prisma.sql template literals
- Add NOTHING_CONDITION constant for consistency with InsightsRoutingService
- Update all test cases to use direct Prisma.sql comparisons
- Use $queryRaw for actual database integration testing
- Follow same testing patterns as InsightsRoutingService

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: exclude intentionally skipped jobs from required CI check failure

- Remove 'skipped' from failure condition in pr.yml and all-checks.yml
- Allow E2E jobs to be skipped without failing the required check
- Only actual failures and cancelled jobs will cause required check to fail

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix tests

* Revert "fix: exclude intentionally skipped jobs from required CI check failure"

This reverts commit 6ff44fc9a8f14ad657f7bba7c2e454e192b66c8f.

* clean up tests

* address feedback

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-07-15 11:09:06 +02:00
Omar LópezandDevin AI 202d248ae4 fix: resolve unique constraint violations in listWithTeam integration test (#22493)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-07-15 07:51:51 +05:30
Hariom Balhara f667417d84 test: Add e2e for prerendering headless router with attribute routing (#22080)
* test: Add e2e for prerender

* wip

* fix tests

* conflict resolution

* Fix unit tests and e2e failure

* chore: Reorganize
2025-07-14 22:47:12 -03:00
emrysal 750e6315dc chore: release v5.4.20
Post release / release (push) Canceled after 0s
2025-07-15 00:37:37 +00:00
Omar LópezandDevin AI f117b2df32 fix: CalDAV credential verification between multiple instances (#22331)
Co-authored-by: zomars@cal.com <zomars@me.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-07-15 01:32:52 +01:00
Omar López 9631f083b8 Revert "feat: add race condition test for calendar-cache-serve booking flow (…" (#22507) 2025-07-14 16:58:19 -07:00
Benny Joo c8a52b78e1 Revert "refactor: replace i18n HTTP requests with build-time bundling (#22422)" (#22496)
This reverts commit 163c7ff791.
2025-07-14 22:49:25 +00:00
Parteek malik fe4946a269 fix: added custom filter for time select (#21717)
* added custom filter

* handling spaces
2025-07-14 20:39:07 +00:00
Anik Dhabal Babu 3de9c2bda0 fix: uncheck requires Confirmation For FreeEmail (#22486) 2025-07-14 16:30:11 +00:00
cee30c53b8 feat: remove Event Types from team settings navigation (#22472)
- Remove VerticalTabItem for Event Types from team settings sidebar
- Event Types link no longer appears in team settings navigation
- Other team settings options remain unchanged and functional

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-07-14 15:51:27 +00:00
randAnik Dhabal Babu f22b5d9daa Fix typo "{l" in event-type causing syntax error (#22474)
* Fix typo "{l" in event-type causing syntax error

* Update event-type.mdx

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-07-14 15:51:07 +00:00
88f8753329 feat: make Members tab open in new tab with external link icon (#22471)
- Add isExternalLink: true to Members tab configuration
- Change href to full URL https://app.cal.com/settings/organizations/i/members
- VerticalTabItem component will automatically show external link icon and open in new tab

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-07-14 21:14:09 +05:30
Lauris Skraucis fe02a97fa1 fix: increase v2 e2e instance size (#22481) 2025-07-14 15:29:18 +00:00
a9172fd832 feat: added cancelled by to booking detail view (#18521)
* feat: added cancelled by to booking detail view

* fix: var naming

* handled case for guest user

* move cancelled by outside reason

* Update bookings-single-view.tsx

* Update apps/web/modules/bookings/views/bookings-single-view.tsx

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: Kartik Saini <41051387+kart1ka@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: unknown <adhabal2002@gmail.com>
2025-07-14 15:15:38 +00:00
Lauris Skraucis 96a659ae5a feat: v2 managed orgs filters (#22420)
* fix: don't allow managed orgs with same slug

* feat: filter managed orgs by slug or metadata

* test

* fix: tests
2025-07-14 16:37:15 +02:00
Anik Dhabal Babu 13739dabd8 Revert "feat: Add cancelledBy input to cancellation page (#18770)" (#22479)
This reverts commit 2838053ba8.
2025-07-14 13:13:27 +00:00
Ashish manhas 22acfbae28 fix(ui): interpolate appName in invalid_credential message (#22448) 2025-07-14 10:37:48 +00:00
Lauris Skraucis adf50b2419 docs: v2 workflows and disable on prefill booking fields (#22445)
* wip

* docs: booking fields prefilling

* docs: wofklows

* fix: guests docs
2025-07-14 15:16:21 +05:30
Lauris Skraucis 35022a0478 fix: get v2/calendars existing record conflict (#22286)
* refactor: upsert destination calendar

* test: v2 connected calendars

* chore: bump libraries

* refactor: have only createIfNotExistsForUser

* refactor: exclude eventTypeId from user calendar search

* chore: bump libraries
2025-07-14 08:01:43 +00:00
2838053ba8 feat: Add cancelledBy input to cancellation page (#18770)
* feat: Add cancelledBy input to cancellation page

* fix: Update email verification error message

* Update safe-parse.ts

* fix: check attendees and booking owner email

* fix: minor ui

* Update CancelBooking.tsx

* Update common.json

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: Kartik Saini <41051387+kart1ka@users.noreply.github.com>
2025-07-14 07:14:18 +00:00
Benny Joo 66397a6626 fix: translation bundler logic (#22459)
* fix logic in translationBundler

* remove tsnode
2025-07-14 02:09:23 +00:00
Omar LópezandDevin AI dfe997dce2 feat: add race condition test for calendar-cache-serve booking flow (#22401)
Co-authored-by: zomars@cal.com <zomars@me.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-07-13 20:37:22 +05:30
163c7ff791 refactor: replace i18n HTTP requests with build-time bundling (#22422)
* refactor: replace i18n HTTP requests with build-time bundling

- Create translationBundler.ts for build-time translation loading
- Replace HTTP fetch in loadTranslations with file system reads
- Add CalComVersion cache invalidation to prevent stale translations
- Fix TypeScript errors in booking page components
- Eliminate 60s timeout issues by removing network dependency

Resolves translation timeout issues by bundling translations at build time
instead of making runtime HTTP requests to /static/locales/ endpoints.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: move i18n files back to packages/lib/server with proper imports

- Move i18n.ts and translationBundler.ts back to packages/lib/server/
- Replace all relative imports with @calcom/lib/server/i18n pattern
- Fix LOCALES_PATH to point to correct directory
- Maintain optimized serverless-friendly translation loading

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* refactor: move locale files to packages/lib/server to eliminate circular deps

- Move all locale files from apps/web/public/static/locales to packages/lib/server/locales
- Create copy-locales-static.js script to copy files during build
- Update all references to use new location for build-time access
- Maintain public folder copying for Next.js runtime access
- Update platform atoms, scripts, and config files
- Fix copy script relative path issue

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: update test imports after locale refactor

- Fix import paths in test files updated by pre-commit hooks
- Ensure all tests use correct locale import paths

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: revert import paths from @calcom/web/lib/i18n to @calcom/lib/server/i18n

- Revert all test file imports back to @calcom/lib/server/i18n as requested
- Addresses GitHub comment feedback to stick with packages/lib/server location
- Fixes import paths in 6 test files that were incorrectly changed

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: update vite config alias to use new locale path

- Update @calcom/web/public/static/locales/en/common.json to @calcom/lib/server/locales/en/common.json
- Addresses GitHub comment about updating platform atoms vite config
- Maintains correct path resolution after locale files moved to packages/lib/server

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: update translationBundler path resolution for production builds

- Use process.cwd() instead of __dirname for locale file path resolution
- Ensures locale files can be found in both development and production environments
- Fixes E2E test failures caused by missing locale files in .next/server/chunks/

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: use relative path resolution for locale files in translationBundler

- Change from process.cwd() to __dirname with relative paths
- Ensures locale files can be found in both development and production environments
- Fixes E2E test failures caused by incorrect path resolution in Next.js builds

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: use process.cwd() for locale path resolution in production builds

- Change from __dirname to process.cwd() with relative paths
- Ensures locale files can be found when bundled into Next.js server chunks
- Fixes E2E test failures caused by incorrect path resolution in production environment
- Follows same pattern used in getStaticProps.tsx for cross-package file access

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: use path.resolve pattern from sendVerificationRequest for locale access

- Change from process.cwd() to path.resolve(process.cwd(), '..', '..', 'packages/lib/server/locales')
- Follows same pattern used in sendVerificationRequest.ts for cross-environment file access
- Should resolve E2E test failures by ensuring locale files can be found when bundled into Next.js server chunks
- Pattern navigates up from current working directory to reach packages directory consistently

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: use dynamic monorepo root detection for locale path resolution

- Replace relative path resolution with dynamic monorepo root finder
- Ensures locale files can be found from any working directory (root, apps/web, apps/api/v2)
- Update API v2 i18n config to use new locale path
- Fixes remaining E2E test failures in API v2 and E2E (1/4) test suites

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: use require.resolve(__filename) for robust path resolution in all contexts

- Replace __dirname with require.resolve(__filename) in monorepo root detection
- Ensures locale files can be found when running from any working directory
- Fixes E2E API v2 test failures where __dirname resolves to '.' instead of actual file path

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* Revert "fix: use require.resolve(__filename) for robust path resolution in all contexts"

This reverts commit b37d8226000da8f7d5fb98b83dd0e95a53d45372.

* fix: update copied locale files after translationBundler path resolution fix

- Copy script updated all locale files in public directory
- Ensures E2E tests have access to latest locale files
- Fixes regression where all E2E tests were failing

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* feat: remove existing locale files to establish copy script as single source of truth

- Delete all common.json files from apps/web/public/static/locales/
- Eliminates developer confusion about which files are authoritative
- copy-locales-static.js script now clearly the only mechanism for populating public folder
- packages/lib/server/locales/ remains the definitive source of truth for translations

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* add comment

* refactor: simplify findMonorepoRoot by removing redundant fallback loop

- Remove unnecessary second while loop using process.cwd()
- The first loop from __dirname will always find the monorepo root
- Add clear error message for fail-fast behavior if repo structure is corrupted
- Improves code clarity and maintainability

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* feat: integrate updated translations from main branch

- Restore all common.json files from main branch to apps/web/public/static/locales/
- Overwrite packages/lib/server/locales/ with up-to-date translation content
- Resolve merge conflicts using Benny's safer 2-step approach
- Ensure translation source of truth remains in packages/lib/server/locales/
- Complete safer conflict resolution to eliminate merge conflicts on PR #22422

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* chore: update package.json and yarn.lock after translation integration

- Update dependencies after ts-node installation for pre-commit hooks
- Ensure yarn.lock reflects current dependency state
- Complete translation integration process

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* feat: remove duplicate locale files from apps/web to establish single source of truth

- Delete all common.json files from apps/web/public/static/locales/
- Maintain packages/lib/server/locales/ as the single source of truth for translations
- copy-locales-static.js script will populate public folder during build process
- Complete Benny's safer 2-step approach: restore from main, then remove duplicates
- Resolve merge conflicts and eliminate developer confusion about translation file locations

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: hbjORbj <sldisek783@gmail.com>
2025-07-12 07:49:27 +00:00
Alex van AndelandhbjORbj bd5e14b488 perf: Remove me.get call in event-types / availability (#22336)
* perf: Event types page remove me.get call

* Update ts definition listing view

* fix type check

* get rid of me call from availability page

---------

Co-authored-by: hbjORbj <sldisek783@gmail.com>
2025-07-12 06:49:29 +00:00
Keith Williams 8cd16ee3dc chore: Loosen Platform CODEOWNERS files (#22432) 2025-07-12 09:20:47 +05:30
Keith WilliamsandDevin AI 57564381cb fix: validate eventTypeId is number in API v1 bookings endpoint (#22433)
* fix: validate eventTypeId is number in API v1 bookings endpoint

- Add validation to return 400 when eventTypeId is string instead of integer
- Prevents string values from reaching Prisma and causing 500 errors
- Follows existing validation patterns in the codebase
- Add test case to verify string eventTypeId returns 400 Bad Request

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* test: add focused test for eventTypeId validation

- Create separate test file for string eventTypeId validation
- Ensures validation logic is properly tested without being blocked by pre-existing issues
- Addresses cubic-dev-ai bot feedback about skipped tests
- Both string and number eventTypeId scenarios are tested

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: improve eventTypeId validation to only check defined values

- Only validate eventTypeId when it's defined and not a number
- Prevents interference with schema validation for missing/undefined values
- Maintains 400 error response for string eventTypeId as required
- Fixes test compatibility issues while preserving validation logic

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* test: move eventTypeId validation test outside of skipped block

- Create dedicated test block for eventTypeId validation
- Remove duplicate test from skipped block
- Ensures validation logic is properly tested
- Addresses PR feedback from keithwillcode

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* cleanup: remove duplicate eventTypeId validation test file

- Remove apps/api/v1/test/lib/bookings/eventTypeId-validation.test.ts
- Tests are now properly located in _post.test.ts outside skipped block
- Addresses PR feedback from keithwillcode about duplicate tests

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-07-11 19:16:27 -03:00
0207109612 fix: add validation for empty hosts in round robin reassignment (#22429)
* fix: add validation for empty hosts in round robin reassignment

- Add check for empty availableUsers array before calling getLuckyUser
- Throw RoundRobinHostsUnavailableForBooking error instead of 500 error
- Use existing error infrastructure with 409 status code and localized message
- Prevents runtime errors when no round robin hosts are available for reassignment

Co-Authored-By: joe@cal.com <joe@cal.com>

* fix: check eventType.hosts.length directly for empty hosts validation

- Move validation to check eventType.hosts.length === 0 immediately after hosts array setup
- Remove later validation after ensureAvailableUsers to catch issue earlier
- Follows user feedback to check hosts array directly instead of availableUsers

Co-Authored-By: joe@cal.com <joe@cal.com>

* fix: update translation message for round robin hosts unavailable error

- Make error message clearer about event type having no hosts
- Change from 'No Round Robin hosts is available for booking' to 'No hosts are available in this event type for round robin booking'

Co-Authored-By: joe@cal.com <joe@cal.com>

* Change error for event type no hosts

* fix: add ErrorCode.EventTypeNoHosts to switch statement for 400 status code

Addresses GitHub comment from keithwillcode to ensure EventTypeNoHosts
error returns proper 400 Bad Request status instead of defaulting to 500.

Co-Authored-By: joe@cal.com <joe@cal.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: joe@cal.com <joe@cal.com>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
2025-07-11 18:03:36 -03:00
github-actions[bot] b84405c5eb chore: version packages (#22418)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-07-11 18:53:35 +00:00
Morgan 2743b32536 fix: third part token auth strategy (#22374) 2025-07-11 17:27:51 +00:00
Omar López a251422f7a fix: locks eslint to v8 across monorepo (#22424) 2025-07-11 17:10:12 +00:00
Alex van Andel d7c9bd6ed8 perf: Tasker performance improvements (#22395)
* perf: Tasker performance improvements

* Remove fields from expected tasker create call, test fix

* Fix the tests, needs validation
2025-07-11 10:09:24 -07:00
8b3ff0b789 fix: ensure isBookingDryRun prop works for booking creation (#22182)
* fix: ensure isBookingDryRun prop works for booking creation

- Add isBookingDryRun prop to useHandleBookEvent hook
- Pass prop through BookerPlatformWrapper and useBookings
- Override _isDryRun flag when prop is provided
- Fixes issue where dry run banner showed but booking creation ignored prop

Co-Authored-By: rajiv@cal.com <rajiv@cal.com>

* fixup

* if dry run prop is pass we use that, otherwise we use params

* add changesets for PR

* replace minor with patch changeset

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: rajiv@cal.com <rajiv@cal.com>
Co-authored-by: Ryukemeister <sahalrajiv6900@gmail.com>
Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2025-07-11 16:45:30 +00:00
Lauris Skraucis 94a537bfda feat: v2 bookings return rescheduledToUid (#22289) 2025-07-11 13:17:55 -03:00
Calcom BotandLingo.dev 64305ffee1 feat: update translations via @LingoDotDev (#22416)
Co-authored-by: Lingo.dev <support@lingo.dev>
2025-07-11 15:55:52 +00:00
45698db0b4 fix: validate Round Robin host availability in handleNewBooking (#22253)
* fix: validate Round Robin host availability in handleNewBooking

- Add validation to ensure Round Robin events have at least one available non-fixed host
- Throw NoAvailableUsersFound error when no Round Robin hosts are available
- Add unit test to verify the fix works correctly
- Fixes issue where Round Robin events with fixed hosts could be booked without Round Robin hosts

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* test: fix host configuration in Round Robin test

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* test: improve Round Robin test to only make RR host busy

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* fix: correct Round Robin validation to only check when RR hosts assigned

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* fix: refine Round Robin validation to only apply when both fixed and RR hosts present

- Add fixedUserPool.length > 0 condition to validation
- Ensures validation only triggers for specific bug scenario: events with fixed hosts + RR hosts but no available RR hosts
- Prevents blocking normal Round Robin events that only have RR hosts
- Updates test description to reflect more precise validation logic

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* fix: simplify Round Robin validation to resolve E2E test failures

Remove overly restrictive fixedUserPool.length > 0 condition that was
blocking valid Round Robin booking scenarios in E2E tests. The validation
now only checks if Round Robin hosts are assigned but none are available,
which is the intended behavior for the bug fix.

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* fix: restore fixedUserPool condition to Round Robin validation

- Add back fixedUserPool.length > 0 condition to make validation specific to bug scenario
- Only triggers when Round Robin events have both fixed hosts AND Round Robin hosts but no available Round Robin hosts
- Prevents blocking normal Round Robin events that only have Round Robin hosts (like in organization settings E2E test)
- Updates test description to reflect more precise validation logic

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* throw error if no RR user is available

* add tests

* fix comments

* revert change

* remove comments

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2025-07-11 16:47:21 +01:00
Anik Dhabal Babuandcubic-dev-ai[bot] 14e14289f0 fix: e2e tests flakes (#22415)
* fix: e2e flakes

* Update apps/web/playwright/dynamic-booking-pages.e2e.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Update delete-account.e2e.ts

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-07-11 16:45:06 +01:00
Omar López 18650b1215 fix: local eslint runs (#22402) 2025-07-11 16:44:35 +01:00
d2bbbf3f45 feat: expose AvailabilitySettingsProps type in @calcom/atoms (#22246)
* feat: expose AvailabilitySettingsProps type in @calcom/atoms

- Export AvailabilitySettingsPlatformWrapperProps as AvailabilitySettingsProps
- Add type export to main atoms package index for direct import
- Enables external consumers to import type directly from @calcom/atoms

Co-Authored-By: rajiv@cal.com <rajiv@cal.com>

* feat: also export AtomScheduleType for atomSchedule data

- Export FindDetailedScheduleByIdReturnType as AtomScheduleType
- Enables direct import of atomSchedule type from @calcom/atoms
- Covers both AvailabilitySettingsProps and AtomScheduleType exports

Co-Authored-By: rajiv@cal.com <rajiv@cal.com>

* fix: update AtomScheduleType to include null and undefined

Co-Authored-By: rajiv@cal.com <rajiv@cal.com>

* refactor: move AtomScheduleType to AvailabilitySettingsPlatformWrapper for cleaner organization

Co-Authored-By: rajiv@cal.com <rajiv@cal.com>

* feat: rename AtomScheduleType to AvailabilitySettingsAtomScheduleType for better clarity

Co-Authored-By: rajiv@cal.com <rajiv@cal.com>

* feat: rename to AvailabilitySettingsScheduleType for better naming consistency

Co-Authored-By: rajiv@cal.com <rajiv@cal.com>

* fix: use proper import from @calcom/platform-libraries/schedules instead of dynamic import

Co-Authored-By: rajiv@cal.com <rajiv@cal.com>

* add changelogs

* feat: extract AvailabilitySettingsSchedule type from AvailabilitySettingsProps

- Extract schedule property structure into separate AvailabilitySettingsSchedule type
- Update AvailabilitySettingsProps to reuse the extracted schedule type
- Export AvailabilitySettingsSchedule from @calcom/atoms package index
- Enables direct import of schedule type for external consumers

Co-Authored-By: rajiv@cal.com <rajiv@cal.com>

* Revert "feat: extract AvailabilitySettingsSchedule type from AvailabilitySettingsProps"

This reverts commit 79239e4b18925db3fcc1d8df7e9f37770ec4f116.

* fixup: extract schedule for AvailabilitySettingsProps

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: rajiv@cal.com <rajiv@cal.com>
Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
Co-authored-by: Ryukemeister <sahalrajiv6900@gmail.com>
2025-07-11 16:53:40 +02:00
devin-ai-integration[bot]andmorgan@cal.com 13cb99b7fe feat: inject required repositories into AvailableSlotsService using dependency injection (#22413)
* feat: inject all repositories into AvailableSlotsService using dependency injection

- Create DI modules for SelectedSlotsRepository, TeamRepository, UserRepository, BookingRepository, EventTypeRepository, RoutingFormResponseRepository
- Update available-slots DI module to bind all 6 repositories
- Update DI container to load all new repository modules
- Replace all 10 direct repository instantiations with injected dependencies
- Add missing DI tokens for repository modules
- Expand IAvailableSlotsService interface to include all repository dependencies

This follows the same dependency injection pattern established in previous repository refactoring PRs and enables better testability and modularity by making all dependencies explicit and configurable.

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* chore: DI available slots repo on api v2

* chore: bump platform libs

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: morgan@cal.com <morgan@cal.com>
2025-07-11 17:37:24 +03:00
a1571d01bd docs: Update Organization Readme (#22060)
* Update org readme

* Update packages/features/ee/organizations/README.md

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Apply suggestions from code review

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>
2025-07-11 18:30:28 +05:30
Kartik Saini bbd8af074e chore: update i18n workflow to use Node.js 20 (#22403) 2025-07-11 12:17:12 +00:00
c9a47dd0ce refactor: convert RoutingFormResponseRepository to use dependency injection pattern (#22408)
* refactor: convert RoutingFormResponseRepository to use dependency injection pattern

- Add constructor with PrismaClient dependency injection
- Convert all 5 static methods to instance methods using this.prismaClient
- Convert private static helper method generateCreateFormResponseData to instance method
- Update all usage sites to use two-step instantiation pattern:
  const formResponseRepo = new RoutingFormResponseRepository(prisma); formResponseRepo.method(...)
- Update test files to use proper mock implementation with vi.mocked pattern
- Reuse repository instances within same function scope where multiple calls are made
- Follow same dependency injection pattern as UserRepository, TeamRepository, SelectedSlotsRepository, BookingRepository, and EventTypeRepository

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* fix: resolve inconsistent dependency injection in AvailableSlotsService

- Use two-step instantiation pattern for UserRepository calls
- Continue fixing remaining repository instantiation inconsistencies

Co-Authored-By: morgan@cal.com <morgan@cal.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: morgan@cal.com <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2025-07-11 10:03:25 +00:00
sean-brydon 1c9778e667 fix members page crash with pbac feature flag (#22409) 2025-07-11 09:59:56 +01:00
devin-ai-integration[bot]andmorgan@cal.com 758143ef70 refactor: convert EventTypeRepository to use dependency injection pattern (#22397)
- Add constructor with PrismaClient dependency injection
- Convert all 14 static methods to instance methods using this.prismaClient
- Update all usage sites to use two-step instantiation pattern:
  const eventTypeRepo = new EventTypeRepository(prisma); eventTypeRepo.method(...)
- Keep getSelectedCalendarsFromUser as static utility method
- Follow same pattern as UserRepository, TeamRepository, SelectedSlotsRepository, and BookingRepository
- Maintain all existing method signatures and functionality

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: morgan@cal.com <morgan@cal.com>
2025-07-11 10:39:22 +03:00
sean-brydon b5911a9a2d feat: add method for getting teamId permissions PBAC (#22375)
* feat:add method for getting teamId permissions

* add logic and test for zero permsiion strings

* fix test by updating mock
2025-07-11 08:34:33 +01:00
keithwillcode 260f4e1b51 chore: release v5.4.19
Post release / release (push) Canceled after 0s
2025-07-11 01:25:57 +00:00
Keith Williams e6c36af3b4 revert: "fix: Add new route to create team routing-form response (#22347)" (#22399)
This reverts commit 89e7fca183.
2025-07-11 01:02:11 +00:00
Omar López 2fb2458eee Revert "feat: add race condition test for calendar-cache-serve booking flow (…" (#22400) 2025-07-10 17:43:41 -07:00
keithwillcode b340b0edbe chore: release v5.4.18 2025-07-10 22:59:01 +00:00
f7fd1c4402 feat: remove unused x-cal-timezone header and middleware matcher (#22398)
* feat: remove unused x-cal-timezone header and middleware matcher

- Remove x-cal-timezone header setting from middleware.ts
- Remove x-cal-timezone header setting from createNextApiHandler.ts
- Remove /api/trpc/:path* from middleware matcher
- Eliminates ~50M edge requests per month for unused functionality
- All timezone handling uses browser detection and localStorage instead

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* update POST_METHODS_ALLOWED_API_ROUTES

* test: remove api/trpc POST validation test

- Remove test for /api/trpc/book/event POST requests since /api/trpc/:path* was removed from middleware matcher
- Keep test for /api/auth/signup which is still processed by middleware

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: hbjORbj <sldisek783@gmail.com>
2025-07-10 22:16:25 +00:00
devin-ai-integration[bot]andmorgan@cal.com c316721051 refactor: convert BookingRepository to use dependency injection pattern (#22389)
* refactor: convert BookingRepository to use dependency injection pattern

- Add constructor injection for PrismaClient to BookingRepository
- Convert all static methods to instance methods using this.prismaClient
- Update all usage sites to use two-step instantiation pattern:
  const bookingRepo = new BookingRepository(prisma); bookingRepo.method(...)
- Apply same dependency injection pattern as UserRepository, TeamRepository, and SelectedSlotsRepository
- Update test files to use correct prismaMock import paths
- Maintain all existing functionality and type safety

Files updated:
- BookingRepository class structure and all 15 static methods
- Video meeting pages and booking views
- Booking utilities and services (handleNewBooking, originalRescheduledBookingUtils)
- Round robin handlers and reassignment logic
- Interval limits and booking limits checking
- Test files with proper mocking setup

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* chore: bump platform libs

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: morgan@cal.com <morgan@cal.com>
2025-07-10 18:06:57 +00:00
80ac118242 refactor: convert SelectedSlotsRepository to use dependency injection pattern (#22387)
* refactor: convert TeamRepository to use dependency injection pattern

- Add constructor injection for PrismaClient in TeamRepository
- Convert all static methods to instance methods using this.prismaClient
- Update all usage sites to use two-step pattern: const teamRepo = new TeamRepository(prisma); teamRepo.method(...)
- Optimize instance reuse within same function scopes where possible
- Update test files to work with new instance pattern
- Preserve all existing functionality and method signatures

Follows the same dependency injection pattern as UserRepository refactoring

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* refactor: convert SelectedSlotsRepository to use dependency injection pattern

- Add constructor injection for PrismaClient/PrismaTransaction
- Convert all static methods to instance methods using this.prismaClient
- Update usage sites to use two-step instantiation pattern:
  const slotsRepo = new SelectedSlotsRepository(prisma); slotsRepo.method(...)
- Optimize instance reuse in util.ts for multiple method calls
- Update test mocks to handle new constructor-based pattern
- Add explicit type annotations to resolve TypeScript inference issues

Follows same dependency injection pattern as UserRepository and TeamRepository refactorings.

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* chore: bump platform libs

* fix: devin mistake prisma client

* fix: devin typing mistakes

* chore: bump platform libs

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: morgan@cal.com <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2025-07-10 15:14:26 +00:00
efd15c5a3e refactor: convert TeamRepository to use dependency injection pattern (#22383)
* refactor: convert TeamRepository to use dependency injection pattern

- Add constructor injection for PrismaClient in TeamRepository
- Convert all static methods to instance methods using this.prismaClient
- Update all usage sites to use two-step pattern: const teamRepo = new TeamRepository(prisma); teamRepo.method(...)
- Optimize instance reuse within same function scopes where possible
- Update test files to work with new instance pattern
- Preserve all existing functionality and method signatures

Follows the same dependency injection pattern as UserRepository refactoring

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* chore: bump platform libs

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: morgan@cal.com <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2025-07-10 14:03:50 +00:00
devin-ai-integration[bot]andBailey 7d02d1bb23 fix: improve layout in copy times popup (#22368)
- Remove justify-between from checkbox labels to fix uneven padding
- Use CheckboxField with descriptionAsLabel for consistent spacing
- Add flex justify-end to button container for right alignment
- Maintain existing keyboard navigation functionality

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Bailey <bailey@pumfleet.co.uk>
2025-07-10 13:21:38 +00:00
Dhairyashil ShindeandAnik Dhabal Babu 0d877e7be3 fix: Always return cancellationReason and cancelledByEmail for cancelled bookings (#22082)
* fix: always return cancellationReason and cancelledByEmail for cancelled bookings

* Implemented reviewed changes

* Updated ternary conditional logic for cancelled booking

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-07-10 18:45:46 +05:30
e4c47640fc refactor: convert UserRepository to use dependency injection pattern (#22360)
* refactor: convert UserRepository to use dependency injection pattern

- Convert all static methods to public instance methods
- Add constructor that takes PrismaClient parameter
- Update all usage sites to use new instantiation pattern: new UserRepository(prisma).method()
- Follow same pattern as PrismaOOORepository for consistency
- Maintain all existing method logic and signatures unchanged
- Update 125+ files across the codebase to adapt to new pattern

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* optimize: reuse UserRepository instances within same function scope

- Create single UserRepository instance per function scope
- Reuse instance for multiple method calls within same function
- Reduces object instantiation overhead and improves performance
- Apply optimization pattern consistently across codebase

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* fix: repository

* fixup! fix: repository

* fixup! fixup! fix: repository

* fixup! fixup! fixup! fix: repository

* fix: update test mocking strategies for UserRepository dependency injection

- Convert static method mocks to instance method mocks in userCreationService.test.ts
- Update vi.spyOn calls to work with constructor injection pattern in getAllCredentials.test.ts
- Fix UserRepository mocking in getRoutedUrl.test.ts to use constructor injection
- Ensure consistent mocking approach across all test files
- Fix 'UserRepository is not a constructor' errors in tests

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* feat: optimize UserRepository instance reuse and add SessionUser type

- Reuse UserRepository instance in OrganizationRepository.createWithNonExistentOwner
- Add comprehensive SessionUser type definition for type safety
- Improve type constraints in enrichUserWithTheProfile and enrichUserWithItsProfile
- Ensure proper return types with profile information

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* fix: make UserRepository mocking strategy more robust for CI environments

- Add defensive checks for vi.mocked() to handle CI environment differences
- Ensure mockImplementation is available before calling it
- Maintain consistent mocking pattern across all test files
- Fix 'Cannot read properties of undefined' error in CI

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* fixup! fix: make UserRepository mocking strategy more robust for CI environments

* refactor: convert direct UserRepository instantiations to two-step pattern

- Change await new UserRepository(prisma).method(...) to const userRepo = new UserRepository(prisma); await userRepo.method(...)
- Optimize instance reuse within same function scopes
- Apply pattern consistently across all modified files in PR
- Fix type errors in organization.ts and sessionMiddleware.ts

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* refactor: complete two-step UserRepository pattern for remaining files

- Apply two-step instantiation pattern to all remaining modified files in PR
- Ensure consistent UserRepository usage across entire codebase
- Maintain instance reuse optimization within function scopes

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* chore: bump platform libs

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: morgan@cal.com <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2025-07-10 12:11:14 +00:00
Hariom Balhara 89e7fca183 fix: Add new route to create team routing-form response (#22347)
* fix: Add formId ownership with org guard

* Don't allow user routing form endpoint to create response for team
routing form

* rename to or guard
2025-07-10 11:56:45 +00:00
sean-brydon 33b5bf1db8 fix: Move pbac to prisma from kysley (#22318)
* fixes

* fix prisma mock to include transaction callbacj

* remove redudant transactions

* remove hard requirement on transactions in services

* remove mocktrx

* fix cubic feedback

* correct permission updating logic of roles. Implement diff service + domain types

* remove role mapper
2025-07-10 10:24:50 +00:00
Devanshu Sharma f69c4a900e refactor: enhance UI spacing and text styling in Locations component and Switch component (#22328) 2025-07-10 08:34:32 +00:00
Sarthak Kapila 1da25cc85f docs: booking attendee absent (#22094)
* refactor: booking attendee absent

* docs: swagger generate
2025-07-10 07:52:10 +00:00
Akash Kinkar Pandey 3a65b372c5 perf:Remove Redundant Keys in common.json for english (#22362) 2025-07-10 13:19:38 +05:30
sean-brydon 9892d521fb fix: use domain errors instead of trpc (#22341) 2025-07-10 08:23:50 +01:00
Alex van Andel 3285b252c2 chore: Add High-Load warning for user availability checks with many users (#22369) 2025-07-10 01:09:21 +00:00
emrysal 97af2fc0f9 chore: release v5.4.17
Post release / release (push) Canceled after 0s
2025-07-09 21:19:55 +00:00
Morgan 5c508bce6d chore: DI repositories in AvailableSlotsService class (#22356)
* chore: DI available slots service repositories

* remove configService from worker module

* register scheduleRepo in availableSlotsModule

* chore: bump platform libs

* remove useless comment from prisma module

* fix: availableSlotsModule to class deps

* fix: repositoriesModule deps

* chore: container pattern

* refactor: move modules in DI folder

* fixup! refactor: move modules in DI folder
2025-07-09 19:55:55 +00:00
Morgan db84343581 chore: new auth strategy for third party access tokens (#21867)
* chore: new auth strategy for third party access tokens

* chore: throw error earlier if Bearer token is invalid

* fix: check apikey and access token before third party token
2025-07-09 22:47:07 +03:00
Shaunak DasandUdit Takkar 2b44d09191 fix: 🐛 guests no show insights bug (#22045)
* fix: guests no show insights bug

* feat: fix feature failure introduced by conflict resolve

* feat: address cubic comments

* fix: add no show guests count

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-07-09 19:17:19 +00:00
Anik Dhabal Babu 10d67aee86 Revert "fix: issue #9523 limited scroll range on mobile device (#21935)" (#22363)
This reverts commit f611c3d767.
2025-07-09 19:09:46 +00:00
Anik Dhabal Babuandcubic-dev-ai[bot] b33bbb8af0 fix: manage Seo index for embed page (#22348)
* fix: manage seo index

* Update apps/web/app/(booking-page-wrapper)/[user]/[type]/embed/page.tsx

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* update

* tweak

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-07-09 16:03:46 +00:00
Joe Au-Yeung 3fe9327724 fix: Add unique constraint to team and slug for attributes (#22357)
* Add unique constraint to team and slug

* Add migration file
2025-07-09 15:52:48 +00:00
Omar LópezandDevin AI 179a547bd0 feat: add race condition test for calendar-cache-serve booking flow (#22170)
* feat: add race condition test for calendar-cache-serve booking flow

- Reproduces double-booking when two guests book same timeslot 1-2s apart
- Enables both calendar-cache and calendar-cache-serve feature flags
- Uses parallel browser contexts to simulate concurrent booking attempts
- Verifies both bookings succeed and create double-booking scenario

Co-Authored-By: zomars@cal.com <zomars@me.com>

* fix: correct page reference in race condition test timeout

- Change page.waitForTimeout(1500) to use correct page context
- Fix timeslot selection to ensure both contexts book same slot
- Remove incorrect host assertion and add logging to demonstrate race condition
- Test now successfully reproduces double-booking bug locally
- Fixes 'end of central directory record signature not found' error

Co-Authored-By: zomars@cal.com <zomars@me.com>

* Update booking-race-condition.e2e.ts

* Update booking-race-condition.e2e.ts

* Update booking-race-condition.e2e.ts

* Update booking-race-condition.e2e.ts

* Create scratchpad.md

* Update booking-race-condition.e2e.ts

* Delete scratchpad.md

* Update booking-race-condition.e2e.ts

* Update booking-race-condition.e2e.ts

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-07-09 10:33:13 -04:00
Morganandcubic-dev-ai[bot] 7ada02177d refactor: get available slots service (#22340)
* refactor: GetAvailableSlotsService

* chore: add todo comments where DI is needed

* chore: bump platform libs

* chore: fix unit tests

* fix: only instantiate AvailableSlotsService once per service

* Update packages/trpc/server/routers/viewer/slots/util.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix: bind this on all functions with reporting

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-07-09 12:15:09 +01:00
59b55e40b5 fix: allow enter key to create new list items in editor (#22001)
* fix: allow enter key to create new list items in editor

* remove: unnecessary priority set to low

* remove: unnecessary priority set to low

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: Eunjae Lee <hey@eunjae.dev>
2025-07-09 09:39:08 +00:00
19563aa697 feat: Self hosted onboarding (#22102)
* intro work

* update wixard form to have content callback to remove preset navigation

* more fixes to deployment

* fix calling static service

* fix save license key text

* ensure default steps work as expected

* fix conditional for rendering step

* skip step

* add on next step for free license

* refactor wizard form to use nuqs

* fix styles

* merge base param with step config

* fix next stepo text

* use deployment Signature token

* decrypt signature token

* fix: resolve type errors and test failures from wizard form refactor

- Fix signatureToken field name to signatureTokenEncrypted in deployment repository
- Add missing getSignatureToken method to verifyApiKey test mock
- Fix WizardForm import from default to named export in test file
- Add missing nextStep prop to Steps component in WizardForm

Resolves TypeScript type check errors and unit test failures without changing functionality.

Co-Authored-By: sean@cal.com <Sean@brydon.io>

* fix: add missing getDeploymentSignatureToken mock in LicenseKeyService test

Co-Authored-By: sean@cal.com <Sean@brydon.io>

* fix: add nuqs library mock for WizardForm test

Co-Authored-By: sean@cal.com <Sean@brydon.io>

* fix: add missing nav prop to AdminAppsList component with eslint disable

Co-Authored-By: sean@cal.com <Sean@brydon.io>

* Apply suggestions from code review

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Update apps/web/modules/auth/setup-view.tsx

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix license schema changes

* revret schema generation

* fix eslint errors

* remove required nav type + add use client

* fix types

* Update packages/ui/components/form/wizard/useWizardState.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix controller issue

* add checks for deployment key being null - add more tests

* fix tests

* add deployment key tests

* fix: resolve crypto mock to handle empty encryption keys gracefully

- Updated symmetricDecrypt mock to return null instead of throwing 'Invalid key' error when encryption key is empty
- All getDeploymentKey tests now pass including the previously failing 'should return null when decryption fails due to missing encryption key' test
- Fixes mocking issues in PR 22102 self-hosted onboarding wizard form refactor

Co-Authored-By: sean@cal.com <Sean@brydon.io>

* fix label

* add i18n to error

* use enum for steps

* add as const

* fix test env issues

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-07-09 09:26:01 +01:00
emrysal 6410687fb6 chore: release v5.4.16
Post release / release (push) Canceled after 0s
2025-07-09 00:00:28 +00:00
Bandhan Majumder 4e4c8f5f49 fix: fixes type issue in theme and password property of newUser seed data (#22232)
Signed-off-by: bandhan-majumder <bandhanmajumder16@gmail.com>
2025-07-08 23:53:48 +00:00
abhix4 416b17cf69 fix: center align dropdown indicator when menu is open (#22262)
* fix: vertical misalignment of dropdown indicator icon in select

* fix: vertical misalignment of dropdown indicator icon in select
2025-07-08 23:37:24 +00:00
Anwar SadathandAnik Dhabal Babu 27cd7c8496 fix: Hosts are able to cancel an event without providing any reason but with whitepsace characters (#22282)
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-07-09 00:17:13 +01:00
Benny Joo 02321c33b2 Revert "refactor: GetAvailableSlotsService (#22321)" (#22334) 2025-07-08 14:28:59 -07:00
Morgan c3dab3e4f8 refactor: GetAvailableSlotsService (#22321)
* refactor: GetAvailableSlotsService

* chore: add todo comments where DI is needed

* chore: bump platform libs
2025-07-08 16:54:45 -04:00
Joe Au-Yeung 0c182e2813 Allow admins to update users (#22332) 2025-07-08 20:14:44 +00:00
Hariom BalharaandUdit Takkar 51a076212b fix: Do not wait for slots request before removing the (#22323)
default(non-skeleton) loader

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-07-08 16:52:37 -03:00
Akash Kinkar Pandey 27dce7374b feat: Add Bengali Language Support. This fixes #17717 (#20567) 2025-07-08 13:15:11 +00:00
Lauris Skraucis 52f2c18800 refactor: attendee scheduled email timezone (#22301) 2025-07-08 10:16:22 +00:00
Eunjae LeeandDevin AI 35a8918ea9 feat: add expandable submenu for sidebar (#22268)
* feat: add dropdown submenu for Insights navigation

- Add dropdown functionality for desktop Insights menu to show submenu instead of immediate navigation
- Add expandable submenu for mobile Insights in More navigation
- Users can now select specific insights destination (Bookings, Routing, Router Position)
- Maintains existing navigation patterns and accessibility

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: use expansion state instead of dropdown for insights navigation

- Remove dropdown components and use existing child rendering pattern
- Add state management for expansion tracking
- Change items with children to render as buttons instead of links
- Preserve existing behavior when currently on page

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* feat: keep parent expanded and hide chevron when sub-item is active

- Add hasActiveChild logic to detect when any child item is currently active
- Keep parent menu expanded when any sub-item is selected
- Hide chevron icon when any sub-item is active
- Maintain existing expansion behavior when no sub-item is active

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* feat: add localStorage persistence for navigation expansion state

- Replace useState with usePersistedExpansionState hook in both NavigationItem and MobileNavigationMoreItem
- Expansion state now persists across page navigations using localStorage
- Uses nav-expansion-{itemName} keys following existing localStorage patterns

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* chore: update yarn.lock from dev server startup

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* feat: change navigation expansion persistence from localStorage to sessionStorage

- Expansion state now persists within browser session but resets when tab closes
- Maintains same error handling and key naming patterns

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* Revert "chore: update yarn.lock from dev server startup"

This reverts commit 832f417da96f79979942c99400d2a7b26f889616.

* clean up

* add aria attributes

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-07-08 09:39:38 +00:00
b39eab72e7 feat: added option to lock maxactivebookingsperbooker for managed events (#21892)
* added option to disable maxactivebookingsperbooker for managed events

* chore

* update

---------

Co-authored-by: Kartik Saini <41051387+kart1ka@users.noreply.github.com>
Co-authored-by: unknown <adhabal2002@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-07-08 08:25:37 +00:00
Peer Richelsenandcubic-dev-ai[bot] 928b2477be chore: added platform link to api key settings (#21807)
* added platform link to api key settings

* Update packages/features/ee/api-keys/components/ApiKeyDialogForm.tsx

* Update packages/features/ee/api-keys/components/ApiKeyDialogForm.tsx

* nit

* Update packages/features/ee/api-keys/components/ApiKeyDialogForm.tsx

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-07-08 08:05:29 +00:00
Lauris Skraucis dc13251bcc fix: flakey v2 assign-all-team-members test (#22300) 2025-07-08 08:03:10 +00:00
Hariom Balhara 4843658dfb Allow scroll when user selects a date (#22313) 2025-07-08 07:00:30 +00:00
Anik Dhabal Babuandcubic-dev-ai[bot] 076afdc00e fix: Unable to cancel a team event if any event host is an attendee (#22233)
* fix

* Update handleCancelBooking.ts

* Update handleCancelBooking.ts

* update comment

* fix type error

* added test

* Update packages/features/bookings/lib/handleCancelBooking.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Update handleCancelBooking.test.ts

* refactor

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-07-07 19:33:33 +00:00
Deepak guptaandKartik Saini 4404699fa6 fix: improve redirect parameter handling for success page (#20764)
* improve redirect parameter

* test

---------

Co-authored-by: Kartik Saini <41051387+kart1ka@users.noreply.github.com>
2025-07-08 00:23:38 +05:30
Morgan 52940ce254 refactor: getAvailableSlots use repositories (#22290) 2025-07-07 10:57:01 -07:00
Balaji KrishnamurthyandKartik Saini cd6293d220 fix: sort the availabilities based on start time for each day (#21656)
* sort the availabilities based on start time for each day

* move the sorting outside the reduce

* add guard variable for safe access

---------

Co-authored-by: Kartik Saini <41051387+kart1ka@users.noreply.github.com>
2025-07-07 23:11:47 +05:30
Romit 108f95723b fix: Changes to Managed Event Types Reset Assignee Availability (#21980)
* fixed

* chore
2025-07-07 17:03:50 +00:00
Fábio Galiano f611c3d767 fix: issue #9523 limited scroll range on mobile device (#21935) 2025-07-07 21:45:26 +05:30
Lauris Skraucis 6091208f8a refactor: standardize v2 docs (#22299) 2025-07-07 14:47:31 +00:00
Morgan 585a12fa48 fix: unit tests failing on destination calendar missing timestamps (#22292) 2025-07-07 11:40:13 +00:00
emrysal bfc4f7b66c chore: release v5.4.15
Post release / release (push) Canceled after 0s
2025-07-07 10:30:57 +00:00
9dca13305f feat: pbac core ui (#21471)
* migration plus feature flag

* show navigation route + inital roles migration

* add a check permission use case to take in the feature flags for a team

* bulk update script

* inital frontend work for displaying roles

* move to a more "anemic domain models" approach

* update test to match new DDD strutcture

* fix tests

* update transaction call back types to include trx

* align fe types after transaction to DDD

* move away from usecases to a more domain tailored approach

* get permissions per resource and map them to domain permission string

* update permision logic

* correctly get the logic for *.* permissions on owner

* wip sheet logic for ssr

* role list

* use nuqs for sheet parsing on handle change

* fox

* improve hook usage

* enable PBAC router

* delete modal etc

* i18n and inital rough layout of roles + permisions creating

* add color to migrations

* add colors and new method to tests

* move hooks out of infra into client with provider

* move hooks out of infra into client with provider

* memo features and ensure render once

* remove comment

* seed color

* use role colours

* match i18n

* add custom color picker to edit/create form

* fix advanced mode toggle

* more work on adv permission group

* update migrations

* abstract lots of core form logic to a custom hook

* improve UX for selecting all and toggling all

* improve code quality and use domain mappers in role repositoryu

* call server action to revalidate cache

* call invalidate cache on delete

* fix re-render + improves update logic wip

* fix txn for assinging role to member

* wip on assigning users custom roles

* fix repo

* update logic for checking if users can update roles

* remove member from permission check

* check users permission and assign roles

* move to factory approach

* move default rolesIDs to constant

* add facuted values to table

* display custom role in table

* fix type error

* fix role filter

* check pbac feature flag to see what column to filter on

* push repo mocks and other mocks to fix unit tests

* fix and add test for empty permissions when creating a role

* pass updates to repo so we actually update roles

* fix types

* fix types

* restore lock changes

* fix role service test for new updates section

* fix updated at types

* update mocks to use feature repository mock

* remove roletype from db in model

* prevent multiple queries

* fix typeof in role model

* fix and migrate i18n to one registery

* fix and update i18n to be in registery

* fix type error + fall back in service instead of repo for BL

* more type errors

* update members faceted values to bennys refactor

* fix types

* remove the _resource from type conditionally

* fix managment factory types to expose PBAC enbaled obol

* narrow down types

* wip fix for types

* more fix types

* cast role

* fix tests

* attempt of fixing _resoucre key access type

* attempt of fixing _resoucre key access type

* seperate migraations to batches

* add invalidate time to team features

* restore router to main

* push main lock

* Update packages/features/pbac/domain/types/permission-registry.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Update packages/features/pbac/domain/mappers/PermissionMapper.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Update packages/prisma/migrations/20250527091330_add_color_to_pbac_role/migration.sql

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Update packages/prisma/migrations/20250617070118_update_memberships_one_time/migration.sql

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Update apps/web/app/(use-page-wrapper)/settings/(settings-layout)/organizations/roles/_components/AdvancedPermissionGroup.tsx

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Apply suggestions from code review

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix mapped type

* restore migration

* skip _resource

* use partical

* fix type errors in tests and hooks

* Simplified the role field in the editSchema to use z.nativeEnum(MembershipRole)

* fix type errors for editsheet

* fix type errors for editsheet

* Apply suggestion from comment 2151515295

* remove footer since we dont have docs yet

* add i18n

* lock all toggle chevron

* use prisma

* tidy up old manage permission

* fix i18n

* remove can manage from role permission check

* auto select read

* address benny feedback

* fix type

* fix type

* update function name due to merge

* fix types

* update tests to match new membership method from merge

* address cubic feedback

---------

Co-authored-by: Eunjae Lee <hey@eunjae.dev>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-07-07 10:20:24 +01:00
Joe Au-Yeung 0ab9823c9a chore: add createdAt field to SelectedCalendar and DestinationCalendar (#22071)
* Add createdAt

* Address feedback

* Make date fields nullable

* Type fixes

* Type fix

* Fix tests
2025-07-05 17:04:38 +01:00
zomars b3fd4f307f chore: release v5.4.14
Post release / release (push) Canceled after 0s
2025-07-04 20:28:41 +00:00
Alex van Andel 06ed0de456 Quick eslint fixup 2025-07-04 21:10:52 +01:00
devin-ai-integration[bot]andalex@cal.com 79b6278883 refactor: replace Prisma.validator<Select>() with satisfies syntax (#22270)
* refactor: replace Prisma.validator<Select>() with satisfies syntax

- Convert all Prisma.validator<Prisma.SomeSelect>()({...}) patterns to {...} satisfies Prisma.SomeSelect
- Update import { Prisma } to import type { Prisma } where only used for types
- Maintain existing functionality while modernizing TypeScript syntax
- Covers 89+ files across packages/prisma/selects, repository classes, tRPC handlers, and API modules

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* refactor: complete remaining Prisma.validator conversions

- Update test fixture files with satisfies syntax
- Apply lint-staged formatting fixes
- Complete refactoring of all remaining files

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* revert: remove unintended platform library update

- Revert yarn.lock changes that updated @calcom/platform-libraries from 0.0.236 to 0.0.239
- This was an unintended side effect of the refactoring process
- Keep only the intended Prisma.validator → satisfies syntax changes

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* fix: update ESLint plugin references to correct package name

- Change @calcom/eslint to @calcom/eslint-plugin-eslint in eslint-preset.js
- Resolves 'Failed to load plugin @calcom/eslint' error causing CI failures

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: alex@cal.com <me@alexvanandel.com>
2025-07-04 21:08:05 +01:00
Joe Au-Yeung 673823cb97 fix: Workflow scanning (#22273) 2025-07-04 10:49:06 -07:00
abhix4 15b26dff73 prevent footer from overlapping content in SearchDialog (#22266) 2025-07-04 15:46:08 +00:00
Ajeet Pratap SinghandKartik Saini 2303f2e9e1 chore: remove the duplicate keys from the common.json (#21975)
Co-authored-by: Kartik Saini <41051387+kart1ka@users.noreply.github.com>
2025-07-04 18:34:29 +05:30
056b821070 feat: Add routing-forms record response endpoint with available slots (#22239)
* feat: Add routing-forms record response endpoint with available slots

* fix: resolve TypeScript error in handleResponse.test.ts

- Fix type mismatch where mockResponse was passed as identifierKeyedResponse
- identifierKeyedResponse expects Record<string, string | string[]> structure
- Updated test to pass correct data structure for type compatibility

Co-Authored-By: hariom@cal.com <hariom@cal.com>

* fix: correct POST endpoint parameter handling and request body parsing in routing forms responses controller

- Change @Query() to @Body() decorator for POST request data in controller
- Update service method to accept parsed body data directly
- Remove incorrect URLSearchParams parsing of request.body object
- Fix getRoutingUrl method to use form response data parameter

This resolves API v2 test failures by following proper NestJS patterns for POST request handling.

Co-Authored-By: hariom@cal.com <hariom@cal.com>

* Pass teamMemberEmail as well

* Devin fixes reverted

* Keep all routing related props together in both endpoints

* Remove newly added slots props from Slots documentation as they are used through internal fn call only

* fix test

* Pass skipContactOwner

* Pass crmAppSlug and crmOwnerRecordGType and add more tests

* handle external redirect case and form not found case

* hide props

* chore: bump platform libs

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: hariom@cal.com <hariom@cal.com>
Co-authored-by: cal.com <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2025-07-04 12:33:13 +00:00
Lauris Skraucis c90fded6b7 refactor: filter out admins and owners from platform event types hosts (#22258) 2025-07-04 14:10:31 +02:00
Anik Dhabal Babu aa6f1a7f93 feat: Waiting room setting for Zoom (#22256) 2025-07-04 17:38:07 +05:30
0cdd7c9605 refactor: create team service (#22036)
* refactor: create team service

* refactor: finish

* tests: add unit test for team service

* Add alternative approach to testing

---------

Co-authored-by: Hariom <hariombalhara@gmail.com>
Co-authored-by: Benny Joo <sldisek783@gmail.com>
2025-07-04 07:45:44 +00:00
Anik Dhabal Babu f40a1c92ef fix: Duplicate calendar event when a guest is added (#22247) 2025-07-04 03:37:56 +00:00
Keith WilliamsandDevin AI 739ef153f6 docs: improve English naturalness in API v2 documentation (#22130)
* docs: improve English naturalness in API v2 documentation

- Fix awkward API summary 'Find out when is an event type ready to be booked' to 'Get available time slots for an event type'
- Correct 'setup' vs 'set up' usage throughout documentation
- Fix OAuth capitalization consistency
- Improve 'api' to 'API' capitalization in v2 docs
- Enhance readability while preserving technical accuracy

Fixes unnatural English phrasing in titles, headers, descriptions, and summaries across API v2 documentation files.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* docs: add missing articles 'the' in API v2 documentation

- Fix 'How to Set Up API' to 'How to Set Up the API' in titles
- Add 'the' before 'API' in descriptions and summaries
- Fix grammar error 'all you need to is' to 'all you need to do is'
- Improve naturalness while maintaining technical accuracy

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* docs: fix unnatural English in API v2 @ApiOperation summaries

- Fix grammatically incorrect 'conferencing apps oauths callback' to 'Conferencing app OAuth callback'
- Replace 'ooo' with 'out-of-office' in user-facing summaries for clarity
- Ensure consistent sentence case capitalization (only first letter capitalized)
- Remove trailing periods from summaries for consistency
- Fix awkward phrasing like 'Get by attribute id all of...' to more natural English
- Revert 'Introduction to the API v2' back to 'Introduction to API v2'
- Improve naturalness while maintaining technical accuracy

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* Update apps/api/v2/src/modules/slots/slots-2024-09-04/controllers/slots.controller.ts

* Update docs/api-reference/v2/openapi.json

* docs: fix setup/set up usage - use 'backend setup' (noun) not 'backend set up' (verb)

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* docs: fix setup/set up verb usage - use 'set up' (verb) not 'setup' (verb)

- Fix 'You have to setup' → 'You have to set up' in quickstart.mdx
- Fix 'Setup environment variables' → 'Set up environment variables'
- Fix 'Setup root of your app' → 'Set up root of your app'
- Fix 'prompted to setup' → 'prompted to set up' in setup.mdx

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* Ran v2 locally to regen the doc json files

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-07-03 23:47:09 +00:00
850ac8092f perf: optimize date range intersection algorithm from O(n²) to O(n log n) (#22076)
* feat: optimize date range intersection algorithm from O(n²) to O(n log n)

- Replace nested forEach loops with two-pointer approach
- Sort arrays once and traverse efficiently
- Maintains exact same functionality and API
- Improves performance for team scheduling scenarios

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* feat: add comprehensive stress test for intersect function performance

- Add performance comparison test showing 22x improvement from O(n²) to O(n log n)
- Include edge cases testing for correctness validation
- Test with realistic data sizes (50 date ranges per user)
- Demonstrate identical results between old and new algorithms
- Provide timing measurements and performance logging

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* refactor: update stress test to focus on optimized algorithm performance

- Remove old O(n²) algorithm comparison logic from test
- Focus stress test on current optimized intersect function performance
- Test with 400 total date ranges (4 users × 100 ranges each)
- Maintain realistic data sizes for team scheduling scenarios
- Execution time: 10.33ms for 400 ranges with 97 intersections found

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* docs: restore explanatory comment in intersect function

- Add back comment explaining intersection logic as requested in PR review
- Comment clarifies when intersected time ranges are added to results array
- Addresses GitHub feedback from hbjORbj to revert comment removal

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* refactor: remove unnecessary intersectNew variable in edge cases test

- Use intersect function directly instead of intersectNew variable assignment
- Addresses GitHub feedback from keithwillcode to clean up test code
- No functional changes to test logic or assertions

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* test: add comprehensive test coverage for intersect function

- Add 27 comprehensive test cases covering all edge cases and scenarios
- Test empty inputs, single arrays, overlapping ranges, containment
- Add team scheduling scenarios and performance testing
- Test unsorted input handling, cross-day scenarios, time precision
- Ensure comprehensive coverage without knowing algorithm implementation
- All tests pass with optimized O(n log n) algorithm
- Performance test shows 8.50ms execution time for 400 date ranges

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* perf: improve intersect function in slots (#22087)

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: Benny Joo <sldisek783@gmail.com>
2025-07-04 00:00:31 +01:00
Omar LópezandBenny Joo 5b1eb48e6b perf: optimize google's getAvailability with caching (#22191)
* refactor: optimize google's getAvailability with caching

Refactored the getAvailability method to improve readability and efficiency by extracting logic into helper methods for cache checking, calendar ID retrieval, and chunked API fetching. Added early cache lookup for selected calendar IDs, improved cache hit logging, and modularized the code for easier maintenance and future enhancements.

* Update CalendarService.test.ts

* Update CalendarService.ts

* Update CalendarService.test.ts

* Update CalendarService.ts

* Update CalendarService.test.ts

* Update CalendarService.ts

* Apply suggestion from @hbjORbj

Co-authored-by: Benny Joo <sldisek783@gmail.com>

---------

Co-authored-by: Benny Joo <sldisek783@gmail.com>
2025-07-03 22:53:56 +00:00
zomars da6fc9f2d5 chore: release v5.4.13
Post release / release (push) Canceled after 0s
2025-07-03 21:10:47 +00:00
Keith Williamsandcubic-dev-ai[bot] 20434856e9 fix: Don't continue retrying SMS reminders infinitely (#22251)
* fix: Don't continue retrying SMS reminders infinitely

* Update packages/features/ee/workflows/api/scheduleSMSReminders.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-07-03 21:02:08 +00:00
Joe Au-YeungandUdit Takkar 7f891adff2 feat: Salesforce - write assignment reason to record (#22223)
* Create `assignmentReasonRepository`

* Write `assignmentReason` to booking

* Type fix

* Clean up

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-07-03 20:56:36 +00:00
eb66fbe054 feat: add Video Options dropdown with meeting session details (#22147)
* feat: add Video Options dropdown with meeting session details

- Add Video Options dropdown to BookingListItem for Daily video bookings
- Move recording actions from TableActions to new dropdown
- Add meeting session details feature with participant info, join times, duration
- Create new tRPC endpoint for fetching Daily.co meeting information
- Add getMeetingInformation method to VideoApiAdapter
- Create MeetingSessionDetailsDialog component following ViewRecordingsDialog pattern
- Add translation strings for new UI elements
- Update VideoApiAdapter TypeScript interface

Co-Authored-By: udit@cal.com <udit222001@gmail.com>

* fix: bugs and types

* Update packages/app-store/dailyvideo/lib/VideoApiAdapter.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Update packages/app-store/dailyvideo/lib/VideoApiAdapter.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-07-04 01:47:48 +05:30
Lauris Skraucis 29122934a9 fix: atoms local (#22245)
* Revert "fix: atoms for local development (#22178)"

This reverts commit d74d99dde7.

* chore: remove comment

* feat: local dev scripts

* feat: local dev scripts
2025-07-03 16:45:23 +00:00
manthansubhash01andKartik Saini 0825cce82c fix(ui): improve delete popup spacing on tablets and small screens (#22042)
Co-authored-by: Kartik Saini <41051387+kart1ka@users.noreply.github.com>
2025-07-03 16:19:19 +00:00
fd964131d1 fix: add formatPeriodFull method for different date formatting in insights (#22202)
* feat: add formatPeriodStraightforward method for comprehensive date formatting

- Add new formatPeriodStraightforward method that always shows full date information
- Update DateRange interface to include formattedDateStraightforward field
- Modify getDateRanges to generate both formatted versions
- Add comprehensive unit tests for the new straightforward formatting
- Maintain backward compatibility with existing formatPeriod method

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* refactor: rename formatPeriodStraightforward to formatPeriodFull

- Rename method from formatPeriodStraightforward to formatPeriodFull
- Rename interface field from formattedDateStraightforward to formattedDateFull
- Update all test cases to use new method name
- All tests continue to pass with new naming

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* test: add comprehensive getDateRanges formatting comparison tests

- Add 7 new test cases that call getDateRanges directly
- Demonstrate side-by-side comparison of formattedDate vs formattedDateFull
- Cover daily, weekly, and monthly view formatting differences
- Include real-world usage examples showing practical benefits
- All 65 tests pass including new formatting comparison tests

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* refactor: extract formattedDate arrays in getDateRanges comparison tests

- Refactor all 6 tests in 'getDateRanges - Formatting Comparison' suite
- Extract formattedDate and formattedDateFull arrays separately
- Use clean expect statements for easier visual review
- Remove startDate/endDate checks as requested
- Maintain all existing test scenarios and expected values

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* clean up

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Benny Joo <sldisek783@gmail.com>
2025-07-03 16:01:44 +00:00
Lauris Skraucis 77d9c15fed fix: atoms local dev (#22240)
* fix: atoms for local development

* fix: atoms for local development
2025-07-03 16:42:57 +02:00
Morgan b21295f268 chore: add user org id to user context apiv2 axiom (#22236) 2025-07-03 12:09:55 +00:00
5769553659 chore: add sharp as depdency on apiv1 (#22204)
* fix: Process base64 avatar image (#22165)

* fix: process base64 avatar image

* better name

* more

* fix import

* Attempt to fix sharp dependency issue by upgrading next

---------

Co-authored-by: Benny Joo <sldisek783@gmail.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-07-03 12:52:14 +01:00
devin-ai-integration[bot]andalex@cal.com d23d68bf2d fix: add explicit type annotation to CalComAdapter function (#22230)
* fix: add explicit type annotation to CalComAdapter function

Resolves TS7056 error where inferred type exceeded maximum length
the compiler will serialize. Added custom CalComAdapterType type
annotation to provide explicit typing while preserving existing
functionality of the authentication adapter.

The custom type annotation matches the actual implementation structure
and resolves the TypeScript compilation error without breaking the
existing NextAuth adapter functionality.

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* fix: replace any types with proper NextAuth Adapter typing

- Import Awaitable type from next-auth for proper async typing
- Define CalComAdapter type using Cal.com's actual Prisma types
- Remove all any types following TypeScript best practices
- Maintain compatibility with NextAuth's expected interface
- Resolves TS7056 compilation error with explicit typing

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: alex@cal.com <me@alexvanandel.com>
2025-07-03 11:37:15 +01:00
Morgan d04c7f58a1 chore: stringify user context ids apiv2 axiom (#22234) 2025-07-03 10:12:32 +00:00
Keith WilliamsandDevin AI 93e2426760 perf: optimize filterRedundantDateRanges from O(n²) to O(n log n) (#22093)
* perf: optimize filterRedundantDateRanges from O(n²) to O(n log n)

- Replace nested loop with optimized algorithm that leverages sorted ranges
- Add valueOf caching to avoid repeated .valueOf() calls (similar to PR #22076)
- Implement early termination for ranges that start after current range ends
- Handle identical ranges correctly by keeping first occurrence
- Add comprehensive test coverage with 8 new test cases covering:
  - Multiple nested containments
  - Identical ranges
  - Same start/end time edge cases
  - Invalid ranges (end before start)
  - Large dataset performance (100 ranges)
  - Touching ranges (adjacent ranges)

All 11 tests pass, maintaining behavioral compatibility while improving performance.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* revert: remove valueOf caching optimization, keep O(n log n) algorithm

- Remove cached valueOf() variables to address user feedback
- Keep algorithmic optimization with early termination logic
- Maintain O(n log n) complexity through sorted range leveraging
- All 11 tests continue to pass with identical functionality

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: correct identical range handling in O(n log n) optimization

- Remove complex conditional logic that caused incorrect filtering of identical ranges
- Revert to simple containment check while preserving O(n log n) performance
- All 10 comprehensive unit tests now pass
- Maintains early termination optimization for performance gains

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: correct identical range handling to keep first occurrence

- Update test expectation from 0 to 1 for three identical ranges
- Modify implementation to keep first occurrence of identical ranges
- Maintain O(n log n) performance optimization
- All 10 unit tests now pass

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* feat: implement interval tree for O(n log n) worst-case complexity

- Replace nested loop with interval tree data structure
- Achieve O(n log n) worst-case complexity vs previous O(n²)
- Maintain identical range handling logic
- Preserve all existing test compatibility
- Performance improvements: 1.08x-2.46x speedup across scenarios
- Note: Enterprise pattern correctness issue requires investigation

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* feat: implement interval tree for O(n log n) worst-case complexity

- Replace segment tree with interval tree data structure
- Achieve O(n log n) worst-case complexity vs previous O(n²)
- Maintain identical range handling logic
- All unit tests (10/10) and integration tests (5/5) pass
- Type checking passes with no errors
- Still investigating enterprise pattern correctness issue (499 vs 379 results)

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* feat: implement interval tree for O(n log n) worst-case complexity

- Replace nested loop with interval tree data structure
- Achieve O(n log n) worst-case complexity vs previous O(n²)
- Maintain identical range handling logic
- Preserve all existing test compatibility

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: remove redundant sort in interval tree constructor

- Fix index misalignment issue causing correctness problems
- Remove duplicate sorting of nodes after mapping
- Maintain proper index references for containment queries

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* feat: implement interval tree for O(n log n) worst-case complexity

- Replace nested loop with interval tree data structure
- Achieve O(n log n) worst-case complexity vs previous O(n²)
- Maintain identical range handling logic
- Preserve all existing test compatibility

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: simplify interval tree logic to match original behavior

- Remove complex identical range handling logic
- Filter out any range that has containing intervals
- Achieve O(n log n) worst-case complexity with correct behavior
- Fix 'should handle three identical ranges' test failure

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* feat: implement interval tree for O(n log n) worst-case complexity

- Replace hybrid algorithm with interval tree data structure
- Achieve O(n log n) worst-case complexity vs previous O(n²)
- Fix identical range handling to keep first occurrence
- Maintain all existing test compatibility
- Update test expectation for three identical ranges to return 1 result

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: resolve TypeScript errors in interval tree implementation

- Add explicit type annotations for sort function parameters
- Use Array.from() for Map iteration to ensure TypeScript compatibility
- Maintain O(n log n) worst-case complexity with type safety

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* feat: implement interval tree for O(n log n) worst-case complexity

- Replace hybrid algorithm with pure interval tree data structure
- Achieve O(n log n) worst-case complexity vs previous O(n²)
- Maintain balanced tree structure for efficient containment queries
- Preserve all existing test compatibility
- Performance improvements: 1.12x-2.36x speedup depending on scenario

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* refactor: extract IntervalTree to generic reusable implementation

- Move IntervalTree and IntervalNode to separate packages/lib/intervalTree.ts
- Make IntervalTree generic with type parameter <T> and function parameters for start/end extraction
- Update filterRedundantDateRanges.ts to use generic IntervalTree implementation
- Maintain O(n log n) worst-case complexity and all existing functionality
- All unit tests (10/10) and integration tests (5/5) passing

Addresses GitHub comment from @keithwillcode requesting generic, reusable interval tree

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: correct containment logic in interval tree implementation

- Fix unconditional 'return false' that incorrectly filtered non-contained ranges
- Maintain O(n log n) complexity while ensuring correct containment behavior
- Add test case for overlapping but non-containing ranges
- Addresses cubic-dev-ai[bot] comment on PR #22093

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* test: add comprehensive test coverage for cubic-dev-ai bug scenario

- Add test for overlapping but non-containing ranges
- Add test for complex overlapping pattern that exposed the cubic-dev-ai bug
- These tests would have caught the unconditional 'return false;' logic error
- Addresses test coverage gap that allowed the bug to slip through

The original test suite focused on clear containment scenarios but missed
complex overlapping patterns where interval tree finds false positives
that need proper filtering logic.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* refactor: separate IntervalTree structure from search algorithm

- Extract ContainmentSearchAlgorithm to separate class
- Make IntervalTree generic and reusable for different search patterns
- Maintain existing API compatibility for filterRedundantDateRanges
- Address GitHub feedback from @keithwillcode

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* refactor: make IntervalTree truly generic by moving node construction outside

- Extract createIntervalNodes helper function for date-specific node construction
- Remove start/end/maxEnd property handling from IntervalTree constructor
- Make IntervalTree accept pre-constructed nodes instead of raw items
- Move date-specific logic to filterRedundantDateRanges caller
- Addresses GitHub feedback from @keithwillcode about generic tree structure
- Maintains O(n log n) performance and all existing functionality

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* perf: eliminate redundant sorting in IntervalTree implementation

- Remove duplicate sort in IntervalTree constructor
- Sort interval nodes once in filterRedundantDateRanges after creation
- Addresses @Udit-takkar's performance feedback on PR #22093
- Maintains O(n log n) complexity while reducing constant factors

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: remove redundant sorting of interval nodes

- Eliminates unnecessary .sort() operation on interval nodes
- Nodes are already sorted from initial sortedRanges sort
- Addresses @keithwillcode's performance feedback

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-07-03 10:59:33 +01:00
Hariom BalharaandAlex van Andel 9f6c05f389 fix: Avoid prerender duplicate calls for same calLink that could arise with faulty implementation (#21982)
* fix: Avoid prerender duplicate calls

* Update README

* Ensure "noAction" action occurs if nothing changes

* fix bug

* Introduce connect method for reliable re-use

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-07-03 10:51:13 +01:00
Hariom BalharaandAnik Dhabal Babu f8a1bd7b94 fix: Don't default to ROUND_ROBIN as user bookings don't have it set (#22210)
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-07-03 10:15:55 +05:30
Omar LópezandDevin AI 02967961f3 fix: use triggering user's email/name in draft-release workflow (#22229)
Co-authored-by: zomars@cal.com <zomars@me.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-07-03 02:49:00 +00:00
Keith WilliamsandDevin AI 053b8b5c0a fix: resolve race condition in ready-for-e2e label checking (#22222)
- Simplify conditional logic in check-label job output
- Remove redundant condition that caused race condition
- Maintain event filtering to only run when ready-for-e2e label is added
- Fixes issue where workflow failed despite script finding the label correctly

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-07-03 00:21:43 +00:00
Keith Williams d59efd3ba0 chore: Ignore 'dba' for labeling (#22216) 2025-07-02 23:36:02 +00:00
GitHub Actions ce56cd1ab0 chore: release v5.4.12
Post release / release (push) Canceled after 0s
2025-07-02 21:05:34 +00:00
Romit 54b6deee19 fix (#22117) 2025-07-02 23:06:28 +05:30
abhix4 8315641724 fix: the icon in ooo empty view in light mode (#22208) 2025-07-02 22:50:20 +05:30
Anik Dhabal Babu aa3086cfae fix: Can cancel an already cancelled booking through the API (#22128)
* fix: can cancel already cancelled booking

* add test

* fix test

* update

* Update bookings.service.ts

* add commnet

* update

* tweak
2025-07-02 08:40:57 -04:00
devin-ai-integration[bot]andmorgan@cal.com b599ce4919 feat: add user context logging to request interceptor (#22180)
- Import extractUserContext function from @/lib/extract-user-context
- Extract user context from request in intercept method
- Add user context to logger output using spread operator
- Follow same pattern as exception filters for consistency

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: morgan@cal.com <morgan@cal.com>
2025-07-01 21:08:31 +00:00
Benny Joo 52f16604c1 feat: Use a separate project for Client Sentry (#22183) 2025-07-01 19:26:51 +00:00
Benny Joo c98c06062b revert: Process Base64 Avatar Image (#22185)
* Revert "chore: add test for updateProfilePhotoGoogle (#22169)"

This reverts commit 67032ddaf1.

* Revert "fix: Process base64 avatar image (#22165)"

This reverts commit d8d8bc4d00.
2025-07-01 18:38:32 +00:00
Carina WollendorferandCarinaWolli 4963d247dc fix: don't use unpublished org for credit usage (#22154)
* only return publichsed orgs

* fix twilioWebhook tests

* code clean up

* add missing import

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2025-07-01 16:04:13 +00:00
9405bc9553 feat: enable stripe invoices for credit purchases (#22096)
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Benny Joo <sldisek783@gmail.com>
2025-07-01 16:01:53 +00:00
8a080b91b9 feat: add timezone indicator on insights for unmatched timezone (#21568)
* feat: adds timezone indicator on insights informing user that user settings timezone is used instead of browser timezone

* added i18 helper for translation

* chore: use entities.decodeHTML instead of custom decoder

* feat(insights): align TimezoneBadge with new timeZone prop flow

* chore

* chore: smaller icon

* do not escape value

---------

Co-authored-by: Kartik Saini <41051387+kart1ka@users.noreply.github.com>
Co-authored-by: Eunjae Lee <hey@eunjae.dev>
2025-07-01 12:49:21 +00:00
Lauris Skraucis 4aa05fe523 docs: releasing atoms (#22160) 2025-07-01 17:54:47 +05:30
Lauris Skraucis d74d99dde7 fix: atoms for local development (#22178)
* fix: atoms for local development

* fix: atoms for local development
2025-07-01 17:33:22 +05:30
Parteek malikandSomay Chauhan 0ee137efbb fix: passing props (#21670)
Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com>
2025-07-01 11:21:25 +00:00
GitHub Actions 90f55670dc chore: release v5.4.11
Post release / release (push) Canceled after 0s
2025-07-01 11:06:49 +00:00
Anik Dhabal Babu 9c53f392ca fix: Optional Question ' Leaves Variable Tag in Event Name (#22175) 2025-07-01 10:50:41 +00:00
Morganandcubic-dev-ai[bot] cc19a81875 chore: deprecate platform libraries 0.0.2 (#22149)
* chore: deprecate platform libraries 0.0.2

* fixup! chore: deprecate platform libraries 0.0.2

* Update packages/lib/server/repository/schedule.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Update apps/api/v2/src/ee/schedules/schedules_2024_04_15/services/schedules.service.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* chore: bump platform libs

* Update apps/api/v2/src/ee/event-types/event-types_2024_04_15/controllers/event-types.controller.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* chore: bump platform libs

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-07-01 10:23:58 +00:00
Benny Joo 67032ddaf1 chore: add test for updateProfilePhotoGoogle (#22169)
* fix: process base64 avatar image

* better name

* more

* fix import

* add test

* util

* clean up

* address
2025-07-01 11:06:57 +01:00
2fe71c3695 refactor: destination calendars when rescheduling (#21873)
* refactor: destination calendars when rescheduling

* test: add unit test for collective evnet type

* chore: remove log

* chore: bump libraries

* fix: test

* chore: bump libraries

* fix: tests

* reset lock file

* Revert "reset lock file"

This reverts commit 4d48b678778b0daa19624338b302478e4655d200.

* Revert "Revert "reset lock file""

This reverts commit a7c3120c926a0d37a2b55a6ff8d2a070969ec0f4.

* regenerate lock file

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: Udit Takkar <udit222001@gmail.com>
2025-07-01 12:07:48 +03:00
21422fe027 feat: enhance API v2 exception filters with user context for improved Axiom observability (#22157)
* feat: enhance API v2 exception filters with user context for improved Axiom observability

- Add extractUserContext utility to safely extract user/org/team context from request
- Enhance all 5 exception filters (HTTP, TRPC, Prisma, Zod, Calendar) with user context
- Include userId, userEmail, organizationId, teamId in Axiom logs when available
- Improve observability for debugging and monitoring authenticated requests

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* chore: update yarn.lock from lint-staged hooks

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* fix: use request.organization instead of request.organizationId

- Address GitHub comment feedback from ThyMinimalDev
- Extract organization ID from organization object for consistency
- Follows same pattern as user and team extraction

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* fix: revert to using request.organizationId as requested in GitHub comment

- Change back from request.organization to request.organizationId
- This aligns with how auth strategies actually populate the request object
- Addresses GitHub comment from ThyMinimalDev

Co-Authored-By: morgan@cal.com <morgan@cal.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: morgan@cal.com <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2025-07-01 10:05:21 +03:00
Devanshu Sharma 95575291ff feat: add Finnish locale to Day.js locales (#22174) 2025-07-01 07:01:32 +00:00
KartikandKartik Saini 3e61a0633d prevent info icon from repositioning when text wraps on small screens (#22132)
Co-authored-by: Kartik Saini <41051387+kart1ka@users.noreply.github.com>
2025-07-01 09:32:41 +05:30
abhix4 85c9a790f2 fix: prevent location input from losing focus after each key stroke (#22167)
* fix: prevent location input from losing focus after each key stroke

* typo
2025-07-01 03:54:35 +00:00
Omar López e17d55457f refactor: cookie domain logic in defaultCookies (#22168) 2025-06-30 20:21:16 +00:00
Benny Joo d8d8bc4d00 fix: Process base64 avatar image (#22165)
* fix: process base64 avatar image

* better name

* more

* fix import
2025-06-30 21:08:46 +01:00
Udit TakkarandAlex van Andel 55cc1aea59 perf: optimize listWithTeamHandler query (#22069)
* perf: optimize listWithTeamHandler query

* chore: update query

* chore: add accepted true

* Update packages/trpc/server/routers/viewer/eventTypes/listWithTeam.handler.ts

* test: add integration test for the sql query

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-06-30 18:35:49 +00:00
GitHub Actions ae383164bc chore: release v5.4.10
Post release / release (push) Canceled after 0s
2025-06-30 13:22:55 +00:00
GitHub Actions 0d8863fe8e chore: release v5.4.10 2025-06-30 13:02:06 +00:00
GitHub Actions 51f6654635 chore: release v5.5.0 2025-06-30 12:39:41 +00:00
Eunjae LeeandDevin AI fa11e10bcb feat: remove 3-attendee limitation from CSV export (#22092)
Co-authored-by: eunjae@cal.com <hey@eunjae.dev>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-06-30 12:28:54 +00:00
github-actions[bot] a8f5bd6fe9 chore: version packages (#22152)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-06-30 11:16:15 +00:00
Lauris Skraucis a1c725bb35 refactor: atoms peer deps (#22153) 2025-06-30 10:22:45 +00:00
Anik Dhabal BabuandHariom Balhara e4eeb11a61 fix: fix request reschedule - not allowing reschedule of cancelled booking (#22115)
* fix: fix broken request reschdule feature

* Update getServerSideProps.ts

---------

Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2025-06-30 09:56:45 +00:00
Udit TakkarandHariom 3b0bb25251 fix: status code or router/embed rate limiting (#21968)
* fix: status code or router embed rate limiting

* fix: type err

* fix: handle api v2

* fix: status code

* chore: remove unused

* chore: update unit test

* chore: unit test

* refactor: make res required

* chore: remove unused

* chore: add a wrapper in getserversideprops

* chore: remlove log

* Add ratelLimiting unit test

---------

Co-authored-by: Hariom <hariombalhara@gmail.com>
2025-06-30 14:58:44 +05:30
Lauris Skraucis d27490e6f2 fix: atoms dist size (#22148)
* fix: reduce atoms dist size

* test changesets entry

* bump version
2025-06-30 09:26:08 +00:00
Anik Dhabal BabuandUdit Takkar b3c191b553 fix: truncate zoom meeting agenda (#22137)
* fix truncate zoom agenda

* type error

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-06-30 08:45:13 +00:00
Anik Dhabal Babuandcubic-dev-ai[bot] 0b977e615d fix: exclude opt out message from body (#22100)
* fix: exclude opt out

* Update packages/features/ee/workflows/api/scheduleSMSReminders.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-06-30 08:17:36 +00:00
621 changed files with 32222 additions and 7314 deletions
+1
View File
@@ -164,6 +164,7 @@ SENTRY_PROJECT=
SENTRY_AUTH_TOKEN=
# Used for capturing exceptions and logging messages
NEXT_PUBLIC_SENTRY_DSN=
NEXT_PUBLIC_SENTRY_DSN_CLIENT=
SENTRY_DEBUG=
SENTRY_MAX_SPANS=
SENTRY_SAMPLE_RATE=
+1
View File
@@ -23,6 +23,7 @@
/packages/lib/getUserAvailability.ts @calcom/Foundation
/packages/lib/server/getLuckyUser.ts @calcom/Foundation
/packages/lib/slots.ts @calcom/Foundation
/packages/platform/atoms/**/*WebWrapper.tsx @calcom/Consumer
/packages/platform/**/* @calcom/Platform @calcom/Foundation
/packages/prisma/**/* @calcom/DBA
/packages/trpc/server/routers/viewer/bookings/confirm.handler.ts @calcom/Foundation
+18 -2
View File
@@ -27,8 +27,24 @@ jobs:
- name: Configure git
run: |
git config --local user.email "github-actions@github.com"
git config --local user.name "GitHub Actions"
# Define authorized users and their emails using organization secret
# Expected format: JSON object with username -> email mapping
# Example: {"zomars": "zomars@cal.com", "peer": "peer@cal.com", "username3": "email3@cal.com"}
USER_EMAILS='${{ secrets.RELEASE_USER_EMAILS }}'
# Extract email for the triggering user
USER_EMAIL=$(echo "$USER_EMAILS" | jq -r --arg user "${{ github.actor }}" '.[$user] // empty')
# Fail if user is not authorized or not in mapping
if [ -z "$USER_EMAIL" ] || [ "$USER_EMAIL" = "null" ]; then
echo "Error: User '${{ github.actor }}' is not authorized to run the release workflow."
echo "Only authorized team members can trigger releases."
echo "Contact your administrator to be added to the authorized users list."
exit 1
fi
git config --local user.email "$USER_EMAIL"
git config --local user.name "${{ github.actor }}"
- uses: ./.github/actions/yarn-install
+1 -1
View File
@@ -26,7 +26,7 @@ jobs:
e2e:
timeout-minutes: 20
name: E2E API v2
runs-on: buildjet-8vcpu-ubuntu-2204
runs-on: buildjet-16vcpu-ubuntu-2204
services:
postgres:
image: postgres:13
+4
View File
@@ -17,6 +17,10 @@ jobs:
pull-requests: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- uses: lingodotdev/lingo.dev@main
env:
GH_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }}
+1 -1
View File
@@ -26,7 +26,7 @@ jobs:
with:
repo-token: ${{ secrets.EQUITY_BEE_TEAM_LABELER_ACTION_TOKEN }}
organization-name: calcom
ignore-labels: "admin, app-store, ai, authentication, automated-testing, devops, billing, bookings, caldav, calendar-apps, ci, console, crm-apps, docs, documentation, emails, embeds, event-types, i18n, impersonation, manual-testing, ui, performance, ops-stack, organizations, public-api, routing-forms, seats, teams, webhooks, workflows, zapier"
ignore-labels: "admin, app-store, ai, authentication, automated-testing, billing, bookings, caldav, calendar-apps, ci, console, crm-apps, dba, devops, docs, documentation, emails, embeds, event-types, i18n, impersonation, manual-testing, ui, performance, ops-stack, organizations, public-api, routing-forms, seats, teams, webhooks, workflows, zapier"
apply-labels-from-issue:
runs-on: ubuntu-latest
+1 -1
View File
@@ -46,7 +46,7 @@ jobs:
permissions:
pull-requests: read
outputs:
run-e2e: ${{ steps.check-if-pr-has-label.outputs.run-e2e == 'true' && (github.event.action != 'labeled' || (github.event.action == 'labeled' && github.event.label.name == 'ready-for-e2e')) }}
run-e2e: ${{ steps.check-if-pr-has-label.outputs.run-e2e == 'true' && (github.event.action != 'labeled' || github.event.label.name == 'ready-for-e2e') }}
steps:
- name: Check if PR exists with ready-for-e2e label for this SHA
id: check-if-pr-has-label
+2
View File
@@ -0,0 +1,2 @@
undecided:
- "@calcom/prisma"
View File
View File
+2
View File
@@ -0,0 +1,2 @@
undecided:
- "@calcom/prisma"
View File
View File
+2
View File
@@ -0,0 +1,2 @@
undecided:
- "@calcom/prisma"
View File
+2
View File
@@ -0,0 +1,2 @@
undecided:
- "@calcom/prisma"
+8
View File
@@ -0,0 +1,8 @@
undecided:
- calcom-monorepo
- "@calcom/app-store-cli"
- "@calcom/platform-constants"
- "@calcom/platform-enums"
- "@calcom/platform-types"
- "@calcom/platform-utils"
- "@calcom/prisma"
+2
View File
@@ -0,0 +1,2 @@
undecided:
- "@calcom/prisma"
View File
+8
View File
@@ -0,0 +1,8 @@
undecided:
- calcom-monorepo
- "@calcom/app-store-cli"
- "@calcom/platform-constants"
- "@calcom/platform-enums"
- "@calcom/platform-types"
- "@calcom/platform-utils"
- "@calcom/prisma"
+2
View File
@@ -0,0 +1,2 @@
undecided:
- "@calcom/prisma"
+1 -6
View File
@@ -488,13 +488,8 @@ Don't code but still want to contribute? Join our [Discussions](https://github.c
- Set CSP_POLICY="non-strict" env variable, which enables [Strict CSP](https://web.dev/strict-csp/) except for unsafe-inline in style-src . If you have some custom changes in your instance, you might have to make some code change to make your instance CSP compatible. Right now it enables strict CSP only on login page and on other SSR pages it is enabled in Report only mode to detect possible issues. On, SSG pages it is still not supported.
## Single Org Mode
If you want to have booker.yourcompany.com to be the domain used for both dashboard(e.g. https://booker.yourcompany.com/event-types) and booking pages(e.g. https://booker.yourcompany.com/john.joe/15min).
- Set the `NEXT_PUBLIC_SINGLE_ORG_SLUG` environment variable to the slug of the organization you want to use. `NEXT_PUBLIC_SINGLE_ORG_SLUG=booker`
- Set the `NEXT_PUBLIC_WEBAPP_URL` environment variable to the URL of the Cal.com self-hosted instance e.g. `NEXT_PUBLIC_WEBAPP_URL=https://booker.yourcompany.com`.
- Set the `NEXT_PUBLIC_WEBSITE_URL` environment variable to the URL of the Cal.com self-hosted instance e.g. `NEXT_PUBLIC_WEBSITE_URL=https://booker.yourcompany.com`.
- Set the `NEXTAUTH_URL` environment variable to the URL of the Cal.com self-hosted instance e.g. `NEXTAUTH_URL=https://booker.yourcompany.com`.
Refer to docs [here](./docs/self-hosting/guides/organization/single-organization-setup) for a detailed documentation with screenshots.
Note: It causes root to serve the dashboard and not the organization profile page which shows all bookable users in the organization.
## Integrations
@@ -23,6 +23,7 @@ afterEach(() => {
const mockDeploymentRepository: IDeploymentRepository = {
getLicenseKeyWithId: vi.fn().mockResolvedValue("mockLicenseKey"), // Mocked return value
getSignatureToken: vi.fn().mockResolvedValue("mockSignatureToken"),
};
// TODO: Fix the skip condition for this test suite
+1
View File
@@ -43,6 +43,7 @@ enum locales {
SR = "sr",
SV = "sv",
VI = "vi",
BN = "bn",
}
enum theme {
DARK = "dark",
+1 -1
View File
@@ -2,4 +2,4 @@
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
-3
View File
@@ -5,9 +5,6 @@ const plugins = [withAxiom];
/** @type {import("next").NextConfig} */
const nextConfig = {
experimental: {
instrumentationHook: true,
},
transpilePackages: [
"@calcom/app-store",
"@calcom/dayjs",
+1 -1
View File
@@ -33,7 +33,7 @@
"@sentry/nextjs": "^9.15.0",
"bcryptjs": "^2.4.3",
"memory-cache": "^0.2.0",
"next": "^13.5.9",
"next": "^15.3.0",
"next-api-middleware": "^1.0.1",
"next-axiom": "^0.17.0",
"next-swagger-doc": "^0.3.6",
+7
View File
@@ -222,6 +222,13 @@ async function handler(req: NextApiRequest) {
};
if (isSystemWideAdmin) userId = req.body.userId || userId;
if (req.body.eventTypeId !== undefined && typeof req.body.eventTypeId !== "number") {
throw new HttpError({
statusCode: 400,
message: "Bad request, eventTypeId must be a number",
});
}
if (isOrganizationOwnerOrAdmin) {
const accessibleUsersIds = await getAccessibleUsers({
adminUserId: userId,
@@ -105,7 +105,9 @@ async function getHandler(req: NextApiRequest) {
const userIds = req.query.userId ? extractUserIdsFromQuery(req) : [userId];
const usersWithCalendars = await UserRepository.findManyByIdsIncludeDestinationAndSelectedCalendars({
const usersWithCalendars = await new UserRepository(
prisma
).findManyByIdsIncludeDestinationAndSelectedCalendars({
ids: userIds,
});
+8 -2
View File
@@ -4,11 +4,11 @@ import type { NextApiRequest, NextApiResponse } from "next";
import dayjs from "@calcom/dayjs";
import { isSupportedTimeZone } from "@calcom/lib/dayjs";
import { getAvailableSlotsService } from "@calcom/lib/di/containers/available-slots";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import { createContext } from "@calcom/trpc/server/createContext";
import { getScheduleSchema } from "@calcom/trpc/server/routers/viewer/slots/types";
import { getAvailableSlots } from "@calcom/trpc/server/routers/viewer/slots/util";
import { TRPCError } from "@trpc/server";
import { getHTTPStatusCodeFromError } from "@trpc/server/http";
@@ -27,7 +27,13 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
}
const input = getScheduleSchema.parse({ usernameList: slugs, isTeamEvent: parsedIsTeamEvent, ...rest });
const timeZoneSupported = input.timeZone ? isSupportedTimeZone(input.timeZone) : false;
const availableSlots = await getAvailableSlots({ ctx: await createContext({ req, res }), input });
const availableSlotsService = getAvailableSlotsService();
const availableSlots = await availableSlotsService.getAvailableSlots({
ctx: await createContext({ req, res }),
input,
});
const slotsInProvidedTimeZone = timeZoneSupported
? Object.keys(availableSlots.slots).reduce(
(acc: Record<string, { time: string; attendees?: number; bookingUid?: string }[]>, date) => {
@@ -25,6 +25,44 @@ vi.mock("@calcom/lib/server/i18n", () => {
};
});
describe("POST /api/bookings - eventTypeId validation", () => {
test("String eventTypeId should return 400", async () => {
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "POST",
body: {
eventTypeId: "invalid-string",
},
});
await handler(req, res);
expect(res._getStatusCode()).toBe(400);
expect(JSON.parse(res._getData())).toEqual(
expect.objectContaining({
message: "Bad request, eventTypeId must be a number",
})
);
});
test("Number eventTypeId should not trigger validation error", async () => {
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "POST",
body: {
eventTypeId: 123,
},
});
await handler(req, res);
const statusCode = res._getStatusCode();
const responseData = JSON.parse(res._getData());
if (statusCode === 400) {
expect(responseData.message).not.toBe("Bad request, eventTypeId must be a number");
}
});
});
describe.skipIf(true)("POST /api/bookings", () => {
describe("Errors", () => {
test("Missing required data", async () => {
@@ -93,6 +93,8 @@ describe("POST /api/selected-calendars", () => {
watchAttempts: 0,
maxAttempts: 3,
unwatchAttempts: 0,
createdAt: new Date(),
updatedAt: new Date(),
});
await handler(req, res);
@@ -136,6 +138,8 @@ describe("POST /api/selected-calendars", () => {
watchAttempts: 0,
maxAttempts: 3,
unwatchAttempts: 0,
createdAt: new Date(),
updatedAt: new Date(),
});
await handler(req, res);
+1 -2
View File
@@ -38,8 +38,7 @@
"@axiomhq/winston": "^1.2.0",
"@calcom/platform-constants": "*",
"@calcom/platform-enums": "*",
"@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.231",
"@calcom/platform-libraries-0.0.2": "npm:@calcom/platform-libraries@0.0.2",
"@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.258",
"@calcom/platform-types": "*",
"@calcom/platform-utils": "*",
"@calcom/prisma": "*",
@@ -232,6 +232,15 @@ export class BookingsController_2024_04_15 {
}
if (bookingUid) {
const { bookingInfo } = await getBookingInfo(bookingUid);
if (!bookingInfo) {
throw new NotFoundException(`Booking with UID=${bookingUid} does not exist.`);
}
if (bookingInfo.status === "CANCELLED") {
throw new BadRequestException(
`Can't cancel booking with uid=${bookingUid} because it has been cancelled already. Please provide uid of a booking that is not cancelled.`
);
}
try {
req.body.uid = bookingUid;
const bookingRequest = await this.createNextApiBookingRequest(req, oAuthClientId, undefined, isEmbed);
@@ -443,7 +443,7 @@ export class BookingsController_2024_08_13 {
@Permissions([BOOKING_READ])
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
@ApiOperation({
summary: "Get 'Booking References' for a booking",
summary: "Get booking references",
})
@HttpCode(HttpStatus.OK)
async getBookingReferences(
@@ -1425,8 +1425,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
// @ts-ignore
const data: BookingOutput_2024_08_13 = responseBody.data;
expect(data.status).toEqual("cancelled");
createdBooking = data;
expect(data.rescheduledToUid).toEqual(rescheduledBooking.uid);
});
});
@@ -2553,6 +2552,59 @@ describe("Bookings Endpoints 2024-08-13", () => {
});
});
describe("cant't cancel already cancelled booking", () => {
it("should not be able to cancel alraedy cancelled booking", async () => {
const cancelledBooking = await bookingsRepositoryFixture.create({
status: "CANCELLED",
user: {
connect: {
id: user.id,
},
},
startTime: new Date(Date.UTC(2050, 0, 8, 13, 0, 0)),
endTime: new Date(Date.UTC(2050, 0, 8, 14, 0, 0)),
title: "peer coding lets goo",
uid: `cancelled-booking-${randomString()}`,
eventType: {
connect: {
id: eventTypeId,
},
},
location: "integrations:daily",
customInputs: {},
metadata: {},
responses: {
name: "Oldie",
email: "oldie@gmail.com",
},
attendees: {
create: {
email: "oldie@gmail.com",
name: "Oldie",
locale: "lv",
timeZone: "Europe/Rome",
},
},
});
const body: CancelBookingInput_2024_08_13 = {
cancellationReason: "Going on a vacation",
};
const response = await request(app.getHttpServer())
.post(`/v2/bookings/${cancelledBooking.uid}/cancel`)
.send(body)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set(X_CAL_CLIENT_ID, oAuthClient.id)
.expect(400);
expect(response.body.error.message).toEqual(
`Can't cancel booking with uid=${cancelledBooking.uid} because it has been cancelled already. Please provide uid of a booking that is not cancelled.`
);
await bookingsRepositoryFixture.deleteById(cancelledBooking.id);
});
});
describe("calendar events", () => {
beforeEach(() => {
jest.restoreAllMocks();
@@ -596,9 +596,9 @@ export class BookingsService_2024_08_13 {
} else if (isRecurring && isSeated) {
formattedBookings.push(this.outputService.getOutputRecurringSeatedBooking(formatted));
} else if (isSeated) {
formattedBookings.push(this.outputService.getOutputSeatedBooking(formatted));
formattedBookings.push(await this.outputService.getOutputSeatedBooking(formatted));
} else {
formattedBookings.push(this.outputService.getOutputBooking(formatted));
formattedBookings.push(await this.outputService.getOutputBooking(formatted));
}
}
@@ -186,6 +186,31 @@ export class InputBookingsService_2024_08_13 {
guests,
location,
},
...this.getRoutingFormData(inputBooking.routing),
};
}
private getRoutingFormData(
routing:
| {
teamMemberIds?: number[];
responseId?: number;
teamMemberEmail?: string;
skipContactOwner?: boolean;
crmAppSlug?: string;
crmOwnerRecordType?: string;
}
| undefined
) {
if (!routing) return null;
return {
routedTeamMemberIds: routing.teamMemberIds,
routingFormResponseId: routing.responseId,
teamMemberEmail: routing.teamMemberEmail,
skipContactOwner: routing.skipContactOwner,
crmAppSlug: routing.crmAppSlug,
crmOwnerRecordType: routing.crmOwnerRecordType,
};
}
@@ -453,6 +478,7 @@ export class InputBookingsService_2024_08_13 {
location,
},
schedulingType: eventType.schedulingType,
...this.getRoutingFormData(inputBooking.routing),
});
switch (timeBetween) {
@@ -711,6 +737,12 @@ export class InputBookingsService_2024_08_13 {
throw new NotFoundException(`Booking with uid=${bookingUid} not found`);
}
if (booking.status === "CANCELLED") {
throw new BadRequestException(
`Can't cancel booking with uid=${bookingUid} because it has been cancelled already. Please provide uid of a booking that is not cancelled.`
);
}
const oAuthClientParams = booking.eventTypeId
? await this.platformBookingsService.getOAuthClientParams(booking.eventTypeId)
: undefined;
@@ -90,7 +90,7 @@ type DatabaseMetadata = z.infer<typeof bookingMetadataSchema>;
export class OutputBookingsService_2024_08_13 {
constructor(private readonly bookingsRepository: BookingsRepository_2024_08_13) {}
getOutputBooking(databaseBooking: DatabaseBooking) {
async getOutputBooking(databaseBooking: DatabaseBooking) {
const dateStart = DateTime.fromISO(databaseBooking.startTime.toISOString());
const dateEnd = DateTime.fromISO(databaseBooking.endTime.toISOString());
const duration = dateEnd.diff(dateStart, "minutes").minutes;
@@ -101,6 +101,9 @@ export class OutputBookingsService_2024_08_13 {
);
const metadata = safeParse(bookingMetadataSchema, databaseBooking.metadata, defaultBookingMetadata);
const location = metadata?.videoCallUrl || databaseBooking.location;
const rescheduledToUid = databaseBooking.rescheduled
? await this.getRescheduledToUid(databaseBooking.uid)
: undefined;
const booking = {
id: databaseBooking.id,
@@ -109,8 +112,9 @@ export class OutputBookingsService_2024_08_13 {
description: databaseBooking.description,
hosts: [this.getHost(databaseBooking.user)],
status: databaseBooking.status.toLowerCase(),
cancellationReason: databaseBooking.cancellationReason || undefined,
cancelledByEmail: databaseBooking.cancelledBy || undefined,
cancellationReason:
databaseBooking.status === "CANCELLED" ? databaseBooking.cancellationReason : undefined,
cancelledByEmail: databaseBooking.status === "CANCELLED" ? databaseBooking.cancelledBy : undefined,
reschedulingReason: bookingResponses?.rescheduledReason,
rescheduledByEmail: databaseBooking.rescheduledBy || undefined,
rescheduledFromUid: databaseBooking.fromReschedule || undefined,
@@ -137,6 +141,7 @@ export class OutputBookingsService_2024_08_13 {
updatedAt: databaseBooking.updatedAt,
rating: databaseBooking.rating,
icsUid: databaseBooking.iCalUID,
rescheduledToUid,
};
const bookingTransformed = plainToClass(BookingOutput_2024_08_13, booking, { strategy: "excludeAll" });
@@ -146,6 +151,11 @@ export class OutputBookingsService_2024_08_13 {
return bookingTransformed;
}
async getRescheduledToUid(bookingUid: string) {
const rescheduledTo = await this.bookingsRepository.getByFromReschedule(bookingUid);
return rescheduledTo?.uid;
}
getUserDefinedMetadata(databaseMetadata: DatabaseMetadata) {
if (databaseMetadata === null) return {};
@@ -204,8 +214,9 @@ export class OutputBookingsService_2024_08_13 {
description: databaseBooking.description,
hosts: [this.getHost(databaseBooking.user)],
status: databaseBooking.status.toLowerCase(),
cancellationReason: databaseBooking.cancellationReason || undefined,
cancelledByEmail: databaseBooking.cancelledBy || undefined,
cancellationReason:
databaseBooking.status === "CANCELLED" ? databaseBooking.cancellationReason : undefined,
cancelledByEmail: databaseBooking.status === "CANCELLED" ? databaseBooking.cancelledBy : undefined,
reschedulingReason: bookingResponses?.rescheduledReason,
rescheduledByEmail: databaseBooking.rescheduledBy || undefined,
rescheduledFromUid: databaseBooking.fromReschedule || undefined,
@@ -244,20 +255,23 @@ export class OutputBookingsService_2024_08_13 {
return bookingTransformed;
}
getOutputCreateSeatedBooking(
async getOutputCreateSeatedBooking(
databaseBooking: DatabaseBooking,
seatUid: string
): CreateSeatedBookingOutput_2024_08_13 {
const getSeatedBookingOutput = this.getOutputSeatedBooking(databaseBooking);
): Promise<CreateSeatedBookingOutput_2024_08_13> {
const getSeatedBookingOutput = await this.getOutputSeatedBooking(databaseBooking);
return { ...getSeatedBookingOutput, seatUid };
}
getOutputSeatedBooking(databaseBooking: DatabaseBooking) {
async getOutputSeatedBooking(databaseBooking: DatabaseBooking) {
const dateStart = DateTime.fromISO(databaseBooking.startTime.toISOString());
const dateEnd = DateTime.fromISO(databaseBooking.endTime.toISOString());
const duration = dateEnd.diff(dateStart, "minutes").minutes;
const metadata = safeParse(bookingMetadataSchema, databaseBooking.metadata, defaultBookingMetadata);
const location = metadata?.videoCallUrl || databaseBooking.location;
const rescheduledToUid = databaseBooking.rescheduled
? await this.getRescheduledToUid(databaseBooking.uid)
: undefined;
const booking = {
id: databaseBooking.id,
@@ -266,7 +280,8 @@ export class OutputBookingsService_2024_08_13 {
description: databaseBooking.description,
hosts: [this.getHost(databaseBooking.user)],
status: databaseBooking.status.toLowerCase(),
cancellationReason: databaseBooking.cancellationReason || undefined,
cancellationReason:
databaseBooking.status === "CANCELLED" ? databaseBooking.cancellationReason : undefined,
rescheduledFromUid: databaseBooking.fromReschedule || undefined,
start: databaseBooking.startTime,
end: databaseBooking.endTime,
@@ -283,6 +298,7 @@ export class OutputBookingsService_2024_08_13 {
updatedAt: databaseBooking.updatedAt,
rating: databaseBooking.rating,
icsUid: databaseBooking.iCalUID,
rescheduledToUid,
};
const parsed = plainToClass(GetSeatedBookingOutput_2024_08_13, booking, { strategy: "excludeAll" });
@@ -375,7 +391,8 @@ export class OutputBookingsService_2024_08_13 {
description: databaseBooking.description,
hosts: [this.getHost(databaseBooking.user)],
status: databaseBooking.status.toLowerCase(),
cancellationReason: databaseBooking.cancellationReason || undefined,
cancellationReason:
databaseBooking.status === "CANCELLED" ? databaseBooking.cancellationReason : undefined,
rescheduledFromUid: databaseBooking.fromReschedule || undefined,
start: databaseBooking.startTime,
end: databaseBooking.endTime,
@@ -1,9 +1,9 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import type { Prisma } from "@prisma/client";
const credentialForCalendarRepositorySelect = Prisma.validator<Prisma.CredentialSelect>()({
const credentialForCalendarRepositorySelect = {
id: true,
appId: true,
type: true,
@@ -16,7 +16,7 @@ const credentialForCalendarRepositorySelect = Prisma.validator<Prisma.Credential
teamId: true,
key: true,
invalid: true,
});
} satisfies Prisma.CredentialSelect;
@Injectable()
export class CalendarsRepository {
@@ -1,6 +1,7 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { CreateIcsFeedOutput, CreateIcsFeedOutputResponseDto } from "@/ee/calendars/input/create-ics.output";
import { ConnectedCalendarsData } from "@/ee/calendars/outputs/connected-calendars.output";
import { DeletedCalendarCredentialsOutputResponseDto } from "@/ee/calendars/outputs/delete-calendar-credentials.output";
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
import { HttpExceptionFilter } from "@/filters/http-exception.filter";
@@ -30,7 +31,7 @@ import {
GOOGLE_CALENDAR_ID,
} from "@calcom/platform-constants";
import { OFFICE_365_CALENDAR_ID, OFFICE_365_CALENDAR_TYPE } from "@calcom/platform-constants";
import { ICS_CALENDAR } from "@calcom/platform-constants/apps";
import { ICS_CALENDAR, ICS_CALENDAR_TYPE } from "@calcom/platform-constants/apps";
import { IcsFeedCalendarService } from "@calcom/platform-libraries/app-store";
const CLIENT_REDIRECT_URI = "http://localhost:5555";
@@ -247,6 +248,35 @@ describe("Platform Calendars Endpoints", () => {
.expect(200);
});
it(`/GET/v2/calendars with access token`, async () => {
const response = await request(app.getHttpServer())
.get(`/v2/calendars`)
.set("Authorization", `Bearer ${accessTokenSecret}`)
.set("Origin", CLIENT_REDIRECT_URI)
.expect(200);
const data: ConnectedCalendarsData = response.body.data;
expect(data.connectedCalendars).toBeDefined();
expect(data.connectedCalendars).toHaveLength(3);
const googleConnectedCalendar = data.connectedCalendars.find(
(calendar) => calendar.integration.type === GOOGLE_CALENDAR_TYPE
);
const office365ConnectedCalendar = data.connectedCalendars.find(
(calendar) => calendar.integration.type === OFFICE_365_CALENDAR_TYPE
);
const icsConnectedCalendar = data.connectedCalendars.find(
(calendar) => calendar.integration.type === ICS_CALENDAR_TYPE
);
expect(googleConnectedCalendar).toBeDefined();
expect(office365ConnectedCalendar).toBeDefined();
expect(icsConnectedCalendar).toBeDefined();
expect(data.destinationCalendar).toBeDefined();
expect(data.destinationCalendar.integration).toEqual(GOOGLE_CALENDAR_TYPE);
});
it.skip(`/POST/v2/calendars/${OFFICE_365_CALENDAR}/disconnect: it should respond with a 201 returning back the user deleted calendar credentials`, async () => {
const body = {
id: 10,
@@ -157,7 +157,7 @@ export class CalendarsController {
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
@Get("/:calendar/connect")
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: "Get oAuth connect URL" })
@ApiOperation({ summary: "Get OAuth connect URL" })
@ApiQuery({
name: "redir",
required: false,
@@ -14,7 +14,7 @@ import {
NotFoundException,
} from "@nestjs/common";
import { User } from "@prisma/client";
import { Prisma } from "@prisma/client";
import type { Prisma } from "@prisma/client";
import { DateTime } from "luxon";
import { z } from "zod";
@@ -18,6 +18,7 @@ import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { UserWithProfile } from "@/modules/users/users.repository";
import {
@@ -33,13 +34,19 @@ import {
HttpStatus,
Delete,
Query,
Headers,
InternalServerErrorException,
ParseIntPipe,
} from "@nestjs/common";
import { ApiExcludeController as DocsExcludeController } from "@nestjs/swagger";
import { EVENT_TYPE_READ, EVENT_TYPE_WRITE, SUCCESS_STATUS } from "@calcom/platform-constants";
import { getPublicEvent, getEventTypesByViewer } from "@calcom/platform-libraries-0.0.2";
import {
EVENT_TYPE_READ,
EVENT_TYPE_WRITE,
SUCCESS_STATUS,
X_CAL_CLIENT_ID,
} from "@calcom/platform-constants";
import { getPublicEvent, getEventTypesByViewer } from "@calcom/platform-libraries/event-types";
import { PrismaClient } from "@calcom/prisma";
@Controller({
@@ -51,7 +58,8 @@ import { PrismaClient } from "@calcom/prisma";
export class EventTypesController_2024_04_15 {
constructor(
private readonly eventTypesService: EventTypesService_2024_04_15,
private readonly prismaReadService: PrismaReadService
private readonly prismaReadService: PrismaReadService,
private readonly organizationsRepository: OrganizationsRepository
) {}
@Post("/")
@@ -109,19 +117,32 @@ export class EventTypesController_2024_04_15 {
async getPublicEventType(
@Param("username") username: string,
@Param("eventSlug") eventSlug: string,
@Query() queryParams: GetPublicEventTypeQueryParams_2024_04_15
@Query() queryParams: GetPublicEventTypeQueryParams_2024_04_15,
@Headers(X_CAL_CLIENT_ID) clientId?: string
): Promise<GetEventTypePublicOutput> {
try {
let orgSlug = queryParams.org;
if (clientId && !orgSlug && username.includes(`-${clientId}`)) {
const org = await this.organizationsRepository
.findTeamIdAndSlugFromClientId(clientId)
.catch(() => null);
if (org) {
orgSlug = org.slug;
}
}
const event = await getPublicEvent(
username.toLowerCase(),
eventSlug,
queryParams.isTeamEvent,
queryParams.org || null,
orgSlug ?? null,
this.prismaReadService.prisma as unknown as PrismaClient,
// We should be fine allowing unpublished orgs events to be servable through platform because Platform access is behind license
// If there is ever a need to restrict this, we can introduce a new query param `fromRedirectOfNonOrgLink`
true
);
return {
data: event,
status: SUCCESS_STATUS,
@@ -2,6 +2,7 @@ import { EventTypesController_2024_04_15 } from "@/ee/event-types/event-types_20
import { EventTypesRepository_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/event-types.repository";
import { EventTypesService_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/services/event-types.service";
import { MembershipsModule } from "@/modules/memberships/memberships.module";
import { OrganizationsModule } from "@/modules/organizations/organizations.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { SelectedCalendarsModule } from "@/modules/selected-calendars/selected-calendars.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
@@ -9,7 +10,14 @@ import { UsersModule } from "@/modules/users/users.module";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule, MembershipsModule, TokensModule, UsersModule, SelectedCalendarsModule],
imports: [
PrismaModule,
MembershipsModule,
TokensModule,
UsersModule,
SelectedCalendarsModule,
OrganizationsModule,
],
providers: [EventTypesRepository_2024_04_15, EventTypesService_2024_04_15],
controllers: [EventTypesController_2024_04_15],
exports: [EventTypesService_2024_04_15, EventTypesRepository_2024_04_15],
@@ -1721,7 +1721,7 @@ describe("Event types Endpoints", () => {
description: "undefined booking fields",
length: 40,
hidden: false,
slug: "undefined-booking-fields",
slug: `undefined-booking-fields-${randomString()}`,
locations: [],
schedulingType: SchedulingType.ROUND_ROBIN,
};
@@ -1751,6 +1751,14 @@ describe("Event types Endpoints", () => {
disableOnPrefill: false,
hidden: false,
},
{
disableOnPrefill: false,
hidden: true,
isDefault: true,
required: false,
slug: "attendeePhoneNumber",
type: "phone",
},
{
isDefault: true,
type: "radioInput",
@@ -46,11 +46,10 @@ export class SchedulesController_2024_04_15 {
@Body() bodySchedule: CreateScheduleInput_2024_04_15
): Promise<CreateScheduleOutput_2024_04_15> {
const schedule = await this.schedulesService.createUserSchedule(user.id, bodySchedule);
const scheduleFormatted = await this.schedulesService.formatScheduleForAtom(user, schedule);
return {
status: SUCCESS_STATUS,
data: scheduleFormatted,
data: schedule,
};
}
@@ -60,13 +59,10 @@ export class SchedulesController_2024_04_15 {
@GetUser() user: UserWithProfile
): Promise<GetDefaultScheduleOutput_2024_04_15 | null> {
const schedule = await this.schedulesService.getUserScheduleDefault(user.id);
const scheduleFormatted = schedule
? await this.schedulesService.formatScheduleForAtom(user, schedule)
: null;
return {
status: SUCCESS_STATUS,
data: scheduleFormatted,
data: schedule,
};
}
@@ -77,23 +73,25 @@ export class SchedulesController_2024_04_15 {
@Param("scheduleId") scheduleId: number
): Promise<GetScheduleOutput_2024_04_15> {
const schedule = await this.schedulesService.getUserSchedule(user.id, scheduleId);
const scheduleFormatted = await this.schedulesService.formatScheduleForAtom(user, schedule);
return {
status: SUCCESS_STATUS,
data: scheduleFormatted,
data: schedule,
};
}
@Get("/")
@Permissions([SCHEDULE_READ])
async getSchedules(@GetUser() user: UserWithProfile): Promise<GetSchedulesOutput_2024_04_15> {
const schedules = await this.schedulesService.getUserSchedules(user.id);
const schedulesFormatted = await this.schedulesService.formatSchedulesForAtom(user, schedules);
const schedules = await this.schedulesService.getUserSchedules(
user.id,
user.timeZone,
user.defaultScheduleId
);
return {
status: SUCCESS_STATUS,
data: schedulesFormatted,
data: schedules,
};
}
@@ -3,7 +3,7 @@ import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import type { Prisma } from "@prisma/client";
@Injectable()
export class SchedulesRepository_2024_04_15 {
@@ -1,26 +1,22 @@
import { CreateAvailabilityInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-availability.input";
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
import { ScheduleOutput } from "@/ee/schedules/schedules_2024_04_15/outputs/schedule.output";
import { SchedulesRepository_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.repository";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { UserWithProfile, UsersRepository } from "@/modules/users/users.repository";
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
import { Schedule } from "@prisma/client";
import { User } from "@prisma/client";
import type { ScheduleWithAvailabilities } from "@calcom/platform-libraries-0.0.2";
import { updateScheduleHandler } from "@calcom/platform-libraries-0.0.2";
import {
transformWorkingHoursForClient,
transformAvailabilityForClient,
transformDateOverridesForClient,
} from "@calcom/platform-libraries-0.0.2";
import { updateSchedule } from "@calcom/platform-libraries/schedules";
import { ScheduleRepository } from "@calcom/platform-libraries/schedules";
import { UpdateScheduleInput_2024_04_15 } from "@calcom/platform-types";
import { PrismaClient } from "@calcom/prisma";
@Injectable()
export class SchedulesService_2024_04_15 {
constructor(
private readonly schedulesRepository: SchedulesRepository_2024_04_15,
private readonly usersRepository: UsersRepository
private readonly usersRepository: UsersRepository,
private readonly dbWrite: PrismaWriteService
) {}
async createUserDefaultSchedule(userId: number, timeZone: string) {
@@ -48,7 +44,9 @@ export class SchedulesService_2024_04_15 {
await this.usersRepository.setDefaultSchedule(userId, createdSchedule.id);
}
return createdSchedule;
const formattedSchedule = await this.getUserSchedule(userId, createdSchedule.id);
return formattedSchedule;
}
async getUserScheduleDefault(userId: number) {
@@ -56,11 +54,29 @@ export class SchedulesService_2024_04_15 {
if (!user?.defaultScheduleId) return null;
return this.schedulesRepository.getScheduleById(user.defaultScheduleId);
return await ScheduleRepository.findDetailedScheduleById({
scheduleId: user.defaultScheduleId,
isManagedEventType: undefined,
userId,
timeZone: user.timeZone,
defaultScheduleId: user.defaultScheduleId,
});
}
async getUserSchedule(userId: number, scheduleId: number) {
const existingSchedule = await this.schedulesRepository.getScheduleById(scheduleId);
const user = await this.usersRepository.findById(userId);
if (!user) {
throw new NotFoundException(`User with ID=${userId} does not exist.`);
}
const existingSchedule = await ScheduleRepository.findDetailedScheduleById({
scheduleId: scheduleId,
isManagedEventType: undefined,
userId,
timeZone: user.timeZone,
defaultScheduleId: user.defaultScheduleId,
});
if (!existingSchedule) {
throw new NotFoundException(`Schedule with ID=${scheduleId} does not exist.`);
@@ -71,8 +87,8 @@ export class SchedulesService_2024_04_15 {
return existingSchedule;
}
async getUserSchedules(userId: number) {
return this.schedulesRepository.getSchedulesByUserId(userId);
async getUserSchedules(userId: number, timeZone: string, defaultScheduleId: number | null) {
return ScheduleRepository.findManyDetailedScheduleByUserId({ userId, timeZone, defaultScheduleId });
}
async updateUserSchedule(
@@ -89,7 +105,6 @@ export class SchedulesService_2024_04_15 {
this.checkUserOwnsSchedule(user.id, existingSchedule);
const schedule = await this.getUserSchedule(user.id, Number(scheduleId));
const scheduleFormatted = await this.formatScheduleForAtom(user, schedule);
if (!bodySchedule.schedule) {
// note(Lauris): When updating an availability in cal web app, lets say only its name, also
@@ -97,12 +112,16 @@ export class SchedulesService_2024_04_15 {
// and they have same shape, so to match shapes I attach "scheduleFormatted.availability" to reflect
// schedule that would be passed by the web app. If we don't, then updating schedule name will erase
// schedule.
bodySchedule.schedule = scheduleFormatted.availability;
bodySchedule.schedule = schedule.availability;
}
return updateScheduleHandler({
input: { scheduleId: Number(scheduleId), ...bodySchedule },
ctx: { user },
return updateSchedule({
input: {
scheduleId: Number(scheduleId),
...bodySchedule,
},
user,
prisma: this.dbWrite.prisma as unknown as PrismaClient,
});
}
@@ -118,44 +137,6 @@ export class SchedulesService_2024_04_15 {
return this.schedulesRepository.deleteScheduleById(scheduleId);
}
async formatScheduleForAtom(user: User, schedule: ScheduleWithAvailabilities): Promise<ScheduleOutput> {
const usersSchedulesCount = await this.schedulesRepository.getUserSchedulesCount(user.id);
return this.transformScheduleForAtom(schedule, usersSchedulesCount, user);
}
async formatSchedulesForAtom(
user: User,
schedules: ScheduleWithAvailabilities[]
): Promise<ScheduleOutput[]> {
const usersSchedulesCount = await this.schedulesRepository.getUserSchedulesCount(user.id);
return Promise.all(
schedules.map((schedule) => this.transformScheduleForAtom(schedule, usersSchedulesCount, user))
);
}
async transformScheduleForAtom(
schedule: ScheduleWithAvailabilities,
userSchedulesCount: number,
user: Pick<User, "id" | "defaultScheduleId" | "timeZone">
): Promise<ScheduleOutput> {
const timeZone = schedule.timeZone || user.timeZone;
const defaultSchedule = await this.getUserScheduleDefault(user.id);
return {
id: schedule.id,
name: schedule.name,
isManaged: schedule.userId !== user.id,
workingHours: transformWorkingHoursForClient(schedule),
schedule: schedule.availability,
availability: transformAvailabilityForClient(schedule),
timeZone,
dateOverrides: transformDateOverridesForClient(schedule, timeZone),
isDefault: defaultSchedule?.id === schedule.id,
isLastSchedule: userSchedulesCount <= 1,
readOnly: schedule.userId !== user.id,
};
}
checkUserOwnsSchedule(userId: number, schedule: Pick<Schedule, "id" | "userId">) {
if (userId !== schedule.userId) {
throw new ForbiddenException(`User with ID=${userId} does not own schedule with ID=${schedule.id}`);
@@ -1,3 +1,4 @@
import { extractUserContext } from "@/lib/extract-user-context";
import { filterReqHeaders } from "@/lib/filterReqHeaders";
import { ArgumentsHost, Catch, ExceptionFilter, Logger } from "@nestjs/common";
import { Request } from "express";
@@ -39,6 +40,7 @@ export class CalendarServiceExceptionFilter implements ExceptionFilter {
const requestId = request.headers["X-Request-Id"] ?? "unknown-request-id";
response.setHeader("X-Request-Id", requestId.toString());
const userContext = extractUserContext(request);
this.logger.error(`Calendar Service Exception Filter: ${exception?.message}`, {
exception,
body: request.body,
@@ -46,6 +48,7 @@ export class CalendarServiceExceptionFilter implements ExceptionFilter {
url: request.url,
method: request.method,
requestId,
...userContext,
});
response.status(400).json({
@@ -1,3 +1,4 @@
import { extractUserContext } from "@/lib/extract-user-context";
import { filterReqHeaders } from "@/lib/filterReqHeaders";
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, Logger } from "@nestjs/common";
import { Request } from "express";
@@ -16,6 +17,7 @@ export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
const statusCode = exception.getStatus();
const requestId = request.headers["X-Request-Id"] ?? "unknown-request-id";
response.setHeader("X-Request-Id", requestId.toString());
const userContext = extractUserContext(request);
this.logger.error(`Http Exception Filter: ${exception?.message}`, {
exception,
body: request.body,
@@ -23,6 +25,7 @@ export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
url: request.url,
method: request.method,
requestId,
...userContext,
});
response.status(statusCode).json({
@@ -1,3 +1,4 @@
import { extractUserContext } from "@/lib/extract-user-context";
import { filterReqHeaders } from "@/lib/filterReqHeaders";
import type { ArgumentsHost, ExceptionFilter } from "@nestjs/common";
import { Catch, HttpStatus, Logger } from "@nestjs/common";
@@ -43,6 +44,7 @@ export class PrismaExceptionFilter implements ExceptionFilter {
const requestId = request.headers["X-Request-Id"] ?? "unknown-request-id";
response.setHeader("X-Request-Id", requestId.toString());
const userContext = extractUserContext(request);
this.logger.error(`PrismaError: ${error.message}`, {
error,
body: request.body,
@@ -50,6 +52,7 @@ export class PrismaExceptionFilter implements ExceptionFilter {
url: request.url,
method: request.method,
requestId,
...userContext,
});
let message = "There was an error, please try again later.";
@@ -1,3 +1,4 @@
import { extractUserContext } from "@/lib/extract-user-context";
import { filterReqHeaders } from "@/lib/filterReqHeaders";
import { ArgumentsHost, Catch, ExceptionFilter, Logger } from "@nestjs/common";
import { Request } from "express";
@@ -120,6 +121,7 @@ export class TRPCExceptionFilter implements ExceptionFilter {
const requestId = request.headers["X-Request-Id"] ?? "unknown-request-id";
response.setHeader("X-Request-Id", requestId.toString());
const userContext = extractUserContext(request);
this.logger.error(`TRPC Exception Filter: ${exception?.message}`, {
exception,
body: request.body,
@@ -127,6 +129,7 @@ export class TRPCExceptionFilter implements ExceptionFilter {
url: request.url,
method: request.method,
requestId,
...userContext,
});
response.status(statusCode).json({
@@ -1,3 +1,4 @@
import { extractUserContext } from "@/lib/extract-user-context";
import { filterReqHeaders } from "@/lib/filterReqHeaders";
import type { ArgumentsHost, ExceptionFilter } from "@nestjs/common";
import { Catch, HttpStatus, Logger } from "@nestjs/common";
@@ -18,6 +19,7 @@ export class ZodExceptionFilter implements ExceptionFilter {
const requestId = request.headers["X-Request-Id"] ?? "unknown-request-id";
response.setHeader("X-Request-Id", requestId.toString());
const userContext = extractUserContext(request);
this.logger.error(`ZodError: ${error.message}`, {
error,
body: request.body,
@@ -25,6 +27,7 @@ export class ZodExceptionFilter implements ExceptionFilter {
url: request.url,
method: request.method,
requestId,
...userContext,
});
response.status(HttpStatus.BAD_REQUEST).json({
@@ -3,4 +3,5 @@ export enum AuthMethods {
"ACCESS_TOKEN" = "access-token",
"OAUTH_CLIENT" = "oauth-client",
"NEXT_AUTH" = "next-auth",
"THIRD_PARTY_ACCESS_TOKEN" = "third_party_access_token",
}
+1
View File
@@ -41,4 +41,5 @@ export enum Locales {
TA = "ta",
UK = "uk",
ZH_TW = "zh-TW",
BN = "bn",
}
@@ -0,0 +1,38 @@
import { Request } from "express";
import { Team } from "@calcom/prisma/client";
import { ApiAuthGuardUser } from "../modules/auth/strategies/api-auth/api-auth.strategy";
export interface UserContext {
userId?: string;
userEmail?: string;
organizationId?: string;
teamId?: string;
userOrgId?: string;
}
export function extractUserContext(request: Request): UserContext {
const context: UserContext = {};
const user = (request as any).user as ApiAuthGuardUser | undefined;
if (user) {
context.userId = String(user.id);
context.userEmail = user.email;
if (user.profiles?.[0]?.organizationId) {
context.userOrgId = String(user.profiles?.[0].organizationId);
}
}
const organizationId = (request as any).organizationId as number | undefined;
if (organizationId) {
context.organizationId = String(organizationId);
}
const team = (request as any).team as Team | undefined;
if (team) {
context.teamId = String(team.id);
}
return context;
}
@@ -0,0 +1,28 @@
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
import { PrismaEventTypeRepository } from "@/lib/repositories/prisma-event-type.repository";
import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";
import { PrismaRoutingFormResponseRepository } from "@/lib/repositories/prisma-routing-form-response.repository";
import { PrismaScheduleRepository } from "@/lib/repositories/prisma-schedule.repository";
import { PrismaSelectedSlotsRepository } from "@/lib/repositories/prisma-selected-slots.repository";
import { PrismaTeamRepository } from "@/lib/repositories/prisma-team.repository";
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
import { AvailableSlotsService } from "@/lib/services/available-slots.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule],
providers: [
PrismaOOORepository,
PrismaScheduleRepository,
PrismaBookingRepository,
PrismaSelectedSlotsRepository,
PrismaUserRepository,
PrismaEventTypeRepository,
PrismaRoutingFormResponseRepository,
PrismaTeamRepository,
AvailableSlotsService,
],
exports: [AvailableSlotsService],
})
export class AvailableSlotsModule {}
@@ -0,0 +1,12 @@
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { PrismaBookingRepository as PrismaBookingRepositoryLib } from "@calcom/platform-libraries/repositories";
import { PrismaClient } from "@calcom/prisma";
@Injectable()
export class PrismaBookingRepository extends PrismaBookingRepositoryLib {
constructor(private readonly dbWrite: PrismaWriteService) {
super(dbWrite.prisma as unknown as PrismaClient);
}
}
@@ -0,0 +1,12 @@
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { PrismaEventTypeRepository as PrismaEventTypeRepositoryLib } from "@calcom/platform-libraries/repositories";
import { PrismaClient } from "@calcom/prisma";
@Injectable()
export class PrismaEventTypeRepository extends PrismaEventTypeRepositoryLib {
constructor(private readonly dbWrite: PrismaWriteService) {
super(dbWrite.prisma as unknown as PrismaClient);
}
}
@@ -0,0 +1,12 @@
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { PrismaOOORepository as PrismaOOORepositoryLib } from "@calcom/platform-libraries/repositories";
import { PrismaClient } from "@calcom/prisma";
@Injectable()
export class PrismaOOORepository extends PrismaOOORepositoryLib {
constructor(private readonly dbWrite: PrismaWriteService) {
super(dbWrite.prisma as unknown as PrismaClient);
}
}
@@ -0,0 +1,12 @@
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { PrismaRoutingFormResponseRepository as PrismaRoutingFormResponseRepositoryLib } from "@calcom/platform-libraries/repositories";
import { PrismaClient } from "@calcom/prisma";
@Injectable()
export class PrismaRoutingFormResponseRepository extends PrismaRoutingFormResponseRepositoryLib {
constructor(private readonly dbWrite: PrismaWriteService) {
super(dbWrite.prisma as unknown as PrismaClient);
}
}
@@ -0,0 +1,12 @@
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { PrismaScheduleRepository as PrismaScheduleRepositoryLib } from "@calcom/platform-libraries/repositories";
import { PrismaClient } from "@calcom/prisma";
@Injectable()
export class PrismaScheduleRepository extends PrismaScheduleRepositoryLib {
constructor(private readonly dbWrite: PrismaWriteService) {
super(dbWrite.prisma as unknown as PrismaClient);
}
}
@@ -0,0 +1,12 @@
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { PrismaSelectedSlotsRepository as PrismaSelectedSlotsRepositoryLib } from "@calcom/platform-libraries/repositories";
import { PrismaClient } from "@calcom/prisma";
@Injectable()
export class PrismaSelectedSlotsRepository extends PrismaSelectedSlotsRepositoryLib {
constructor(private readonly dbWrite: PrismaWriteService) {
super(dbWrite.prisma as unknown as PrismaClient);
}
}
@@ -0,0 +1,12 @@
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { PrismaTeamRepository as PrismaTeamRepositoryLib } from "@calcom/platform-libraries/repositories";
import { PrismaClient } from "@calcom/prisma";
@Injectable()
export class PrismaTeamRepository extends PrismaTeamRepositoryLib {
constructor(private readonly dbWrite: PrismaWriteService) {
super(dbWrite.prisma as unknown as PrismaClient);
}
}
@@ -0,0 +1,12 @@
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { PrismaUserRepository as PrismaUserRepositoryLib } from "@calcom/platform-libraries/repositories";
import { PrismaClient } from "@calcom/prisma";
@Injectable()
export class PrismaUserRepository extends PrismaUserRepositoryLib {
constructor(private readonly dbWrite: PrismaWriteService) {
super(dbWrite.prisma as unknown as PrismaClient);
}
}
@@ -0,0 +1,36 @@
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
import { PrismaEventTypeRepository } from "@/lib/repositories/prisma-event-type.repository";
import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";
import { PrismaRoutingFormResponseRepository } from "@/lib/repositories/prisma-routing-form-response.repository";
import { PrismaScheduleRepository } from "@/lib/repositories/prisma-schedule.repository";
import { PrismaSelectedSlotsRepository } from "@/lib/repositories/prisma-selected-slots.repository";
import { PrismaTeamRepository } from "@/lib/repositories/prisma-team.repository";
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
import { Injectable } from "@nestjs/common";
import { AvailableSlotsService as BaseAvailableSlotsService } from "@calcom/platform-libraries/slots";
@Injectable()
export class AvailableSlotsService extends BaseAvailableSlotsService {
constructor(
private readonly oooRepoDependency: PrismaOOORepository,
private readonly scheduleRepoDependency: PrismaScheduleRepository,
private readonly teamRepository: PrismaTeamRepository,
private readonly routingFormResponseRepository: PrismaRoutingFormResponseRepository,
private readonly bookingRepository: PrismaBookingRepository,
private readonly selectedSlotsRepository: PrismaSelectedSlotsRepository,
private readonly eventTypeRepository: PrismaEventTypeRepository,
private readonly userRepository: PrismaUserRepository
) {
super({
oooRepo: oooRepoDependency,
scheduleRepo: scheduleRepoDependency,
teamRepo: teamRepository,
routingFormResponseRepo: routingFormResponseRepository,
bookingRepo: bookingRepository,
selectedSlotsRepo: selectedSlotsRepository,
eventTypeRepo: eventTypeRepository,
userRepo: userRepository,
});
}
}
@@ -1,3 +1,4 @@
import { extractUserContext } from "@/lib/extract-user-context";
import { CallHandler, ExecutionContext, Injectable, NestInterceptor, Logger } from "@nestjs/common";
import { Request, Response } from "express";
import { tap } from "rxjs/operators";
@@ -14,6 +15,7 @@ export class ResponseInterceptor implements NestInterceptor {
const requestId = request.headers["X-Request-Id"] ?? "unknown-request-id";
response.setHeader("X-Request-Id", requestId.toString());
const { method, url } = request;
const userContext = extractUserContext(request);
const startTime = Date.now();
return next.handle().pipe(
@@ -39,6 +41,7 @@ export class ResponseInterceptor implements NestInterceptor {
responseTime,
responseBody: jsonBodyString,
timestamp: new Date().toISOString(),
...userContext,
});
})
);
@@ -95,7 +95,9 @@ export class EventTypesAtomService {
}
// note (Lauris): don't show platform owner as one of the people that can be assigned to managed team event type
const onlyManagedTeamMembers = eventType.teamMembers.filter((user) => user.isPlatformManaged);
const onlyManagedTeamMembers = eventType.teamMembers.filter(
(user) => user.isPlatformManaged && user.membership === "MEMBER"
);
eventType.teamMembers = onlyManagedTeamMembers;
return eventType;
@@ -1,5 +1,10 @@
import { Reflector } from "@nestjs/core";
export type AllowedAuthMethod = "OAUTH_CLIENT_CREDENTIALS" | "API_KEY" | "ACCESS_TOKEN" | "NEXT_AUTH";
export type AllowedAuthMethod =
| "OAUTH_CLIENT_CREDENTIALS"
| "API_KEY"
| "ACCESS_TOKEN"
| "NEXT_AUTH"
| "THIRD_PARTY_ACCESS_TOKEN";
export const ApiAuthGuardOnlyAllow = Reflector.createDecorator<AllowedAuthMethod[]>();
@@ -10,16 +10,30 @@ import { ProfilesRepository } from "@/modules/profiles/profiles.repository";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { UsersService } from "@/modules/users/services/users.service";
import { UserWithProfile, UsersRepository } from "@/modules/users/users.repository";
import { Injectable, InternalServerErrorException, UnauthorizedException } from "@nestjs/common";
import {
HttpException,
Injectable,
InternalServerErrorException,
UnauthorizedException,
} from "@nestjs/common";
import { Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { PassportStrategy } from "@nestjs/passport";
import type { Request } from "express";
import * as jwt from "jsonwebtoken";
import { getToken } from "next-auth/jwt";
import { INVALID_ACCESS_TOKEN, X_CAL_CLIENT_ID, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
import type { AllowedAuthMethod } from "../../decorators/api-auth-guard-only-allow.decorator";
interface OAuthTokenPayload {
userId?: number;
teamId?: number;
scope: string[];
token_type: string;
}
export type ApiAuthGuardUser = UserWithProfile & { isSystemAdmin: boolean };
export type ApiAuthGuardRequest = Request & {
authMethod: AuthMethods;
@@ -29,8 +43,11 @@ export type ApiAuthGuardRequest = Request & {
};
export const NO_AUTH_PROVIDED_MESSAGE =
"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";
@Injectable()
export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth") {
private readonly logger = new Logger("ApiAuthStrategy");
constructor(
private readonly deploymentsService: DeploymentsService,
private readonly config: ConfigService,
@@ -54,22 +71,53 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
const allowedMethods = request.allowedAuthMethods;
const noSpecificAuthExpected = !allowedMethods || !allowedMethods.length;
const oAuthAllowed = noSpecificAuthExpected || allowedMethods.includes("OAUTH_CLIENT_CREDENTIALS");
const apiKeyAllowed = noSpecificAuthExpected || allowedMethods.includes("API_KEY");
const accessTokenAllowed = noSpecificAuthExpected || allowedMethods.includes("ACCESS_TOKEN");
const nextAuthAllowed = noSpecificAuthExpected || allowedMethods.includes("NEXT_AUTH");
const thirdPartyAccessTokenAllowed =
noSpecificAuthExpected || allowedMethods.includes("THIRD_PARTY_ACCESS_TOKEN");
if (oAuthClientId && oAuthClientSecret && oAuthAllowed) {
request.authMethod = AuthMethods["OAUTH_CLIENT"];
return await this.authenticateOAuthClient(oAuthClientId, oAuthClientSecret, request);
}
if (bearerToken && (apiKeyAllowed || accessTokenAllowed)) {
const requestOrigin = request.get("Origin");
request.authMethod = isApiKey(bearerToken, this.config.get<string>("api.apiKeyPrefix") ?? "cal_")
? AuthMethods["API_KEY"]
: AuthMethods["ACCESS_TOKEN"];
return await this.authenticateBearerToken(bearerToken, request, requestOrigin);
if (bearerToken) {
if (!apiKeyAllowed && !accessTokenAllowed && thirdPartyAccessTokenAllowed) {
request.authMethod = AuthMethods["THIRD_PARTY_ACCESS_TOKEN"];
const result = await this.validateThirdPartyAccessToken(bearerToken, request);
if (result.success) {
return this.success(this.getSuccessUser(result.data));
}
}
if (apiKeyAllowed || accessTokenAllowed) {
try {
const requestOrigin = request.get("Origin");
request.authMethod = isApiKey(bearerToken, this.config.get<string>("api.apiKeyPrefix") ?? "cal_")
? AuthMethods["API_KEY"]
: AuthMethods["ACCESS_TOKEN"];
return await this.authenticateBearerToken(bearerToken, request, requestOrigin);
} catch (err) {
// failed to validate access token, try to validate third party token
if (thirdPartyAccessTokenAllowed && request.authMethod === AuthMethods["ACCESS_TOKEN"]) {
request.authMethod = AuthMethods["THIRD_PARTY_ACCESS_TOKEN"];
const result = await this.validateThirdPartyAccessToken(bearerToken, request);
if (result.success) {
return this.success(this.getSuccessUser(result.data));
}
}
// token was not third party token, rethrow error from authenticateBearerToken
if (err instanceof Error) {
return this.error(err);
}
}
}
throw new UnauthorizedException(`ApiAuthStrategy - Invalid Bearer token`);
}
const nextAuthSecret = this.config.get("next.authSecret", { infer: true });
@@ -83,8 +131,11 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
if (noAuthProvided) {
throw new UnauthorizedException(`ApiAuthStrategy - ${NO_AUTH_PROVIDED_MESSAGE}`);
}
throw new UnauthorizedException(
`ApiAuthStrategy - Invalid authentication method. Please provide one of the allowed methods: ${allowedMethods}`
`ApiAuthStrategy - Invalid authentication method. Please provide one of the allowed methods: ${
allowedMethods && allowedMethods.length > 0 ? allowedMethods.join(", ") : "Any supported method"
}`
);
} catch (err) {
if (err instanceof Error) {
@@ -164,21 +215,17 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
: await this.accessTokenStrategy(authString, request, requestOrigin);
if (!user) {
return this.error(
new UnauthorizedException(
"ApiAuthStrategy - bearer token - No user associated with the provided token"
)
throw new UnauthorizedException(
"ApiAuthStrategy - bearer token - No user associated with the provided token"
);
}
return this.success(this.getSuccessUser(user));
} catch (err) {
if (err instanceof Error) {
return this.error(err);
throw err;
}
return this.error(
new InternalServerErrorException("An error occurred while authenticating the request")
);
throw new InternalServerErrorException("An error occurred while authenticating the request");
}
}
@@ -271,4 +318,55 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
return user;
}
async validateThirdPartyAccessToken(
token: string,
request: ApiAuthGuardRequest
): Promise<{ success: true; data: UserWithProfile } | { success: false }> {
// Removed requiredScopes parameter
const encryptionKey = this.config.get<string>("CALENDSO_ENCRYPTION_KEY");
if (!encryptionKey) {
throw new InternalServerErrorException("CALENDSO_ENCRYPTION_KEY environment variable is not set.");
}
let decodedToken: OAuthTokenPayload;
try {
decodedToken = jwt.verify(token, encryptionKey) as OAuthTokenPayload;
} catch (e) {
return { success: false };
}
if (!decodedToken || decodedToken.token_type !== "Access Token") {
return { success: false };
}
let user: UserWithProfile | null = null;
let organizationId: number | null = null;
if (decodedToken.userId) {
user = await this.userRepository.findByIdWithProfile(decodedToken.userId);
if (user) {
organizationId = this.usersService.getUserMainOrgId(user) as number;
}
} else if (decodedToken.teamId) {
const teamOwner = await this.userRepository.findOwnerByTeamIdWithProfile(decodedToken.teamId);
if (!teamOwner) {
throw new UnauthorizedException(
"ApiAuthStrategy - third-party token - No owner found for the associated team."
);
}
user = teamOwner;
organizationId =
teamOwner.profiles?.find((p) => p.organizationId === decodedToken.teamId)?.organizationId ?? null;
}
if (!user) {
throw new UnauthorizedException(
"ApiAuthStrategy - third-party token - No user or team owner associated with the token."
);
}
request.organizationId = organizationId;
return { success: true, data: user };
}
}
@@ -1,7 +1,6 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
@Injectable()
export class BookingSeatRepository {
@@ -34,7 +34,7 @@ export class CalUnifiedCalendarsController {
@UseGuards(ApiAuthGuard, PermissionsGuard)
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
@ApiOperation({
summary: "Get meeting Details from calendar",
summary: "Get meeting details from calendar",
description: "Returns detailed information about a meeting including attendance metrics",
})
async getCalendarEventDetails(
@@ -5,7 +5,7 @@ import { calendar_v3 } from "@googleapis/calendar";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { NotFoundException } from "@nestjs/common";
import { Logger } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import type { Prisma } from "@prisma/client";
import { JWT } from "googleapis-common";
import { DelegationCredentialRepository, OAuth2UniversalSchema } from "@calcom/platform-libraries/app-store";
@@ -87,7 +87,7 @@ export class ConferencingController {
@HttpCode(HttpStatus.OK)
@UseGuards(ApiAuthGuard)
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
@ApiOperation({ summary: "Get OAuth conferencing app auth url" })
@ApiOperation({ summary: "Get OAuth conferencing app auth URL" })
@ApiParam({
name: "app",
description: "Conferencing application type",
@@ -130,7 +130,7 @@ export class ConferencingController {
@Get("/:app/oauth/callback")
@UseGuards()
@Redirect(undefined, 301)
@ApiOperation({ summary: "conferencing apps oauths callback" })
@ApiOperation({ summary: "Conferencing app OAuth callback" })
@ApiParam({
name: "app",
description: "Conferencing application type",
@@ -1,7 +1,7 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import type { Prisma } from "@prisma/client";
import { GOOGLE_MEET_TYPE } from "@calcom/platform-constants";
@@ -9,7 +9,7 @@ import { GOOGLE_MEET_TYPE } from "@calcom/platform-constants";
export class ConferencingRepository {
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
private readonly credentialSelect = Prisma.validator<Prisma.CredentialSelect>()({
private readonly credentialSelect = {
id: true,
type: true,
userId: true,
@@ -20,7 +20,7 @@ export class ConferencingRepository {
billingCycleStart: true,
invalid: true,
delegationCredentialId: true,
});
} satisfies Prisma.CredentialSelect;
async findConferencingApps(userId: number) {
return this.dbRead.prisma.credential.findMany({
@@ -1,7 +1,7 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import type { Prisma } from "@prisma/client";
import { APPS_TYPE_ID_MAPPING } from "@calcom/platform-constants";
import { credentialForCalendarServiceSelect } from "@calcom/platform-libraries";
@@ -92,6 +92,8 @@ describe("Platform Destination Calendar Endpoints", () => {
publisher: "",
url: "",
email: "",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
// calendars: {
// externalId:
@@ -118,6 +120,8 @@ describe("Platform Destination Calendar Endpoints", () => {
id: 0,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date(),
updatedAt: new Date(),
},
})
);
@@ -2,7 +2,7 @@ import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { Injectable } from "@nestjs/common";
import { v4 as uuidv4 } from "uuid";
import { Prisma } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
import { PrismaWriteService } from "../../prisma/prisma-write.service";
@@ -134,7 +134,7 @@ export class OrganizationsAttributesOptionsController {
@Roles("ORG_MEMBER")
@PlatformPlan("ESSENTIALS")
@Get("/attributes/:attributeId/options/assigned")
@ApiOperation({ summary: "Get by attribute id all of the attribute options that are assigned to users" })
@ApiOperation({ summary: "Get all assigned attribute options by attribute ID" })
async getOrganizationAttributeAssignedOptions(
@Param("orgId", ParseIntPipe) orgId: number,
@Param("attributeId") attributeId: string,
@@ -158,7 +158,7 @@ export class OrganizationsAttributesOptionsController {
@Roles("ORG_MEMBER")
@PlatformPlan("ESSENTIALS")
@Get("/attributes/slugs/:attributeSlug/options/assigned")
@ApiOperation({ summary: "Get by attribute slug all of the attribute options that are assigned to users" })
@ApiOperation({ summary: "Get all assigned attribute options by attribute slug" })
async getOrganizationAttributeAssignedOptionsBySlug(
@Param("orgId", ParseIntPipe) orgId: number,
@Param("attributeSlug") attributeSlug: string,
@@ -34,7 +34,7 @@ export class OrganizationsBookingsController {
constructor(private readonly bookingsService: BookingsService_2024_08_13) {}
@Get("/")
@ApiOperation({ summary: "Get Organization Bookings" })
@ApiOperation({ summary: "Get organization bookings" })
@Roles("ORG_ADMIN")
@PlatformPlan("ESSENTIALS")
@HttpCode(HttpStatus.OK)
@@ -105,7 +105,7 @@ export class OrganizationsConferencingController {
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
@Get("/teams/:teamId/conferencing/:app/oauth/auth-url")
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: "Get OAuth conferencing app's auth url for a team" })
@ApiOperation({ summary: "Get OAuth conferencing app's auth URL for a team" })
async getTeamOAuthUrl(
@Req() req: Request,
@Headers("Authorization") authorization: string,
@@ -52,7 +52,7 @@ export class OrganizationsDelegationCredentialController {
@HttpCode(HttpStatus.CREATED)
@Roles("ORG_ADMIN")
@PlatformPlan("SCALE")
@ApiOperation({ summary: "Save delegation credentials for your organization." })
@ApiOperation({ summary: "Save delegation credentials for your organization" })
async createDelegationCredential(
@Param("orgId", ParseIntPipe) orgId: number,
@GetUser() delegatedServiceAccountUser: User,
@@ -72,7 +72,7 @@ export class OrganizationsDelegationCredentialController {
@Patch("/:credentialId")
@Roles("ORG_ADMIN")
@PlatformPlan("SCALE")
@ApiOperation({ summary: "Update delegation credentials of your organization." })
@ApiOperation({ summary: "Update delegation credentials of your organization" })
async updateDelegationCredential(
@Param("orgId", ParseIntPipe) orgId: number,
@GetUser() delegatedServiceAccountUser: User,
@@ -2,7 +2,7 @@ import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { Prisma } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
@Injectable()
export class OrganizationsDelegationCredentialRepository {
@@ -304,8 +304,10 @@ describe("Assign all team members", () => {
expect(data.title).toEqual(body.title);
expect(data.hosts.length).toEqual(2);
expect(data.schedulingType).toEqual("collective");
evaluateHost({ userId: firstManagedUser.user.id }, data.hosts[0]);
evaluateHost({ userId: secondManagedUser.user.id }, data.hosts[1]);
const dataFirstHost = data.hosts.find((host) => host.userId === firstManagedUser.user.id);
const dataSecondHost = data.hosts.find((host) => host.userId === secondManagedUser.user.id);
evaluateHost({ userId: firstManagedUser.user.id }, dataFirstHost);
evaluateHost({ userId: secondManagedUser.user.id }, dataSecondHost);
const eventTypeHosts = await hostsRepositoryFixture.getEventTypeHosts(data.id);
expect(eventTypeHosts.length).toEqual(2);
@@ -341,13 +343,15 @@ describe("Assign all team members", () => {
expect(data.title).toEqual(body.title);
expect(data.hosts.length).toEqual(2);
expect(data.schedulingType).toEqual("roundRobin");
const dataFirstHost = data.hosts.find((host) => host.userId === firstManagedUser.user.id);
const dataSecondHost = data.hosts.find((host) => host.userId === secondManagedUser.user.id);
evaluateHost(
{ userId: firstManagedUser.user.id, mandatory: false, priority: "medium" },
data.hosts[0]
dataFirstHost
);
evaluateHost(
{ userId: secondManagedUser.user.id, mandatory: false, priority: "medium" },
data.hosts[1]
dataSecondHost
);
const eventTypeHosts = await hostsRepositoryFixture.getEventTypeHosts(data.id);
@@ -381,13 +385,15 @@ describe("Assign all team members", () => {
expect(data.title).toEqual(body.title);
expect(data.hosts.length).toEqual(2);
expect(data.schedulingType).toEqual("roundRobin");
const dataFirstHost = data.hosts.find((host) => host.userId === firstManagedUser.user.id);
const dataSecondHost = data.hosts.find((host) => host.userId === secondManagedUser.user.id);
evaluateHost(
{ userId: firstManagedUser.user.id, mandatory: false, priority: "medium" },
data.hosts[0]
dataFirstHost
);
evaluateHost(
{ userId: secondManagedUser.user.id, mandatory: false, priority: "medium" },
data.hosts[1]
dataSecondHost
);
const eventTypeHosts = await hostsRepositoryFixture.getEventTypeHosts(data.id);
@@ -69,7 +69,7 @@ export class OrganizationsRepository {
return id;
}
async findTeamIdFromClientId(clientId: string) {
async findTeamIdAndSlugFromClientId(clientId: string) {
return this.dbRead.prisma.team.findFirstOrThrow({
where: {
platformOAuthClient: {
@@ -80,6 +80,7 @@ export class OrganizationsRepository {
},
select: {
id: true,
slug: true,
},
});
}
@@ -4,7 +4,7 @@ import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { MembershipUserSelect } from "@/modules/teams/memberships/teams-memberships.repository";
import { Injectable } from "@nestjs/common";
import { Prisma } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
import { UpdateOrgMembershipDto } from "./inputs/update-organization-membership.input";
@@ -0,0 +1,29 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsOptional, IsString } from "class-validator";
import { SkipTakePagination } from "@calcom/platform-types";
export class GetManagedOrganizationsInput_2024_08_13 extends SkipTakePagination {
@IsOptional()
@IsString()
@ApiProperty({ example: "organization-slug", description: "The slug of the managed organization" })
slug?: string;
@IsOptional()
@IsString()
@ApiProperty({
example: "metadata-key",
description:
"The key of the metadata - it is case sensitive so provide exactly as stored. If you provide it then you must also provide metadataValue",
})
metadataKey?: string;
@IsOptional()
@IsString()
@ApiProperty({
example: "metadata-value",
description:
"The value of the metadata - it is case sensitive so provide exactly as stored. If you provide it then you must also provide metadataKey",
})
metadataValue?: string;
}
@@ -1,9 +1,10 @@
import { GetManagedOrganizationsInput_2024_08_13 } from "@/modules/organizations/organizations/inputs/get-managed-organizations.input";
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { SkipTakePagination } from "@calcom/platform-types";
import { Prisma } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
@Injectable()
export class ManagedOrganizationsRepository {
@@ -24,6 +25,17 @@ export class ManagedOrganizationsRepository {
});
}
async getManagedOrganizationBySlug(managerOrganizationId: number, managedOrganizationSlug: string) {
return this.dbRead.prisma.managedOrganization.findFirst({
where: {
managerOrganizationId,
managedOrganization: {
slug: managedOrganizationSlug,
},
},
});
}
async getByManagerManagedIds(managerOrganizationId: number, managedOrganizationId: number) {
return this.dbRead.prisma.managedOrganization.findUnique({
where: {
@@ -35,11 +47,26 @@ export class ManagedOrganizationsRepository {
});
}
async getByManagerOrganizationIdPaginated(managerOrganizationId: number, pagination: SkipTakePagination) {
const { skip, take } = pagination;
async getByManagerOrganizationIdPaginated(
managerOrganizationId: number,
query: GetManagedOrganizationsInput_2024_08_13
) {
const { skip, take, slug, metadataKey, metadataValue } = query;
const managedOrganizationFilter: Prisma.TeamWhereInput = {
slug,
};
if (metadataKey && metadataValue) {
managedOrganizationFilter.metadata = {
path: [metadataKey],
equals: metadataValue,
};
}
const where: Prisma.ManagedOrganizationWhereInput = {
managerOrganizationId,
managedOrganization: managedOrganizationFilter,
};
const [totalItems, linkRows] = await this.dbRead.prisma.$transaction([
@@ -66,6 +66,7 @@ describe("Organizations Organizations Endpoints", () => {
let managerOrg: Team;
let managedOrg: ManagedOrganizationWithApiKeyOutput;
let managedOrg2: ManagedOrganizationWithApiKeyOutput;
const managerOrgAdminEmail = `organizations-organizations-admin-${randomString()}@api.com`;
let managerOrgAdmin: User;
let managerOrgAdminApiKey: string;
@@ -159,27 +160,36 @@ describe("Organizations Organizations Endpoints", () => {
.expect(400);
});
const suffix = randomString(5);
const metadataKey = "first-org-metadata-key";
const metadataValue = "first-org-metadata-value";
const createManagedOrganizationBody: CreateOrganizationInput = {
name: `org ${suffix}`,
slug: `org-${suffix}`,
metadata: { [metadataKey]: metadataValue },
};
const suffix2 = randomString(5);
const createManagedOrganizationBodySecond: CreateOrganizationInput = {
name: `org2 ${suffix2}`,
slug: `org2-${suffix2}`,
metadata: { key: "value" },
};
it("should create managed organization", async () => {
const suffix = randomString();
const body: CreateOrganizationInput = {
name: `organizations organizations org ${suffix}`,
metadata: { key: "value" },
};
return request(app.getHttpServer())
.post(`/v2/organizations/${managerOrg.id}/organizations`)
.set("Authorization", `Bearer ${managerOrgAdminApiKey}`)
.send(body)
.send(createManagedOrganizationBody)
.expect(201)
.then(async (response) => {
const responseBody: ApiSuccessResponse<ManagedOrganizationWithApiKeyOutput> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
managedOrg = responseBody.data;
expect(managedOrg?.id).toBeDefined();
expect(managedOrg?.name).toEqual(body.name);
expect(managedOrg?.slug).toEqual(slugify(body.name));
expect(managedOrg?.metadata).toEqual(body.metadata);
expect(managedOrg?.name).toEqual(createManagedOrganizationBody.name);
expect(managedOrg?.slug).toEqual(createManagedOrganizationBody.slug);
expect(managedOrg?.metadata).toEqual(createManagedOrganizationBody.metadata);
expect(managedOrg?.apiKey).toBeDefined();
// note(Lauris): check that managed organization is correctly setup in database
@@ -284,6 +294,36 @@ describe("Organizations Organizations Endpoints", () => {
});
});
it("should not create managed organization if slug already exists", async () => {
const response = await request(app.getHttpServer())
.post(`/v2/organizations/${managerOrg.id}/organizations`)
.set("Authorization", `Bearer ${managerOrgAdminApiKey}`)
.send(createManagedOrganizationBody)
.expect(409);
expect(response.body.error.message).toBe(
`Organization with slug '${createManagedOrganizationBody.slug}' already exists. Please, either provide a different slug or change name so that the automatically generated slug is different.`
);
});
it("should create second managed organization", async () => {
return request(app.getHttpServer())
.post(`/v2/organizations/${managerOrg.id}/organizations`)
.set("Authorization", `Bearer ${managerOrgAdminApiKey}`)
.send(createManagedOrganizationBodySecond)
.expect(201)
.then(async (response) => {
const responseBody: ApiSuccessResponse<ManagedOrganizationWithApiKeyOutput> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
managedOrg2 = responseBody.data;
expect(managedOrg2?.id).toBeDefined();
expect(managedOrg2?.name).toEqual(createManagedOrganizationBodySecond.name);
expect(managedOrg2?.slug).toEqual(createManagedOrganizationBodySecond.slug);
expect(managedOrg2?.metadata).toEqual(createManagedOrganizationBodySecond.metadata);
expect(managedOrg2?.apiKey).toBeDefined();
});
});
it("should get managed organization", async () => {
return request(app.getHttpServer())
.get(`/v2/organizations/${managerOrg.id}/organizations/${managedOrg.id}`)
@@ -304,12 +344,69 @@ describe("Organizations Organizations Endpoints", () => {
.get(`/v2/organizations/${managerOrg.id}/organizations`)
.set("Authorization", `Bearer ${managerOrgAdminApiKey}`)
.expect(200)
.then(async (response) => {
const responseBody: GetManagedOrganizationsOutput = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const responseManagedOrgs = responseBody.data;
expect(responseManagedOrgs?.length).toEqual(2);
const responseManagedOrg = responseManagedOrgs.find((org) => org.id === managedOrg.id);
expect(responseManagedOrg?.id).toBeDefined();
expect(responseManagedOrg?.name).toEqual(managedOrg.name);
expect(responseManagedOrg?.metadata).toEqual(managedOrg.metadata);
const responseManagedOrg2 = responseManagedOrgs.find((org) => org.id === managedOrg2.id);
expect(responseManagedOrg2?.id).toBeDefined();
expect(responseManagedOrg2?.name).toEqual(managedOrg2.name);
expect(responseManagedOrg2?.metadata).toEqual(managedOrg2.metadata);
expect(responseBody.pagination).toBeDefined();
expect(responseBody.pagination.totalItems).toEqual(2);
expect(responseBody.pagination.remainingItems).toEqual(0);
expect(responseBody.pagination.returnedItems).toEqual(2);
expect(responseBody.pagination.itemsPerPage).toEqual(250);
expect(responseBody.pagination.currentPage).toEqual(1);
expect(responseBody.pagination.totalPages).toEqual(1);
});
});
it("should get managed organization by slug", async () => {
return request(app.getHttpServer())
.get(`/v2/organizations/${managerOrg.id}/organizations?slug=${managedOrg.slug}`)
.set("Authorization", `Bearer ${managerOrgAdminApiKey}`)
.expect(200)
.then(async (response) => {
const responseBody: GetManagedOrganizationsOutput = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const responseManagedOrgs = responseBody.data;
expect(responseManagedOrgs?.length).toEqual(1);
const responseManagedOrg = responseManagedOrgs[0];
const responseManagedOrg = responseManagedOrgs.find((org) => org.id === managedOrg.id);
expect(responseManagedOrg?.id).toBeDefined();
expect(responseManagedOrg?.name).toEqual(managedOrg.name);
expect(responseManagedOrg?.metadata).toEqual(managedOrg.metadata);
expect(responseBody.pagination).toBeDefined();
expect(responseBody.pagination.totalItems).toEqual(1);
expect(responseBody.pagination.remainingItems).toEqual(0);
expect(responseBody.pagination.returnedItems).toEqual(1);
expect(responseBody.pagination.itemsPerPage).toEqual(250);
expect(responseBody.pagination.currentPage).toEqual(1);
expect(responseBody.pagination.totalPages).toEqual(1);
});
});
it("should get managed organization by metadata key", async () => {
return request(app.getHttpServer())
.get(
`/v2/organizations/${managerOrg.id}/organizations?metadataKey=${metadataKey}&metadataValue=${metadataValue}`
)
.set("Authorization", `Bearer ${managerOrgAdminApiKey}`)
.expect(200)
.then(async (response) => {
const responseBody: GetManagedOrganizationsOutput = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const responseManagedOrgs = responseBody.data;
expect(responseManagedOrgs?.length).toEqual(1);
const responseManagedOrg = responseManagedOrgs.find((org) => org.id === managedOrg.id);
expect(responseManagedOrg?.id).toBeDefined();
expect(responseManagedOrg?.name).toEqual(managedOrg.name);
expect(responseManagedOrg?.metadata).toEqual(managedOrg.metadata);
@@ -465,7 +562,40 @@ describe("Organizations Organizations Endpoints", () => {
});
});
it("should delete managed organization ", async () => {
it("should delete managed organization", async () => {
return request(app.getHttpServer())
.delete(`/v2/organizations/${managerOrg.id}/organizations/${managedOrg2.id}`)
.set("Authorization", `Bearer ${managerOrgAdminApiKey}`)
.expect(200)
.then(async (response) => {
const responseBody: ApiSuccessResponse<ManagedOrganizationWithApiKeyOutput> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const responseManagedOrg = responseBody.data;
expect(responseManagedOrg?.id).toBeDefined();
expect(responseManagedOrg?.id).toEqual(managedOrg2.id);
expect(responseManagedOrg?.name).toEqual(managedOrg2.name);
const managedOrgInDb =
await managedOrganizationsRepositoryFixture.getOrganizationWithManagedOrganizations(managedOrg2.id);
expect(managedOrgInDb).toEqual(null);
const billings = await platformBillingRepositoryFixture.getByCustomerSubscriptionIds(
managerOrgBilling.customerId,
managerOrgBilling.subscriptionId!
);
expect(billings).toBeDefined();
// note(Lauris): manager billing is left and other managed org
expect(billings?.length).toEqual(2);
const managerOrgInDb =
await managedOrganizationsRepositoryFixture.getOrganizationWithManagedOrganizations(managerOrg.id);
expect(managerOrgInDb).toBeDefined();
expect(managerOrgInDb?.id).toEqual(managerOrg.id);
expect(managerOrgInDb?.managedOrganizations?.length).toEqual(1);
});
});
it("should delete managed organization", async () => {
return request(app.getHttpServer())
.delete(`/v2/organizations/${managerOrg.id}/organizations/${managedOrg.id}`)
.set("Authorization", `Bearer ${managerOrgAdminApiKey}`)
@@ -11,6 +11,7 @@ import { IsOrgGuard } from "@/modules/auth/guards/organizations/is-org.guard";
import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard";
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { CreateOrganizationInput } from "@/modules/organizations/organizations/inputs/create-managed-organization.input";
import { GetManagedOrganizationsInput_2024_08_13 } from "@/modules/organizations/organizations/inputs/get-managed-organizations.input";
import { UpdateOrganizationInput } from "@/modules/organizations/organizations/inputs/update-managed-organization.input";
import { CreateManagedOrganizationOutput } from "@/modules/organizations/organizations/outputs/create-managed-organization.output";
import { GetManagedOrganizationOutput } from "@/modules/organizations/organizations/outputs/get-managed-organization.output";
@@ -102,10 +103,10 @@ export class OrganizationsOrganizationsController {
})
async getOrganizations(
@Param("orgId", ParseIntPipe) managerOrganizationId: number,
@Query() queryPagination: SkipTakePagination
@Query() query: GetManagedOrganizationsInput_2024_08_13
): Promise<GetManagedOrganizationsOutput> {
const { organizations, pagination: responsePagination } =
await this.managedOrganizationsService.getManagedOrganizations(managerOrganizationId, queryPagination);
await this.managedOrganizationsService.getManagedOrganizations(managerOrganizationId, query);
return {
status: SUCCESS_STATUS,
data: organizations,
@@ -5,11 +5,12 @@ import { ManagedOrganizationsBillingService } from "@/modules/billing/services/m
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { OrganizationsMembershipService } from "@/modules/organizations/memberships/services/organizations-membership.service";
import { CreateOrganizationInput } from "@/modules/organizations/organizations/inputs/create-managed-organization.input";
import { GetManagedOrganizationsInput_2024_08_13 } from "@/modules/organizations/organizations/inputs/get-managed-organizations.input";
import { UpdateOrganizationInput } from "@/modules/organizations/organizations/inputs/update-managed-organization.input";
import { ManagedOrganizationsRepository } from "@/modules/organizations/organizations/managed-organizations.repository";
import { ManagedOrganizationsOutputService } from "@/modules/organizations/organizations/services/managed-organizations-output.service";
import { ProfilesRepository } from "@/modules/profiles/profiles.repository";
import { ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
import { ConflictException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
import { slugify } from "@calcom/platform-libraries";
import { SkipTakePagination } from "@calcom/platform-types";
@@ -44,6 +45,18 @@ export class ManagedOrganizationsService {
organizationData.slug = slugify(organizationData.name);
}
const existingManagedOrganization =
await this.managedOrganizationsRepository.getManagedOrganizationBySlug(
managerOrganizationId,
organizationData.slug
);
if (existingManagedOrganization) {
throw new ConflictException(
`Organization with slug '${organizationData.slug}' already exists. Please, either provide a different slug or change name so that the automatically generated slug is different.`
);
}
const organization = await this.managedOrganizationsRepository.createManagedOrganization(
managerOrganizationId,
{
@@ -101,11 +114,14 @@ export class ManagedOrganizationsService {
return this.managedOrganizationsOutputService.getOutputManagedOrganization(organization);
}
async getManagedOrganizations(managerOrganizationId: number, pagination: SkipTakePagination) {
async getManagedOrganizations(
managerOrganizationId: number,
query: GetManagedOrganizationsInput_2024_08_13
) {
const { items: managedOrganizations, totalItems } =
await this.managedOrganizationsRepository.getByManagerOrganizationIdPaginated(
managerOrganizationId,
pagination
query
);
return {
@@ -113,7 +129,7 @@ export class ManagedOrganizationsService {
this.managedOrganizationsOutputService.getOutputManagedOrganization(managedOrganization)
),
pagination: getPagination({
...pagination,
...query,
totalCount: totalItems,
}),
};
@@ -37,7 +37,13 @@ describe("OrganizationsRoutingFormsResponsesController", () => {
let user: User;
const userEmail = `OrganizationsRoutingFormsResponsesController-key-bookings-2024-08-13-user-${randomString()}@api.com`;
let profileRepositoryFixture: ProfileRepositoryFixture;
let routingEventType: {
id: number;
slug: string | null;
teamId: number | null;
userId: number | null;
title: string;
};
let membershipsRepositoryFixture: MembershipRepositoryFixture;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
@@ -72,6 +78,7 @@ describe("OrganizationsRoutingFormsResponsesController", () => {
role: "OWNER",
user: { connect: { id: user.id } },
team: { connect: { id: org.id } },
accepted: true,
});
await profileRepositoryFixture.create({
@@ -93,14 +100,74 @@ describe("OrganizationsRoutingFormsResponsesController", () => {
const { keyString } = await apiKeysRepositoryFixture.createApiKey(user.id, null);
apiKeyString = `${keyString}`;
// Create an event type for routing form to route to
routingEventType = await prismaWriteService.prisma.eventType.create({
data: {
title: "Test Event Type",
slug: "test-event-type",
length: 30,
userId: user.id,
teamId: team.id,
},
});
routingForm = await prismaWriteService.prisma.app_RoutingForms_Form.create({
data: {
name: "Test Routing Form",
description: "Test Description",
disabled: false,
routes: JSON.stringify([]),
fields: JSON.stringify([]),
settings: JSON.stringify({}),
routes: [
{
id: "route-1",
queryValue: {
id: "route-1",
type: "group",
children1: {
"rule-1": {
type: "rule",
properties: {
field: "question1",
operator: "equal",
value: ["answer1"],
valueSrc: ["value"],
valueType: ["text"],
},
},
},
},
action: {
type: "eventTypeRedirectUrl",
eventTypeId: routingEventType.id,
value: `team/${team.slug}/${routingEventType.slug}`,
},
isFallback: false,
},
{
id: "fallback-route",
action: { type: "customPageMessage", value: "Fallback Message" },
isFallback: true,
queryValue: { id: "fallback-route", type: "group" },
},
],
fields: [
{
id: "question1",
type: "text",
label: "Question 1",
required: true,
identifier: "question1",
},
{
id: "question2",
type: "text",
label: "Question 2",
required: false,
identifier: "question2",
},
],
settings: {
emailOwnerOnSubmission: false,
},
teamId: team.id,
userId: user.id,
},
@@ -175,6 +242,381 @@ describe("OrganizationsRoutingFormsResponsesController", () => {
});
});
describe(`POST /v2/organizations/:orgId/routing-forms/:routingFormId/responses`, () => {
it("should return 403 when organization does not exist", async () => {
return request(app.getHttpServer())
.post(
`/v2/organizations/99999/routing-forms/${routingForm.id}/responses?start=2050-09-05&end=2050-09-06`
)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question1: "answer1",
})
.expect(403);
});
it("should return 404 when routing form does not exist", async () => {
return request(app.getHttpServer())
.post(
`/v2/organizations/${org.id}/routing-forms/non-existent-id/responses?start=2050-09-05&end=2050-09-06`
)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question1: "answer1",
})
.expect(404);
});
it("should return 401 when authentication token is missing", async () => {
return request(app.getHttpServer())
.post(
`/v2/organizations/${org.id}/routing-forms/${routingForm.id}/responses?start=2050-09-05&end=2050-09-06`
)
.send({
question1: "answer1",
})
.expect(401);
});
it("should create response and return available slots when routing to event type", async () => {
return request(app.getHttpServer())
.post(
`/v2/organizations/${org.id}/routing-forms/${routingForm.id}/responses?start=2050-09-05&end=2050-09-06`
)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question1: "answer1", // This matches the route condition
question2: "answer2",
})
.expect(201)
.then((response) => {
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data;
expect(data).toBeDefined();
expect(data.routing?.responseId).toBeDefined();
expect(typeof data.routing?.responseId).toBe("number");
expect(data.eventTypeId).toEqual(routingEventType.id);
expect(data.slots).toBeDefined();
expect(typeof data.slots).toBe("object");
});
});
it("should return 400 when required form fields are missing", async () => {
return request(app.getHttpServer())
.post(
`/v2/organizations/${org.id}/routing-forms/${routingForm.id}/responses?start=2050-09-05&end=2050-09-06`
)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question2: "answer2", // Missing required question1
})
.expect(400);
});
it("should create response and return custom message if the routing is to custom page", async () => {
return request(app.getHttpServer())
.post(
`/v2/organizations/${org.id}/routing-forms/${routingForm.id}/responses?start=2050-09-05&end=2050-09-06`
)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question1: "different-answer", // This won't match any route
question2: "answer2",
})
.expect(201)
.then((response) => {
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data;
expect(data).toBeDefined();
expect(data.routingCustomMessage).toBeDefined();
expect(data.routingCustomMessage).toBe("Fallback Message");
});
});
it("should return 400 when required slot query parameters are missing", async () => {
// Missing start parameter
await request(app.getHttpServer())
.post(`/v2/organizations/${org.id}/routing-forms/${routingForm.id}/responses?end=2050-09-06`)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question1: "answer1",
question2: "answer2",
})
.expect(400);
// Missing end parameter
await request(app.getHttpServer())
.post(`/v2/organizations/${org.id}/routing-forms/${routingForm.id}/responses?start=2050-09-05`)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question1: "answer1",
question2: "answer2",
})
.expect(400);
});
it("should return 400 when date parameters have invalid format", async () => {
return request(app.getHttpServer())
.post(
`/v2/organizations/${org.id}/routing-forms/${routingForm.id}/responses?start=invalid-date&end=2050-09-06`
)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question1: "answer1",
})
.expect(400);
});
it("should return 400 when end date is before start date", async () => {
return request(app.getHttpServer())
.post(
`/v2/organizations/${org.id}/routing-forms/${routingForm.id}/responses?start=2050-09-10&end=2050-09-05`
)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question1: "answer1",
})
.expect(400);
});
it("should return 403 when user lacks permission to access organization", async () => {
// Create a new user without organization access
const unauthorizedUser = await userRepositoryFixture.create({
email: `unauthorized-user-${randomString()}@api.com`,
});
const { keyString: unauthorizedApiKey } = await apiKeysRepositoryFixture.createApiKey(
unauthorizedUser.id,
null
);
const response = await request(app.getHttpServer())
.post(
`/v2/organizations/${org.id}/routing-forms/${routingForm.id}/responses?start=2050-09-05&end=2050-09-06`
)
.set({ Authorization: `Bearer cal_test_${unauthorizedApiKey}` })
.send({
question1: "answer1",
});
expect(response.status).toBe(403);
// Clean up
await prismaWriteService.prisma.user.delete({
where: { id: unauthorizedUser.id },
});
});
it("should handle queued response creation", async () => {
return request(app.getHttpServer())
.post(
`/v2/organizations/${org.id}/routing-forms/${routingForm.id}/responses?start=2050-09-05&end=2050-09-06&queueResponse=true`
)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question1: "answer1",
question2: "answer2",
})
.expect(201)
.then((response) => {
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data;
expect(data.routing?.queuedResponseId).toBeDefined();
});
});
it("should return 500 when event type is not found", async () => {
// Create a routing form with an invalid eventTypeId
const routingFormWithInvalidEventType = await prismaWriteService.prisma.app_RoutingForms_Form.create({
data: {
name: "Test Routing Form with Invalid Event Type",
description: "Test Description",
disabled: false,
routes: [
{
id: "route-1",
queryValue: {
id: "route-1",
type: "group",
children1: {
"rule-1": {
type: "rule",
properties: {
field: "question1",
operator: "equal",
value: ["answer1"],
valueSrc: ["value"],
valueType: ["text"],
},
},
},
},
action: {
type: "eventTypeRedirectUrl",
eventTypeId: 99999, // Invalid event type ID
value: `team/${team.slug}/non-existent-event-type`,
},
isFallback: false,
},
{
id: "fallback-route",
action: { type: "customPageMessage", value: "Fallback Message" },
isFallback: true,
queryValue: { id: "fallback-route", type: "group" },
},
],
fields: [
{
id: "question1",
type: "text",
label: "Question 1",
required: true,
identifier: "question1",
},
],
settings: {
emailOwnerOnSubmission: false,
},
teamId: team.id,
userId: user.id,
},
});
// Try to create a response for the form with invalid event type
const response = await request(app.getHttpServer())
.post(
`/v2/organizations/${org.id}/routing-forms/${routingFormWithInvalidEventType.id}/responses?start=2050-09-05&end=2050-09-06`
)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question1: "answer1",
});
expect(response.status).toBe(500);
// Clean up the form
await prismaWriteService.prisma.app_RoutingForms_Form.delete({
where: { id: routingFormWithInvalidEventType.id },
});
});
it("should handle routing with team member assignments", async () => {
// This test verifies that routing forms can handle team member assignments
// and that the routing returns the correct team member information
return request(app.getHttpServer())
.post(
`/v2/organizations/${org.id}/routing-forms/${routingForm.id}/responses?start=2050-09-05&end=2050-09-06`
)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question1: "answer1", // This matches the route condition
question2: "answer2",
})
.expect(201)
.then((response) => {
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data;
expect(data).toBeDefined();
expect(data.routing?.responseId).toBeDefined();
expect(typeof data.routing?.responseId).toBe("number");
expect(data.eventTypeId).toEqual(routingEventType.id);
expect(data.slots).toBeDefined();
// Team member assignments would be part of the routing data
// This test validates the basic routing functionality works
});
});
it("should return external redirect URL when routing to external URL", async () => {
// Create a routing form with external redirect action
const externalRoutingForm = await prismaWriteService.prisma.app_RoutingForms_Form.create({
data: {
name: "Test External Routing Form",
description: "Test Description for External Redirect",
disabled: false,
routes: [
{
id: "external-route-1",
queryValue: {
id: "external-route-1",
type: "group",
children1: {
"rule-1": {
type: "rule",
properties: {
field: "question1",
operator: "equal",
value: ["external"],
valueSrc: ["value"],
valueType: ["text"],
},
},
},
},
action: {
type: "externalRedirectUrl",
value: "https://example.com/external-booking",
},
isFallback: false,
},
{
id: "fallback-route",
action: { type: "customPageMessage", value: "Fallback Message" },
isFallback: true,
queryValue: { id: "fallback-route", type: "group" },
},
],
fields: [
{
id: "question1",
type: "text",
label: "Question 1",
required: true,
identifier: "question1",
},
],
settings: {
emailOwnerOnSubmission: false,
},
teamId: team.id,
userId: user.id,
},
});
const response = await request(app.getHttpServer())
.post(
`/v2/organizations/${org.id}/routing-forms/${externalRoutingForm.id}/responses?start=2050-09-05&end=2050-09-06`
)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.send({
question1: "external", // This matches the route condition for external redirect
})
.expect(201);
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data;
expect(data).toBeDefined();
expect(data.routingExternalRedirectUrl).toBeDefined();
expect(data.routingExternalRedirectUrl).toContain("https://example.com/external-booking");
expect(data.routingExternalRedirectUrl).toContain("cal.action=externalRedirectUrl");
// Verify that it doesn't contain event type routing data
expect(data.eventTypeId).toBeUndefined();
expect(data.slots).toBeUndefined();
expect(data.routing).toBeUndefined();
expect(data.routingCustomMessage).toBeUndefined();
// Clean up the external routing form
await prismaWriteService.prisma.app_RoutingForms_Form.delete({
where: { id: externalRoutingForm.id },
});
});
});
describe(`PATCH /v2/organizations/:orgId/routing-forms/:routingFormId/responses/:responseId`, () => {
it("should not update routing form response for non existing org", async () => {
return request(app.getHttpServer())
@@ -9,13 +9,28 @@ import { IsOrgGuard } from "@/modules/auth/guards/organizations/is-org.guard";
import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard";
import { GetRoutingFormResponsesOutput } from "@/modules/organizations/routing-forms/outputs/get-routing-form-responses.output";
import { OrganizationsRoutingFormsResponsesService } from "@/modules/organizations/routing-forms/services/organizations-routing-forms-responses.service";
import { Body, Controller, Get, Param, Patch, Query, UseGuards, ParseIntPipe } from "@nestjs/common";
import {
Body,
Controller,
Get,
Param,
Patch,
Post,
Query,
UseGuards,
ParseIntPipe,
Req,
} from "@nestjs/common";
import { ApiHeader, ApiOperation, ApiTags } from "@nestjs/swagger";
import { Request } from "express";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { GetAvailableSlotsInput_2024_09_04 } from "@calcom/platform-types";
import { CreateRoutingFormResponseInput } from "../inputs/create-routing-form-response.input";
import { GetRoutingFormResponsesParams } from "../inputs/get-routing-form-responses-params.input";
import { UpdateRoutingFormResponseInput } from "../inputs/update-routing-form-response.input";
import { CreateRoutingFormResponseOutput } from "../outputs/create-routing-form-response.output";
import { UpdateRoutingFormResponseOutput } from "../outputs/update-routing-form-response.output";
@Controller({
@@ -56,6 +71,29 @@ export class OrganizationsRoutingFormsResponsesController {
};
}
@Post("/")
@ApiOperation({ summary: "Create routing form response and get available slots" })
@Roles("ORG_ADMIN")
@PlatformPlan("ESSENTIALS")
async createRoutingFormResponse(
@Param("orgId", ParseIntPipe) orgId: number,
@Param("routingFormId") routingFormId: string,
@Query() query: CreateRoutingFormResponseInput,
@Req() request: Request
): Promise<CreateRoutingFormResponseOutput> {
const result = await this.organizationsRoutingFormsResponsesService.createRoutingFormResponseWithSlots(
orgId,
routingFormId,
query,
request
);
return {
status: SUCCESS_STATUS,
data: result,
};
}
@Patch("/:responseId")
@ApiOperation({ summary: "Update routing form response" })
@Roles("ORG_ADMIN")
@@ -0,0 +1,23 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { Transform } from "class-transformer";
import { IsBoolean, IsOptional } from "class-validator";
import { GetAvailableSlotsInput_2024_09_04 } from "@calcom/platform-types";
export class CreateRoutingFormResponseInput extends GetAvailableSlotsInput_2024_09_04 {
@Transform(({ value }: { value: string | boolean }) => {
if (typeof value === "boolean") return value;
if (typeof value === "string") {
return value.toLowerCase() === "true";
}
return undefined;
})
@IsBoolean()
@IsOptional()
@ApiPropertyOptional({
type: Boolean,
description: "Whether to queue the form response.",
example: true,
})
queueResponse?: boolean;
}
@@ -4,7 +4,9 @@ import { OrganizationsTeamsRoutingFormsResponsesOutputService } from "@/modules/
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { RedisModule } from "@/modules/redis/redis.module";
import { RoutingFormsModule } from "@/modules/routing-forms/routing-forms.module";
import { SlotsModule_2024_09_04 } from "@/modules/slots/slots-2024-09-04/slots.module";
import { StripeModule } from "@/modules/stripe/stripe.module";
import { TeamsEventTypesRepository } from "@/modules/teams/event-types/teams-event-types.repository";
import { Module } from "@nestjs/common";
import { OrganizationsRoutingFormsResponsesController } from "./controllers/organizations-routing-forms-responses.controller";
@@ -14,7 +16,7 @@ import { OrganizationsRoutingFormsResponsesService } from "./services/organizati
import { OrganizationsRoutingFormsService } from "./services/organizations-routing-forms.service";
@Module({
imports: [PrismaModule, StripeModule, RedisModule, RoutingFormsModule],
imports: [PrismaModule, StripeModule, RedisModule, RoutingFormsModule, SlotsModule_2024_09_04],
providers: [
MembershipsRepository,
OrganizationsRepository,
@@ -22,6 +24,7 @@ import { OrganizationsRoutingFormsService } from "./services/organizations-routi
OrganizationsRoutingFormsService,
OrganizationsRoutingFormsResponsesService,
OrganizationsTeamsRoutingFormsResponsesOutputService,
TeamsEventTypesRepository,
],
controllers: [OrganizationsRoutingFormsController, OrganizationsRoutingFormsResponsesController],
})
@@ -0,0 +1,141 @@
import { ApiProperty, ApiPropertyOptional, getSchemaPath } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsArray, IsBoolean, IsInt, IsNumber, IsOptional, IsString, ValidateNested } from "class-validator";
import {
ApiResponseWithoutData,
SlotsOutput_2024_09_04,
RangeSlotsOutput_2024_09_04,
} from "@calcom/platform-types";
class Routing {
@ApiProperty({
type: String,
description: "The ID of the queued form response. Only present if the form response was queued.",
example: "123",
})
@IsString()
@IsOptional()
@ApiPropertyOptional()
queuedResponseId?: string | null;
@ApiProperty({
type: Number,
description: "The ID of the routing form response.",
example: 123,
})
@IsInt()
@IsOptional()
@ApiPropertyOptional()
responseId?: number | null;
@ApiProperty({
type: [Number],
description: "Array of team member IDs that were routed to handle this booking.",
example: [101, 102],
})
@IsArray()
@IsInt({ each: true })
teamMemberIds!: number[];
@ApiPropertyOptional({
type: String,
description: "The email of the team member assigned to handle this booking.",
example: "john.doe@example.com",
})
@IsString()
@IsOptional()
teamMemberEmail?: string;
@ApiPropertyOptional({
type: Boolean,
description: "Whether to skip contact owner assignment from CRM integration.",
example: true,
})
@IsBoolean()
@IsOptional()
skipContactOwner?: boolean;
@ApiPropertyOptional({
type: String,
description: "The CRM application slug for integration.",
example: "salesforce",
})
@IsString()
@IsOptional()
crmAppSlug?: string;
@ApiPropertyOptional({
type: String,
description: "The CRM owner record type for contact assignment.",
example: "Account",
})
@IsString()
@IsOptional()
crmOwnerRecordType?: string;
}
export class CreateRoutingFormResponseOutputData {
@ApiPropertyOptional({
type: Number,
description: "The ID of the event type that was routed to.",
example: 123,
})
@IsNumber()
@IsOptional()
eventTypeId?: number;
@ValidateNested()
@ApiProperty({ type: Routing })
@Type(() => Routing)
@ApiPropertyOptional({
type: Routing,
description: "The routing information.",
example: {
eventTypeId: 123,
routing: {
teamMemberIds: [101, 102],
teamMemberEmail: "john.doe@example.com",
skipContactOwner: true,
},
},
})
@ValidateNested()
@Type(() => Routing)
routing?: Routing;
@IsString()
@IsOptional()
@ApiPropertyOptional({
type: String,
description: "A custom message to be displayed to the user in case of routing to a custom page.",
example: "This is a custom message.",
})
routingCustomMessage?: string;
@IsString()
@IsOptional()
@ApiPropertyOptional({
type: String,
description: "The external redirect URL to be used in case of routing to a non cal.com event type URL.",
example: "https://example.com/",
})
routingExternalRedirectUrl?: string;
@ValidateNested()
@ApiProperty({
oneOf: [
{ $ref: getSchemaPath(SlotsOutput_2024_09_04) },
{ $ref: getSchemaPath(RangeSlotsOutput_2024_09_04) },
],
})
@Type(() => Object)
slots?: SlotsOutput_2024_09_04 | RangeSlotsOutput_2024_09_04;
}
export class CreateRoutingFormResponseOutput extends ApiResponseWithoutData {
@ValidateNested()
@ApiProperty({ type: CreateRoutingFormResponseOutputData })
@Type(() => CreateRoutingFormResponseOutputData)
data!: CreateRoutingFormResponseOutputData;
}
@@ -1,12 +1,28 @@
import { OrganizationsRoutingFormsRepository } from "@/modules/organizations/routing-forms/organizations-routing-forms.repository";
import { OrganizationsTeamsRoutingFormsResponsesOutputService } from "@/modules/organizations/teams/routing-forms/services/organizations-teams-routing-forms-responses-output.service";
import { Injectable } from "@nestjs/common";
import { SlotsService_2024_09_04 } from "@/modules/slots/slots-2024-09-04/services/slots.service";
import { TeamsEventTypesRepository } from "@/modules/teams/event-types/teams-event-types.repository";
import {
BadRequestException,
Injectable,
NotFoundException,
InternalServerErrorException,
} from "@nestjs/common";
import { Request } from "express";
import { getRoutedUrl } from "@calcom/platform-libraries";
import { ById_2024_09_04_type } from "@calcom/platform-types";
import type { CreateRoutingFormResponseInput } from "../inputs/create-routing-form-response.input";
import type { CreateRoutingFormResponseOutputData } from "../outputs/create-routing-form-response.output";
@Injectable()
export class OrganizationsRoutingFormsResponsesService {
constructor(
private readonly organizationsRoutingFormsRepository: OrganizationsRoutingFormsRepository,
private readonly outputService: OrganizationsTeamsRoutingFormsResponsesOutputService
private readonly outputService: OrganizationsTeamsRoutingFormsResponsesOutputService,
private readonly slotsService: SlotsService_2024_09_04,
private readonly teamsEventTypesRepository: TeamsEventTypesRepository
) {}
async getOrganizationRoutingFormResponses(
@@ -52,4 +68,201 @@ export class OrganizationsRoutingFormsResponsesService {
return this.outputService.getRoutingFormResponses([updatedResponse])[0];
}
async createRoutingFormResponseWithSlots(
orgId: number,
routingFormId: string,
query: CreateRoutingFormResponseInput,
request: Request
): Promise<CreateRoutingFormResponseOutputData> {
const { queueResponse, ...slotsQuery } = query;
this.validateDateRange(slotsQuery.start, slotsQuery.end);
const { redirectUrl, customMessage } = await this.getRoutingUrl(
request,
routingFormId,
queueResponse ?? false
);
// If there is no redirect URL, then we have to show the message as that would be custom page message to be shown as per the route chosen
if (!redirectUrl) {
return {
routingCustomMessage: customMessage,
};
}
if (!this.isEventTypeRedirectUrl(redirectUrl)) {
return {
routingExternalRedirectUrl: redirectUrl.toString(),
};
}
// Extract event type information from the routed URL
const { eventTypeId, crmParams } = await this.extractEventTypeAndCrmParams(redirectUrl);
const paramsForGetAvailableSlots = {
type: ById_2024_09_04_type,
eventTypeId,
...slotsQuery,
...crmParams,
} as const;
// Get available slots using the slots service with CRM parameters
const slots = await this.slotsService.getAvailableSlots(paramsForGetAvailableSlots);
const teamMemberIds = crmParams.routedTeamMemberIds ?? [];
const teamMemberEmail = crmParams.teamMemberEmail ?? undefined;
const skipContactOwner = crmParams.skipContactOwner ?? undefined;
const queuedResponseId = crmParams.queuedFormResponseId ?? null;
const responseId = crmParams.routingFormResponseId ?? null;
const crmAppSlug = crmParams.crmAppSlug ?? undefined;
const crmOwnerRecordType = crmParams.crmOwnerRecordType ?? undefined;
if (responseId) {
return {
routing: {
responseId,
teamMemberEmail,
teamMemberIds,
skipContactOwner,
crmAppSlug,
crmOwnerRecordType,
},
eventTypeId,
slots,
};
}
if (!queuedResponseId) {
throw new InternalServerErrorException(
"No routing form response ID or queued form response ID could be found."
);
}
return {
routing: {
queuedResponseId,
teamMemberEmail,
teamMemberIds,
skipContactOwner,
crmAppSlug,
crmOwnerRecordType,
},
eventTypeId,
slots,
};
}
private validateDateRange(start: string, end: string) {
const startDate = new Date(start);
const endDate = new Date(end);
if (endDate < startDate) {
throw new BadRequestException("End date cannot be before start date.");
}
}
private async getRoutingUrl(request: Request, formId: string, queueResponse: boolean) {
const params = Object.fromEntries(new URLSearchParams(request.body));
const routedUrlData = await getRoutedUrl(
{
req: request,
query: { ...params, form: formId, ...(queueResponse && { "cal.queueFormResponse": "true" }) },
},
true
);
if (routedUrlData.notFound) {
throw new NotFoundException("Routing form not found.");
}
if (routedUrlData?.props?.errorMessage) {
throw new BadRequestException(routedUrlData.props.errorMessage);
}
const destination = routedUrlData?.redirect?.destination;
if (!destination) {
if (routedUrlData?.props?.message) {
return {
redirectUrl: null,
customMessage: routedUrlData.props.message,
};
}
// This should never happen because there is always a fallback route
throw new InternalServerErrorException("No route found.");
}
return {
redirectUrl: new URL(destination),
customMessage: null,
};
}
private async extractEventTypeAndCrmParams(routingUrl: URL) {
// Extract team and event type information
const { teamId, eventTypeSlug } = this.extractTeamIdAndEventTypeSlugFromRedirectUrl(routingUrl);
const eventType = await this.teamsEventTypesRepository.getEventTypeByTeamIdAndSlug(teamId, eventTypeSlug);
if (!eventType?.id) {
// This could only happen if the event-type earlier selected as route action was deleted
throw new InternalServerErrorException("Chosen event type not found.");
}
// Extract CRM parameters from URL
const urlParams = routingUrl.searchParams;
const crmParams = {
teamMemberEmail: urlParams.get("cal.crmContactOwnerEmail") || undefined,
routedTeamMemberIds: urlParams.get("cal.routedTeamMemberIds")
? urlParams
.get("cal.routedTeamMemberIds")!
.split(",")
.map((id) => parseInt(id))
: undefined,
routingFormResponseId: urlParams.get("cal.routingFormResponseId")
? parseInt(urlParams.get("cal.routingFormResponseId")!)
: undefined,
queuedFormResponseId: urlParams.get("cal.queuedFormResponseId")
? (urlParams.get("cal.queuedFormResponseId") as string)
: undefined,
skipContactOwner: urlParams.get("cal.skipContactOwner") === "true" ? true : false,
crmAppSlug: urlParams.get("cal.crmAppSlug") || undefined,
crmOwnerRecordType: urlParams.get("cal.crmContactOwnerRecordType") || undefined,
};
return {
eventTypeId: eventType.id,
crmParams,
};
}
private isEventTypeRedirectUrl(routingUrl: URL) {
const routingSearchParams = routingUrl.searchParams;
return routingSearchParams.get("cal.action") === "eventTypeRedirectUrl";
}
private extractTeamIdAndEventTypeSlugFromRedirectUrl(routingUrl: URL) {
const eventTypeSlug = this.extractEventTypeFromRoutedUrl(routingUrl);
const teamId = this.extractTeamIdFromRoutedUrl(routingUrl);
if (!teamId) {
throw new NotFoundException("Team ID not found in the routed URL.");
}
if (!eventTypeSlug) {
throw new NotFoundException("Event type slug not found in the routed URL.");
}
return { teamId, eventTypeSlug };
}
private extractTeamIdFromRoutedUrl(routingUrl: URL) {
const routingSearchParams = routingUrl.searchParams;
return Number(routingSearchParams.get("cal.teamId"));
}
private extractEventTypeFromRoutedUrl(routingUrl: URL) {
const pathNameParams = routingUrl.pathname.split("/");
return pathNameParams[pathNameParams.length - 1];
}
}
@@ -53,7 +53,7 @@ export type OAuthCallbackState = {
path: "/v2/organizations/:orgId/teams/:teamId/stripe",
version: API_VERSIONS_VALUES,
})
@DocsTags("Organizations/Teams Stripe")
@DocsTags("Orgs / Teams / Stripe")
export class OrganizationsStripeController {
constructor(
private readonly organizationsStripeService: OrganizationsStripeService,
@@ -65,7 +65,7 @@ export class OrganizationsStripeController {
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
@Get("/connect")
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: "Get stripe connect URL for a team" })
@ApiOperation({ summary: "Get Stripe connect URL for a team" })
async getTeamStripeConnectUrl(
@Req() req: Request,
@Headers("Authorization") authorization: string,
@@ -104,7 +104,7 @@ export class OrganizationsStripeController {
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
@Get("/check")
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: "Check team stripe connection" })
@ApiOperation({ summary: "Check team Stripe connection" })
async checkTeamStripeConnection(
@Param("teamId", ParseIntPipe) teamId: number
): Promise<StripCredentialsCheckOutputResponseDto> {
@@ -116,7 +116,7 @@ export class OrganizationsStripeController {
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
@Get("/save")
@Redirect(undefined, 301)
@ApiOperation({ summary: "Save stripe credentials" })
@ApiOperation({ summary: "Save Stripe credentials" })
async save(
@Query("state") state: string,
@Query("code") code: string,
@@ -80,7 +80,7 @@ export class OrganizationsTeamsBookingsController {
IsAdminAPIEnabledGuard
)
@ApiOperation({
summary: "Get 'Booking References' for a booking",
summary: "Get booking references",
})
@HttpCode(HttpStatus.OK)
async getBookingReferences(

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