Compare commits

..
298 Commits
Author SHA1 Message Date
GitHub Actions 95bf90402c chore: release v4.9.4
Post release / release (push) Canceled after 0s
2025-01-21 20:23:21 +00:00
Carina WollendorferandCarinaWolli f523ce7795 fix: custom templates on team plan (#18792)
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2025-01-21 20:16:57 +00:00
Joe Au-Yeung 65b70d682d fix: Initialize Hubspot client in CRMService (#18789)
* Initialize Hubspot client in class

* Remove debugging artifact
2025-01-21 16:47:32 -03:00
Alex van Andel 2d518f49dd Double available memory on api/book/event (#18790) 2025-01-21 19:01:58 +00:00
7a9d291d1f fix: handle cancelation reason when user is host (#18681)
* handle cancelation reason when user is host

* add attendee reason warning

* add cancellation reason to tests when we are the host

* req.body and not req

* fix: isloggedIn logic

* use new isLoggedInUser from ssr instead of client

* update e2e tests to fill in reason when hosts

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: Udit Takkar <udit222001@gmail.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-21 20:24:06 +05:30
Keith Williams 1a1a506324 chore: Remove Chromatic GitHub workflow (#18780) 2025-01-21 13:50:53 +00:00
Benny Joo 0f7ecb3345 chore: migrate low-risk 3 /auth pages to App Router (#18753)
* add i18n string

* Update config.matcher in middleware

* migrate auth/oauth2/authorize

* migrate auth/platform/authorize

* migrate auth/signin
2025-01-21 10:41:00 +01:00
Mehul 4f1d71e660 fix: routing form list overflow (#18686) 2025-01-21 10:40:44 +01:00
Udit Takkar 30eb7ce846 feat: add transcription as attachment (#18740)
* feat: add transcription as attachment

* fix: change style
2025-01-21 06:07:10 +00:00
3eb5490df9 feat: Use Cloudflare Turnstile in booker (#18755)
* feat: Use Cloudflare Turnstile in booker

* move files arround

* render turnstile widget and add token to store

* use token from body instead of headers

* watch cf token to re-render disabled state

* Update packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx

* Update packages/features/bookings/lib/create-booking.ts

* ensure bool

* add to recuring event

* fix recuring events

---------

Co-authored-by: sean-brydon <sean@cal.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
Co-authored-by: Benny Joo <sldisek783@gmail.com>
2025-01-21 11:27:56 +05:30
GitHub Actions 235382213f chore: release v4.9.3
Post release / release (push) Canceled after 0s
2025-01-20 21:05:54 +00:00
Alex van Andel 01baf7d3c0 chore: Add more logging around getUserAvailability (#18769)
* chore: Add more logging around getUserAvailability

* Add initialData to logging
2025-01-20 17:04:43 +00:00
Calcom BotandReplexica 1a649158e1 feat: update translations via @replexica (#18764)
Co-authored-by: Replexica <support@replexica.com>
2025-01-20 12:41:25 -03:00
Joe Au-Yeung d6306dcd22 fix: Disable custom templates for trialing teams (#18748)
* Create `checkIfTeamHasActivePlan` method on `stripe-billing-service`

* Add `checkIfTeamPlanIsActive` to `InternalTeamBilling`

* Create `hasActiveTeamPlan` trpc endpoint

* Check for active team plan when updating workflows

* Create `useHasActiveTeamPlan` hook

* Use `useHasActiveTeamPlan` on workflow edit page

* Type fixes

* Type fix

* Add `accepted` to team query
2025-01-20 14:48:33 +00:00
Muhammad Aiman Sulaimanandkutsaniuk 7131a1f015 feat: HitPay Payment App (#17213)
* Build HitPay app

* Deleted a lint comment

* Add redirect for iframe

* Fix type check error

* Fixed issue of payment pending

* Update hitpay package.json

* fix: fix lint issue in KeyInput and update zod

* fix: fix issue of parsing string to number

* fix: add default hitpay API links

* fix: resolve atoms build error

---------

Co-authored-by: kutsaniuk <kutsaniuk@gmail.com>
2025-01-20 15:36:23 +01:00
Eunjae Lee 5357228f72 fix: nested scrolls on /bookings/upcoming (#18760) 2025-01-20 09:18:12 -05:00
Lauris Skraucis bfeafaa21f fix: ensure platform managed user has 1 schedule by default (#18719)
* fix: ensure managed user has 1 schedule

* chore: bump platform libraries
2025-01-20 09:11:26 +00:00
Syed Ali Shahbaz 02ef6dc934 Fix raycast bug (#18756) 2025-01-20 10:03:54 +01:00
Benny Joo 4424b2aea3 useIsThemeSupported hook (#18746) 2025-01-20 14:30:18 +05:30
Syed Ali Shahbaz 1f91fe888a bump libphonenumber-js version to 1.11.18 (#18757) 2025-01-20 07:14:01 +00:00
sean-brydonandAlex van Andel b4a51d3560 feat: auto lock (#18630)
* add delete to redis service

* auto lock + tests

* changes to autolock in api/book call

* remove log clutter

* add detection in api v1

* tpye changes

* throw error and add tests for API

* add response logic on locked + tests

* type response properly i hope?

* type fix

* add tests for counter not existing + redis errors

* remove IP - add sentry to track

* rename symbol

* fix type error

* fix tests

* remove sentry call spy

* fix type on sentry setUser call

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-01-18 16:21:12 -03:00
Benny Joo 4855b6b40f fix: small spacing fix in app router 404 (#18741) 2025-01-17 16:45:30 -07:00
Eunjae Lee 4b264a867b fix: adjust table height for a few rows on /bookings (#18728) 2025-01-17 23:07:39 +00:00
GitHub Actions 9caaa0af32 chore: release v4.9.2
Post release / release (push) Canceled after 0s
2025-01-17 22:03:02 +00:00
f411c6ed11 feat: Use dub.customer.list to issue dual-sided incentives (#18452)
* [FEAT] Use dub.customer to issue dual-sided incentives

* update dub implementation

* uncommit yarn.lock

* Update yarn.lock

* account for self-hosting

* remove comments

---------

Co-authored-by: Omar López <zomars@me.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-17 21:33:33 +00:00
Benny Joo 245196fbf3 chore: technical debt clearing - remove getServerSideProps for /event-types (#18733)
* chore: technical debt clearing - remove getServerSideProps for event-types

* refactor
2025-01-17 21:35:03 +01:00
Steven TeyandAlex van Andel 6be69b820c chore: Bump Dub version to fix createMany error (#18591)
Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-01-17 08:53:44 -07:00
Benny Joo b63c9791ec fix (#18718) 2025-01-17 10:48:31 -05:00
Anik Dhabal Babu 8cc61a1fe9 fix: Impersonation issue from userstable (#18608)
* fix: visible error in the userlist handler

* Uncommit yarn.lock

* update
2025-01-17 14:04:41 +00:00
Anik Dhabal Babu be2e1274ff fix: Getting an error with managed events when accessing through api/v1 (#18683)
* fix: getting error with managed events when get through api/v1

* update
2025-01-17 13:59:34 +00:00
Anik Dhabal Babu fa3b1c17ea fix: duplicating an event turns private link on (#18727) 2025-01-17 13:59:19 +00:00
Benny Joo 015edd3c9b chore: migrate /auth/new (#18732)
* move out of /future dir

* remove legacy pages
2025-01-17 06:46:59 -05:00
Benny Joo de05e8e989 chore: migrate /auth/error (#18730)
* migrate auth/error

* fix

* fix type check
2025-01-17 06:46:47 -05:00
Benny Joo 78a6963cd9 chore: clean up <HeadSeo> components where not needed (#18731)
* clean up headseo from d-type-view

* clean up headseo from bookings-single-view

* clean up headseo from team-view
2025-01-17 10:57:39 +00:00
Udit Takkar ea827ebbc6 fix: edit webhook time (#18549) 2025-01-17 08:56:50 +00:00
Joe Au-YeungandPeer Richelsen 08e58851e7 feat: Salesforce - write to field without validation (#18722)
* Allow user to select custom field type

* Get field value and write to field - ignoring field type

* Only validate field length if present

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-17 08:55:34 +00:00
Cao Hoang da1b8137c2 fix: filters ui breaking on mobile in routing insights page (#18713) 2025-01-17 09:40:16 +01:00
Anik Dhabal BabuandUdit Takkar d182e5c99a fix: Booking with the same email when using capital letters (#18694)
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-01-17 09:37:10 +01:00
Nizzy 42259a113b fix: resize app-store images to use less bytes (#18675) 2025-01-17 09:35:01 +01:00
+8 6561b92f40 perf: Move CRM event creation to tasker (#18370)
* Upgrade jsforce to 3.6.2

* Refactor connecting to Salesforce

* Revert yarn.lock changes

* Add `TASKER_ENABLE_CRM_EVENT_CREATION` to .env

* Add createCRMEvent scheduler

* Schedule CRM event creating in `EventManager`

* Add calendar event builder for CRM tasks

* Do not write to person record if fields don't exist

* Change type to expect string from tasker

* Create CRM event

* Create booking references

* Type fixes

* Migrate callback endpoint

* Add jsforce node dependency

* Migrate add endpoint

* Import

* Import package into crmService

* Use new package types

* Type fix

* Update vite config

* Push updated lockfile

* Attempt to bump platform/libraries to unlock jsforce

* Also update lockfile, naturally

* bump platform libraries

* feat: salesforce to tasker improvements (#18419)

* feat: salesforce to tasker

* refactor: event manager

* tests: add unit tests for create CRM Event

* Update vite.config

* Add jsforce to vite config

* Revert mint.json changes

* Default to not enabling

* Revert yarn.lock changes

* Remove `TASKER_ENABLE_CRM_EVENT_CREATION` variable

* Revert yarn.lock changes

* feat: Round Robin weights future members toggle (#17782)

Co-authored-by: Omar López <zomars@me.com>

* detailed customer card (#18511)

Co-authored-by: Omar López <zomars@me.com>

* chore: app router - all sub-pages in `/apps` (#16976)

* chore: apps/[slug] remove pages router

* remove apps/[slug] pages from /future

* chore: apps/installed remove pages router

* chore: apps/installation remove pages router

* remove Head element

* fix metadata

* fix test

* fix another test

* chore: apps/categories remove pages router

* revert unneeded changes

* update middleware

* Remove <Head>

* remove unused import and code

* remove unused import and code again

* fix

* fix category page

* add split icon

* add /routing paths to middleware matcher

* wip

* remove HeadSeo from App.tsx

* clean up head-seo test

* add generateAppMetadata

* use generateAppMetadata in apps/[slug] page

* delete file

* remove log

* fix

* fix

* fix apps/installed pages

* fix cateogires pages

* fix

* fix imports

* wip

* fix

* fix

* fix metadata

* fix

* redirect /apps/routing-forms to /routing

* replace all usages of /apps/routing-forms to /routing

* better naming

* /routing -> /routing/forms

* fix

* fix

* fix

* fix

* remove backPath as it is irrelevant when withoutMain is true

* fix type checks

* fix type check in apps/[slug]

* refactors

* fix

* fix test

* fix

* fix

* fix

* Replace multiple leading slashes with a single slash

* migrate routing-forms too

* add re routing

* fix

* add redirection

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>

* chore: app router 404 page (#18597)

* wip

* wip

* fix not found page

* render middleware for /settings pages

* fix

* remove global-error page

* add metadata to not-found page

* make not-found page static

* remove 404

* adding not-found to middleware is not necessary

* add every routes to config.matcher

* fix test

* fix style

* use i18n string

* fix tests

* fix

* fix

* revert unneeded changes

* fix

* fix

* fix

* fix style

* fix

* remove 404

* remove log

* fix

* fix

* fix

* fix

* better naming

* parallel testing

---------

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

* feat: render custom error page for unexpected sever error + remove` pages/_error` (#18606)

* remove page/_error

* refactor app/error

* fix: app/not-found cannot be a static page (#18610)

* Async False (#18611)

* chore: redirect to /500 if pathname does not exist + better error handling (#18615)

* fix lint error

* fix booking page and better error handling

* chore: gracefully handle 404s from pages router's dynamic pages + tests (#18618)

* restore pages/_error

* set custom header in pages/_error

* handle it in middleware

* add test

* remove logs

* better test description

* chore: try using custom 404 in pages/_error (#18622)

* fix: parsing teamId (#18623)

* chore: restore error pages for pages router (#18625)

* disable emails to all guests (#18628)

Co-authored-by: CarinaWolli <wollencarina@gmail.com>

* revert: "feat: bulk shorten links with dub.links.createMany (#18539)" (#18587)

This reverts commit 4902c6a0f8.

Co-authored-by: Alex van Andel <me@alexvanandel.com>

* chore: release v4.8.18

* fix: disable sending sms when email is present (#18632)

* fix: disable sending sms when email is present

* fix: update test

* fix: main lint errors (#18634)

* fix: error-page.tsx related lint errors

* fix: lint no continue-on-error

* Adding more lint fixes

* Bring back annotate code linting results

* Bring back linting continue-on-error

* Slimline lint

* feat: do not show automation webhooks in webhook list (#18607)

* fix: make ESLint work and fix lint errors that were undetected before (#18639)

* fix eslint config

* fix

* add it to dev dep

* fix

* sync eslint version

* force ts-node to compile our ESLint plugin's TS files into CommonJS (which ESLint requires)

* fix some lint errors

* fix lint errors

* remove duplicate classname

* make @typescript-eslint/ban-types a warn for packages/trpc files

* fix lint errors in trpc

* fix lint errors in trpc - 2

* fix

* fix

* fix lint warnings

* chore: clean up config.matcher in middleware (#18638)

Co-authored-by: Alex van Andel <me@alexvanandel.com>

* Allow lint to error but continue (unblock pipeline)

* fix: potential fix for flaky layout shift (#18651)

* potential fix: layout shift

* fix lint error

* feat: update translations via @replexica (#18598)

* chore: sync with main

* feat: update translations via @replexica

---------

Co-authored-by: Replexica <support@replexica.com>

* Update yarn.lock

* nit: let tasker handle payload stringification

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Morgan Vernay <morgan@cal.com>
Co-authored-by: Omar López <zomars@me.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
Co-authored-by: Nizzy <140507264+nizzyabi@users.noreply.github.com>
Co-authored-by: Benny Joo <sldisek783@gmail.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: GitHub Actions <github-actions@github.com>
Co-authored-by: Kartik Saini <41051387+kart1ka@users.noreply.github.com>
Co-authored-by: Calcom Bot <109866826+calcom-bot@users.noreply.github.com>
Co-authored-by: Replexica <support@replexica.com>
2025-01-16 22:07:30 -05:00
Benny Joo 9e5665f2fb Revert "fix: revert app router error pages (#18696)" (#18714)
This reverts commit 3cc5d9c065.
2025-01-16 16:53:47 -05:00
GitHub Actions 07778d22ed chore: release v4.9.1
Post release / release (push) Canceled after 0s
2025-01-16 18:01:24 +00:00
Joe Au-Yeung 56df8bdf7c feat: Salesforce - map booking questions to event record (#18532) 2025-01-16 12:28:07 -05:00
GitHub Actions a518c7152a chore: release v4.9.1-rc1
Post release / release (push) Canceled after 0s
2025-01-16 15:53:45 +00:00
Benny Joo c37a8a587b fix: add decoding logic to app router params (#18712)
* decode app router params in buildLegacyCtx

* add helpful comments

* add comment

* address comment
2025-01-16 15:14:03 +00:00
Alex van Andel b7f7c33afc feature: Allow non-calcom domains to run team slug pages (#18711) 2025-01-16 09:44:14 -03:00
Lauris Skraucis 1d449ecc6b fix: v2 booking guests (#18690)
* fix: v2 booking guests

* test
2025-01-16 11:20:18 +02:00
Lauris Skraucis f582faed2b fix: Booking atom phone booking field and booking fields order (#18678)
* chore: examples app make managed user admin

* fix: phone field not appearing

* fix: booking fields order

* feat: local libraries setup script

* chore: add log when parsing booking field fails

* fix: backwards compatbile name booking field

* chore: libraries publish support scripts

* chore: bump libraries

* docs

* fix: phone default field return label and placeholder

* fix: e2e tests
2025-01-16 11:10:06 +02:00
GitHub Actions 79a8ab79f8 chore: release v4.9.0
Post release / release (push) Canceled after 0s
2025-01-16 01:26:26 +00:00
Benny Joo ce87de4fc7 fix: Revert - chore: app router - all sub-pages in /apps #16976 (#18702)
* revert

* add incomplete-booking
2025-01-15 21:12:18 -03:00
Calcom BotandReplexica b128579729 feat: update translations via @replexica (#18699)
Co-authored-by: Replexica <support@replexica.com>
2025-01-15 20:38:44 +00:00
Benny Joo 3cc5d9c065 fix: revert app router error pages (#18696) 2025-01-15 16:47:30 -03:00
Benny Joo 7897e14273 fix: add back global-error.tsx (#18692) 2025-01-15 16:55:43 +00:00
GitHub Actions c581456586 chore: release v4.8.19
Post release / release (push) Canceled after 0s
2025-01-15 15:30:52 +00:00
36dd3e9e6c fix: disable custom templates for free plan (#18635)
* add upgrade badge

* adjust update handler

* code clean up

* clean up template code

* only handle email templates

* fixes

* code clean up

* fix workflow template zod type

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-01-15 15:25:14 +00:00
Alex van Andel f137aee436 Remove export keyword @ route - only default allowed (#18682) 2025-01-15 14:33:02 +00:00
Eunjae Lee 4f494d5a32 refactor: use DataTable for /bookings (#18589)
* refactor: use DataTable for /bookings

* remove unnecessary animation (for better scroll performance)

* add consistent search box
2025-01-15 14:29:50 +00:00
Benny Joo cce6e83578 chore: migrate /org team pages and team type pages and user type page (#18668) 2025-01-15 09:21:21 +00:00
Lauris Skraucis c21ba636d2 fix: Booker atom name booking field (#18653)
* feat: split name booking field in v2

* fix: booker atom handle split name

* fix: after and before start dates bookings filter

* chore: bump platform libraries
2025-01-15 14:08:06 +05:30
Benny Joo 5ccf5e6be8 chore: migrate /team booking pages (#18656)
* wip

* remove pages/team/[slug]

* fix tests

* fix tests 2
2025-01-14 23:48:41 +00:00
Joe Au-YeungandAlex van Andel 66b3e735d8 feat: Routing form submitted but no booking - Salesforce actions (#18616)
* Add booking incomplete actions table

* Add incomplete booking page tab

* Add `getincompleteBookingSettings` trpc endpoints

* Add incomplete booking page

* Abstract enabled apps array

* Handle no enabled credentials and no actions

* Add enabled field to incomplete booking action db record

* Add new write record entries

* UI add separation between switch and inputs

* Fix typo

* clean up

* Add saveIncompleteBookingSettings endpoint

* Save incomplete booking settings

* Fix language around when to write to field

* Add `credentialId` to action record

* Choose which credential to assign to action

* Save credential to action

* Revert "Save credential to action"

This reverts commit ba6a1c808baed54f6d3d4c6155cf192c813d0696.

* Revert "Choose which credential to assign to action"

This reverts commit 968f6e5295d098c64abe95268afd1fa139a175ba.

* Revert "Add `credentialId` to action record"

This reverts commit 579f9ff4167b65aa987659e4e8f8c26f9e773317.

* Add credentialId to action record - rewrite migration file

* Revert "Add credentialId to action record - rewrite migration file"

This reverts commit 2843a92c61820e7f7a1614a557d3f7ea96342107.

* Revert "Add booking incomplete actions table"

This reverts commit 7ec75bef4a0f0a9d07be0142da64c49d739439ea.

* Revert "Add enabled field to incomplete booking action db record"

This reverts commit d279a1da05819eafa8fc5d664e3be733e0687e8d.

* Write migration in single commit

* Rename table

* Rename table - remove underscores

* Remove credential relationship

* Type fix - changing table name

* Fix table name

* Change writeToRecordObject to object

* Salesforce add incomplete booking, write to record

* Add incomplete booking actions to `triggerFormSubmittedNoEventWebhooks`

* Remove console.log

* Type fixes

* Type fixes

* Iterate if incompleteBookingActions

* Choose which credential to assign to action

* Save credential to action

* Fix getServerSideProp changes

* Type fix

* Type fix

* Type fix

* Type fix

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-01-14 23:17:16 +00:00
Praash 7a8b9ededb fix: html render from calendar invite (#18577) 2025-01-14 20:40:31 +00:00
Benny Joo 501c49f369 perf: no need for two query fetches for d link (private booking page) (#18659)
* return eventData

* use eventData and do not do extra query fetch
2025-01-14 17:15:56 +00:00
Amit Sharma 536604455b fix: BUG: adding filters to settings/teams/[team-id]/members page throws error (#18631) 2025-01-14 16:30:54 +00:00
MorganandPeer Richelsen cfb76a9689 chore: platform libraries readme publish reasons (#18646)
* chore: platform libraries readme publish reasons

* fixup! chore: platform libraries readme publish reasons

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-14 16:28:34 +00:00
Udit TakkarandPeer Richelsen 30180edc0b fix: phone number in confirmation email (#18642)
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-14 16:27:24 +00:00
MorganandCarina Wollendorfer 2aa3d1d4e0 feat: get org ooo entries and filters/sort (#18645)
* feat: get org ooo entries and filters/sort

* remove console.log

---------

Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
2025-01-14 15:33:22 +00:00
Eunjae Lee 21694c039a perf: improve routing insights view (2) (#18566) 2025-01-14 12:28:39 -03:00
Benny Joo a8c29b5459 chore: log error to Sentry in app router error page (#18637) 2025-01-14 15:23:07 +00:00
Anik Dhabal Babu 6cd7454f43 fix: /booking page datefilter (#18654)
* fix: /booking page datefilter

* Update get.handler.ts

* Update get.handler.ts

* shit
2025-01-14 15:14:28 +00:00
Calcom BotandReplexica 99b2419dd7 feat: update translations via @replexica (#18598)
* chore: sync with main

* feat: update translations via @replexica

---------

Co-authored-by: Replexica <support@replexica.com>
2025-01-14 13:47:22 +00:00
Benny Joo f6d0a2ca09 fix: potential fix for flaky layout shift (#18651)
* potential fix: layout shift

* fix lint error
2025-01-14 13:36:20 +00:00
Alex van Andel f5ab9bd40b Allow lint to error but continue (unblock pipeline) 2025-01-14 13:12:24 +00:00
Benny JooandAlex van Andel 07085b9ffb chore: clean up config.matcher in middleware (#18638)
Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-01-14 10:24:36 +00:00
Benny Joo 14151b827f fix: make ESLint work and fix lint errors that were undetected before (#18639)
* fix eslint config

* fix

* add it to dev dep

* fix

* sync eslint version

* force ts-node to compile our ESLint plugin's TS files into CommonJS (which ESLint requires)

* fix some lint errors

* fix lint errors

* remove duplicate classname

* make @typescript-eslint/ban-types a warn for packages/trpc files

* fix lint errors in trpc

* fix lint errors in trpc - 2

* fix

* fix

* fix lint warnings
2025-01-14 08:58:38 +00:00
Kartik Saini 28b757f19c feat: do not show automation webhooks in webhook list (#18607) 2025-01-14 10:55:22 +05:30
Alex van Andel 68455db860 fix: main lint errors (#18634)
* fix: error-page.tsx related lint errors

* fix: lint no continue-on-error

* Adding more lint fixes

* Bring back annotate code linting results

* Bring back linting continue-on-error

* Slimline lint
2025-01-13 22:01:20 +00:00
Udit Takkar 96ff88d266 fix: disable sending sms when email is present (#18632)
* fix: disable sending sms when email is present

* fix: update test
2025-01-13 20:38:44 +00:00
GitHub Actions f88a91dad0 chore: release v4.8.18
Post release / release (push) Canceled after 0s
2025-01-13 18:12:32 +00:00
Keith WilliamsandAlex van Andel 35059d7727 revert: "feat: bulk shorten links with dub.links.createMany (#18539)" (#18587)
This reverts commit 4902c6a0f8.

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-01-13 18:07:27 +00:00
Carina WollendorferandCarinaWolli 68f76e2acc disable emails to all guests (#18628)
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2025-01-13 15:58:43 +00:00
Benny Joo 80aac06ff3 chore: restore error pages for pages router (#18625) 2025-01-13 12:42:00 +00:00
sean-brydon 0f47528ba2 fix: parsing teamId (#18623) 2025-01-13 12:16:59 +00:00
Benny Joo 113dc5fca6 chore: try using custom 404 in pages/_error (#18622) 2025-01-13 11:35:10 +00:00
Benny Joo 0befdde5d7 chore: gracefully handle 404s from pages router's dynamic pages + tests (#18618)
* restore pages/_error

* set custom header in pages/_error

* handle it in middleware

* add test

* remove logs

* better test description
2025-01-13 15:46:56 +05:30
Benny Joo b3ed6e39e3 chore: redirect to /500 if pathname does not exist + better error handling (#18615)
* fix lint error

* fix booking page and better error handling
2025-01-13 00:04:36 +00:00
sean-brydon e07b1eda32 Async False (#18611) 2025-01-12 20:31:43 +00:00
Benny Joo 8262894bde fix: app/not-found cannot be a static page (#18610) 2025-01-12 20:21:03 +01:00
Benny Joo a3d7bcd22e feat: render custom error page for unexpected sever error + remove pages/_error (#18606)
* remove page/_error

* refactor app/error
2025-01-12 14:12:02 +01:00
Omar LópezandBenny Joo 62b753afba chore: app router 404 page (#18597)
* wip

* wip

* fix not found page

* render middleware for /settings pages

* fix

* remove global-error page

* add metadata to not-found page

* make not-found page static

* remove 404

* adding not-found to middleware is not necessary

* add every routes to config.matcher

* fix test

* fix style

* use i18n string

* fix tests

* fix

* fix

* revert unneeded changes

* fix

* fix

* fix

* fix style

* fix

* remove 404

* remove log

* fix

* fix

* fix

* fix

* better naming

* parallel testing

---------

Co-authored-by: Benny Joo <sldisek783@gmail.com>
2025-01-11 02:42:08 +00:00
bb40b2f6bf chore: app router - all sub-pages in /apps (#16976)
* chore: apps/[slug] remove pages router

* remove apps/[slug] pages from /future

* chore: apps/installed remove pages router

* chore: apps/installation remove pages router

* remove Head element

* fix metadata

* fix test

* fix another test

* chore: apps/categories remove pages router

* revert unneeded changes

* update middleware

* Remove <Head>

* remove unused import and code

* remove unused import and code again

* fix

* fix category page

* add split icon

* add /routing paths to middleware matcher

* wip

* remove HeadSeo from App.tsx

* clean up head-seo test

* add generateAppMetadata

* use generateAppMetadata in apps/[slug] page

* delete file

* remove log

* fix

* fix

* fix apps/installed pages

* fix cateogires pages

* fix

* fix imports

* wip

* fix

* fix

* fix metadata

* fix

* redirect /apps/routing-forms to /routing

* replace all usages of /apps/routing-forms to /routing

* better naming

* /routing -> /routing/forms

* fix

* fix

* fix

* fix

* remove backPath as it is irrelevant when withoutMain is true

* fix type checks

* fix type check in apps/[slug]

* refactors

* fix

* fix test

* fix

* fix

* fix

* Replace multiple leading slashes with a single slash

* migrate routing-forms too

* add re routing

* fix

* add redirection

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-01-10 20:16:11 -05:00
NizzyandOmar López f628dc83a8 detailed customer card (#18511)
Co-authored-by: Omar López <zomars@me.com>
2025-01-10 23:51:27 +00:00
sean-brydonandOmar López 2fd2578504 feat: Round Robin weights future members toggle (#17782)
Co-authored-by: Omar López <zomars@me.com>
2025-01-10 14:24:19 -07:00
Syed Ali ShahbazandCarinaWolli a29407349d docs: fix error introduced in #18578 (#18593)
* Fix error

* remove indent

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2025-01-10 19:48:12 +00:00
Joe Au-YeungandAnik Dhabal Babu e7df1ef493 fix: Create dub links if valid url (#18588)
* Create dub links if valid

* Map through filtered links

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-01-10 15:58:16 +00:00
Kartik Saini b652ae7714 fix: wrong Meeting Ended payload in zapier (#18202)
* fix: wrong Meeting Ended payload in zapier

* fix
2025-01-10 15:55:35 +01:00
Peer Richelsen cec1c9ee46 feat: granola.ai app (#18585)
* new granola app

* granola app
2025-01-10 14:47:18 +00:00
GitHub Actions 3813fd70f7 chore: release v4.8.16
Post release / release (push) Canceled after 0s
2025-01-10 14:01:39 +00:00
Morgan dabd3b0fc3 chore: improve ooo reason documentation apiv2 (#18582) 2025-01-10 13:20:39 +00:00
Calcom BotandReplexica 95f9a02d29 feat: update translations via @replexica (#18584)
Co-authored-by: Replexica <support@replexica.com>
2025-01-10 13:19:47 +00:00
Somay Chauhan f26d2998cb feat: added pagination to platform managed users table (#18523)
* feat: added pagination to platform managed users table

* removed console

* implemented feedback, removed unused components

* added label

* Update managed-users-view.tsx

* Update managed-users-view.tsx
2025-01-10 12:53:20 +00:00
Somay Chauhan f558f8aca5 fix: broken platform members table (#18583) 2025-01-10 12:46:48 +00:00
Syed Ali ShahbazandPeer Richelsen a6dd5185ea docs: fix footer socials in /help and other broken pages (#18578)
* Update mint.json

* fix broken links

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-10 12:50:45 +01:00
Anik Dhabal Babu 3da7694002 fix: flaky e2e test in saml.e2e (#18559)
* chore: skip failure e2e test

* Update .env

* Update manage-booking-questions.e2e.ts

* Update manage-booking-questions.e2e.ts

* Update manage-booking-questions.e2e.ts

* Update manage-booking-questions.e2e.ts

* Update manage-booking-questions.e2e.ts

* Update manage-booking-questions.e2e.ts

* Update .env

* Update manage-booking-questions.e2e.ts

* fix

* fix flake

* Update saml.e2e.ts
2025-01-10 17:17:12 +05:30
Eunjae Lee 1ffb376789 fix: improve filters at /bookings (#18581)
* fix: improve filters at /bookings

* fix type
2025-01-10 11:10:10 +00:00
Anik Dhabal BabuandUdit Takkar 8761b91f71 fix: unpublished org is visble as an option in workflow (#18522)
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-01-10 10:49:08 +00:00
Nizzy 1dbef7f8f6 fix: billing plain chat working (#18530) 2025-01-10 10:12:30 +00:00
Anik Dhabal BabuandPeer Richelsen d4d5ac2b28 fix: date filter for the same day showing appointments of the day before (#18579)
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-10 15:42:24 +05:30
Omar López 88c8ad8b5c chore: fix SVG warning on render (#18572) 2025-01-10 10:00:43 +00:00
Benny Joo 0a08680084 cleanup: remove-headseo-from-migrated-app-router-components (#18576) 2025-01-10 10:35:37 +01:00
Anik Dhabal Babu 65828545b9 fix: wip (#18574) 2025-01-10 00:38:04 -05:00
Omar López 3adb8e84fc chore: Webhook should timeout fast on e2e (#18570) 2025-01-09 20:52:55 -03:00
2a29155641 chore: Upgrade jsforce to 3.6.2 and use jsforce-node (#18363)
* Upgrade jsforce to 3.6.2

* Refactor connecting to Salesforce

* Revert yarn.lock changes

* Migrate callback endpoint

* Add jsforce node dependency

* Migrate add endpoint

* Import

* Import package into crmService

* Use new package types

* Type fix

* Update vite config

* Push updated lockfile

* Attempt to bump platform/libraries to unlock jsforce

* Also update lockfile, naturally

* bump platform libraries

* Update vite.config

* Add jsforce to vite config

* fixup! Merge branch 'main' into upgrade-jsforce-v3

* fixup! fixup! Merge branch 'main' into upgrade-jsforce-v3

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Morgan Vernay <morgan@cal.com>
Co-authored-by: Omar López <zomars@me.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-01-09 20:24:06 +00:00
Steven TeyandPeer Richelsen 4902c6a0f8 feat: bulk shorten links with dub.links.createMany (#18539)
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-09 20:04:55 +00:00
Joe Au-YeungandUdit Takkar a22fd0c151 chore: Salesforce - optimize getContact method [CAL-4940] (#18289)
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-01-09 12:14:49 -07:00
Peer Richelsen b6bd0eda43 Documentation edits made through Mintlify web editor 2025-01-09 19:59:04 +01:00
mintlify[bot]andPeer Richelsen 25d052e8f0 mintlify help edits (#18562)
* Documentation edits made through Mintlify web editor

* Documentation edits made through Mintlify web editor

* Delete help/calendars/how-to-add-apple-calendar.mdx

* Delete help/calendars/how-to-add-google-calendar.mdx

---------

Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-09 19:56:22 +01:00
mintlify[bot] f933432d2b Documentation edits made through Mintlify web editor (#18565)
Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
2025-01-09 19:52:49 +01:00
Benny JooandAnik Dhabal Babu ccf1d4430a chore: clean up some code in app router (#18541)
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-01-09 10:47:21 -07:00
2fd8d24204 perf: Improve routing insights view (#18557)
* perf: Improve routing insights view

* fix: remove old join

---------

Co-authored-by: Eunjae Lee <hey@eunjae.dev>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-01-09 16:42:26 +00:00
Syed Ali Shahbaz b4c18f7bcc Update README.md (#18524) 2025-01-09 16:33:02 +00:00
sean-brydon 23c93d75ca fix: Handle booker UI busy or skip on timeslot (#18553) 2025-01-09 16:29:42 +00:00
Benny Joo 91526d0bc7 chore: unique key missing for child (#18542) 2025-01-09 16:20:05 +00:00
Anik Dhabal Babu a9f95937c4 chore: temporarily skip a failing E2E test (#18560) 2025-01-09 15:53:12 +00:00
Nizzy 74580157ba fix: added videos and fixed iframe sizes for help page docs (#18558) 2025-01-09 16:37:59 +01:00
mintlify[bot] fcdbcceac0 feat: Mintlify /help edits (#18555)
* Documentation edits made through Mintlify web editor

* Documentation edits made through Mintlify web editor

* Documentation edits made through Mintlify web editor

* Documentation edits made through Mintlify web editor

---------

Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
2025-01-09 15:36:56 +01:00
Peer Richelsen aa7c924c2a Documentation edits made through Mintlify web editor 2025-01-09 13:23:51 +01:00
Peer Richelsen 3406ca72bc Documentation edits made through Mintlify web editor 2025-01-09 13:22:18 +01:00
Peer Richelsen c29a2fc7cb Documentation edits made through Mintlify web editor 2025-01-09 13:20:03 +01:00
Peer Richelsen 0a4c7bcecc Documentation edits made through Mintlify web editor 2025-01-09 13:19:26 +01:00
Peer Richelsen 803dfa008c Documentation edits made through Mintlify web editor 2025-01-09 13:17:24 +01:00
Peer Richelsen 0eb6f1beb6 chore: mintlify updates (#18552) 2025-01-09 13:05:32 +01:00
Peer Richelsen edd2e5e584 chore: fixed help logo (#18551) 2025-01-09 12:57:09 +01:00
mintlify[bot] 99a99b4b7e Documentation edits made through Mintlify web editor (#18543) 2025-01-09 09:45:21 +01:00
Somay ChauhanandRajiv Sahal 2ba6f4cb24 fix: payment not working in booker (#18540)
* fix: payment not working in booker

* Update transformApiEventTypeForAtom.ts

---------

Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
2025-01-09 07:32:13 +00:00
Udit TakkarandBailey Pumfleet 8a8c870513 chore: change identifier (#18518)
Co-authored-by: Bailey Pumfleet <bailey@pumfleet.co.uk>
2025-01-08 23:39:56 -05:00
Peer Richelsen eba335c903 chore: moved docs into mintlify (#18536) 2025-01-08 23:01:53 +01:00
GitHub Actions 9b2161cc19 chore: release v4.8.15
Post release / release (push) Canceled after 0s
2025-01-08 18:53:07 +00:00
Morgan b997c656df feat: api v2 org ooo crud (#18499)
* feat: api v2 org ooo crud

* chore: add guard isUserOOO on ooo controller

* chore: add checks for ooo

* fixup! chore: add checks for ooo

* added e2e tests

* fixup! added e2e tests
2025-01-08 10:50:58 -05:00
Udit Takkarandsupalarry c9c5493de6 feat: support phone based booking api (#17635)
* chore: save progress

* feat: support phone based booking using API v2

* chore: change name of the variable

* fix: update event types and booking fields for improved validation and new properties

- Updated imports in input and output event types services to use the correct library version.
- Added new `avatarUrl` and `successRedirectUrl` properties to the Swagger documentation for user and booking schemas.
- Enhanced booking fields validation by changing the `required` property to a boolean type.
- Improved descriptions and examples in the OpenAPI specifications for better clarity.
- Refactored booking fields input and output classes to include new properties and ensure proper validation.

* fix: booking with phone number

* test: add event type update test

* test: add test for creating booking

* chore: update unit test

* fix: tests

* fix: add turbo

* chore: remove emial

* refactor: make email optional and move it to service

* fix: test

* chore: bump platform-libraries

* fix: e2e test

---------

Co-authored-by: supalarry <laurisskraucis@gmail.com>
2025-01-08 21:16:10 +05:30
Anwar Sadath 20a5775f31 fix: Description not rendered as html in select event types screen when installing an app (#18354) 2025-01-08 15:03:34 +00:00
Omar López b9b0a86b32 feat: Add auto payment methods for paid booking on Stripe (#18513) 2025-01-08 07:55:14 -07:00
Abhishek Singh ad93066cf6 feat-insihts-app (#18461) 2025-01-08 14:24:20 +00:00
Benny Joo e6d76b630c chore: Revert "chore: app router - /team, /org, /[user] booking pages (excl. embeds) (#18186) (#18526) 2025-01-08 11:19:45 -03:00
Eunjae Lee b941b716d5 fix: add index to AssignmentReason (#18520) 2025-01-08 12:32:28 +00:00
Eunjae LeeandUdit Takkar 1ab9622416 feat: add DataTableWrapper (#18503)
* feat: data table wrapper

* feat: add DataTableWrapper

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-01-08 09:12:55 +00:00
Benny Joo 15156c2225 perf: use react svg cache from root level (#18506) 2025-01-08 09:29:50 +01:00
Benny JooandPeer Richelsen cc202ed847 chore: app router - /event-types pages (#18181)
* refactor event type web wrapper

* finish migration

* move event-types folder out of future

* remove vars

* remove pages router

* fix

* fix

* fix test

* remove test tag

* refactor

* remove completely

* add withoutSeo prop for event type web page

* remove HeadSeo usage from event types listing view

* make onboarding e2e test faster

* remove useIntercom

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-07 20:39:05 -05:00
Joe Au-Yeung 79d51a4989 chore: Add Salesforce tests to getContacts method (#18225) 2025-01-07 14:14:34 -07:00
Calcom BotandReplexica 53a846d10c feat: update translations via @replexica (#18496)
Co-authored-by: Replexica <support@replexica.com>
2025-01-07 20:53:16 +00:00
GitHub Actions 1619f2daf2 chore: release v4.8.14
Post release / release (push) Canceled after 0s
2025-01-07 20:06:08 +00:00
Alex van Andel 57bd0b3df3 fix: type + build errors (#18502) 2025-01-07 18:35:06 +01:00
Udit Takkar e359d13d9a Revert "fix: improve useInViewObserver hook to trigger when observer is alrea…" (#18504)
This reverts commit 22f92f1ee3.
2025-01-07 16:41:55 +00:00
Hariom Balhara 3b7cb542ed fix checklyt tests (#18501) 2025-01-07 12:58:39 +00:00
Alex van Andel fd7f6c32ae chore: Remove all instances of useIntercom (#18500) 2025-01-07 07:43:46 -05:00
Hariom Balhara 06d8b98b15 fix: 404 on the public form page for a sub-team form when the owner itself was removed from the org (#18495)
* wip

* fix: 404 for a form of a member that has been removed.

- Moved existing authorization check to isAuthorizedToViewFormOnOrgDomain function to handle form access control
- Add comprehensive test suite for org domain authorization scenarios
- Refactor getServerSideProps to use the new authorization function
- Improve code organization by separating domain-specific authorization logic

Test Coverage:
- Non-org domain access
- Org member's form access
- Sub-team form access within org
- Access denial for non-org members/teams
2025-01-07 12:13:19 +00:00
Benny Joo 0c69c5dfea remove MainLayout / MainLayoutAppDir (#18498) 2025-01-07 12:13:00 +00:00
Benny Joo 00f7d8be0d feat: bookings - render layout only once (#18490) 2025-01-07 11:37:17 +00:00
Hariom Balhara 2e9beb8513 fix: Make it easier to manage group options and also improve attribute options performance with 100s of options (#18486) 2025-01-07 11:16:52 +00:00
Omar López b6c6fa7365 Update repository.ts (#18482) 2025-01-07 11:10:52 +00:00
Benny Joo c623785ec2 chore: remove unused code from SideBar (#18487) 2025-01-07 10:56:09 +00:00
Alex van Andel 6a381cdc79 perf: Remove zod from edge runtime (#18494) 2025-01-07 10:47:48 +00:00
Benny Joo 9d4496133e feat: Prevent re-renders (moving SessionProvider to Root level for both app router / pages router) (#18493) 2025-01-07 11:46:08 +01:00
Benny Joo 1452672495 withEmbedSsr is missing in a embed route (#18483) 2025-01-07 07:28:55 -03:00
Lauris Skraucis 9159c591ff fix: v2 slots timeZone parameter (#18488)
* fix: v2 slots timeZone parameter

* test: v2 slots
2025-01-07 15:24:20 +05:30
Benny Joo 408aee5851 insights layout (#18489) 2025-01-07 09:02:52 +00:00
Vishnu 29bbada77a fix: cancel workflows on cancel booking (#17871)
* feat: cancel scheduled email from sendGrid while cancelling the booking

* fix: remove deleteScheduledSend in scheduledEmailReminder cron api

* fix: use cancelScheduledEmailSend

* chore: remove cancelling email workflow in deleteScheduledEmailReminder

* refactor: bring back deleteScheduleSend

* fix: get only past reminders
2025-01-07 00:06:57 -05:00
PraashandHariom 6178092878 fix: Cannot read properties of undefined (reading 'timeZone') (#18107)
Co-authored-by: Hariom <hariombalhara@gmail.com>
2025-01-07 04:17:17 +00:00
Hariom BalharaandOmar López 6f531d0be5 feat: Single domain setup when only one org in the system (#18383)
Co-authored-by: Omar López <zomars@me.com>
2025-01-07 09:28:44 +05:30
GitHub Actions d7b723c914 chore: release v4.8.13
Post release / release (push) Canceled after 0s
2025-01-06 21:59:03 +00:00
Anik Dhabal BabuandAlex van Andel aad3988d60 fix: Zoho Calendar is allowing bookings during busy schedules (#18473)
* fix: zoho calendar allowing to book busy schedule

* Improved more readable version

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-01-06 21:00:05 +05:30
c8172ab790 refactor: v2 default booking fields (#18287)
* feat: allow title,notes,reschedule reason inputs

* refactor: v2 event type default booking fields as in web app

* wip: input validation

* input field validation

* fix: tests

* chore: bump libraries

* remove change in docs

* fix input type

* chore: ensure additional notes at the end

* fixup! Merge branch 'main' into lauris/cal-4932-platform-refactor-default-booking-fields

---------

Co-authored-by: Morgan Vernay <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2025-01-06 16:49:57 +02:00
657f9dfd41 chore: ignore oAuthClientId for Booker Embed bookings (#18314)
* chore: ignore oAuthClientId for Booker Embed bookings

* remove logs

* chore: isEmbed header and emails

* fixup! chore: isEmbed header and emails

* fixup! fixup! chore: isEmbed header and emails

* fixup! fixup! fixup! chore: isEmbed header and emails

* fixup! fixup! fixup! fixup! chore: isEmbed header and emails

* fixup! fixup! fixup! fixup! fixup! chore: isEmbed header and emails

---------

Co-authored-by: Ryukemeister <sahalrajiv6900@gmail.com>
Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
2025-01-06 16:21:38 +02:00
Calcom BotandReplexica c48b209c04 feat: update translations via @replexica (#18472)
* chore: sync with main

* feat: update translations via @replexica

---------

Co-authored-by: Replexica <support@replexica.com>
2025-01-06 11:13:03 -03:00
Hariom BalharaandPeer Richelsen b9a460d8b4 chore: Bump version for embed (#18285)
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-06 12:42:13 +00:00
a7727b5ca6 feat: shorten sms links using dub (#17925)
* feat: add getshortenLinks function

* feat: use shortenLinks in SMS Worflows

* chore: use getShortenLink and cleanup getShortenLinks

* fix: Duplicate keys error

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-01-06 12:39:54 +00:00
Lauris Skraucis 9b661b75f1 docs: OAuth client redirectUri with wildcard character (#18267) 2025-01-06 09:39:31 -03:00
Kartik SainiandPeer Richelsen 487cc0751d feat: add cancel and reschedule reason variables in workflows (#18305)
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-06 11:56:06 +00:00
Akash Jayan f7f36978e1 fix: initialize useCustomTemplate state based on payloadTemplate prop… (#18257) 2025-01-06 12:37:23 +01:00
Amit SharmaandPeer Richelsen c1dbb7cffd feat: refund policies for payment apps (#18428)
* feat: refund policies for payment apps

* tests for payment refund

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-01-06 11:36:37 +00:00
Morgan e722e75a6f docs: cal-api-version header example for bookings controller v2 (#18271)
* docs: api v2 cal-api-version header example for bookings controller

* fixup! docs: api v2 cal-api-version header example for bookings controller
2025-01-06 11:36:03 +00:00
Amit SharmaandAnik Dhabal Babu 455572b5f4 feat: Info lost when navigating without warning routing form (#18386)
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-01-06 12:19:58 +01:00
Alex van Andel 2fe4462f62 perf: Use improved checkIfAvailable and remove dupe code (#18463) 2025-01-06 09:53:39 +00:00
Amit Sharma f9dc788007 fix: It's hard to click on the last available Event Duration (#18462) 2025-01-04 15:07:36 +00:00
René Aaron 6e293d2985 fix: improve qr readability of alby payment integration (#18266)
* fix: optimize qr for better readability

* fix: optimize readability
2025-01-04 12:18:31 +01:00
Benny Joo 00334c5610 chore: app router - /signup page (#18151)
* app router - /signup page

* add to config.matcher

* fix
2025-01-03 22:27:03 +00:00
Benny JooandHariom Balhara 2f9c8cb441 chore: app router - /team, /org, /[user] booking pages (excl. embeds) (#18186)
* update env vars

* update middleware

* remove pages router and move pages to /app

* move to /team

* update imports

* fix

* remove pages router and move org pages to /app

* wip

* fix orgSlug/user pages

* fix orgSlug/user/type pages

* remove generateMetadata from embed pages

* fix

* remove pages router for /user pages

* generateMetadata is not needed in embed pages

* remove future/org

* no layout in [user] page

* simplify

* fix

* fix OG image for [user]

* fix OG images for org/user and team/slug

* fix OG images for booking page

* fix all metadata

* use isBrandingHidden

* remove BookerSeo and its usages

* rename excludeAppNameFromTitle -> hideBranding

* remove logic for meeting type in HeadSeo

* remove BookerSeo instances from team-view and users-public-view

* create generateMeetingMetadata util and use it to reduce duplicate code

* remove BookerSeo imports

* fix spacing

* remove constructMeetingImage mock from head-seo.test

* fetch avatarUrl using user id for user page metadata

* fix test

* remove unused test cases

* index and follow must be true by default

* invert noindex/nofollow flags

* remove HeadSeo for already migrated pages and refactor prepareMetadata

* fix organization-settings.e2e.ts

* fix order

* enable parallel test execution for dynamic-booking e2e test

* fix

* + could be %2B in app router

* refactor handling logic for embeds in app router

* fix isEmbed

* fix embed-core

* remove dead code

* move embed pages back to /future

* add back embed pages in pages router

* revert some changes

* fix import type checks

* simplify

* fix

* feat: Implement generateBookingPageMetadata function for improved SEO and metadata handling across user and event pages (#18440)

- Added a new utility function `generateBookingPageMetadata` to streamline the generation of metadata for booking and user profile pages.
- Updated multiple page components to utilize the new function, enhancing SEO indexing and metadata consistency.
- Removed redundant code related to previous metadata generation methods, improving code clarity and maintainability.

* fix dirs

* Pr-review-fixes-app-router-team-pages (#18450)

* Remove unnecessary getPublicEvent call

* Remove unused variable

* Fix 404 for team page (#18451)

* Remove console log

---------

Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2025-01-03 22:26:30 +00:00
GitHub Actions 39173900b1 chore: release v4.8.12
Post release / release (push) Canceled after 0s
2025-01-03 21:53:06 +00:00
Syed Ali Shahbaz bd61e01a5d fix: Show managed event bookings for team admins/owners (#18434)
* add managed event bookings for team admins/owners

* remove unnecessary OR

* address change suggestion

* improve readability
2025-01-03 21:43:05 +00:00
Cao Hoang aa0b3a2778 fix: improve useInViewObserver hook to trigger when observer is already in view on mount (#18455) 2025-01-03 21:20:59 +00:00
Joe Au-Yeung 170feeae5e chore: Salesforce - Add additional logging and error checks (#18448) 2025-01-03 12:57:24 -05:00
Eunjae Lee a67b57b216 feat: server side sorting for insights routing (#18113)
* feat: server side sorting for insights routing

^ Conflicts:
^	packages/prisma/playground.ts

* fix download csv

* fix hooks locations
2025-01-03 10:58:01 +00:00
821a16648f fix: Timezone in Email Embed not working #15525 (#15537)
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: Hariom <hariombalhara@gmail.com>
2025-01-03 08:43:09 +00:00
Hariom Balhara 727f7df2c2 fix: Enhance SCIM payload handling and attribute creation (#18427)
* feat: Enhance SCIM user attribute handling and sync process

- Introduced a new PR_TODO.md file to track ongoing tasks and fixes.
- Updated `getAttributesFromScimPayload` to accept a directoryId and ignore core user attributes during syncing.
- Modified `handleUserEvents` to pass directoryId when syncing custom attributes.
- Improved attribute creation logic to handle unique options and added support for optional isGroup property in attribute options.
- Added utility function `getOptionsWithValidContains` to ensure valid sub-options in attribute options.
- Updated tests to reflect changes in attribute handling and ensure proper functionality.

This commit addresses issues with user attribute syncing and enhances the overall attribute management process.

* test: Add unit tests for getOptionsWithValidContains utility function

- Introduced a new test file for the getOptionsWithValidContains function.
- Added tests to verify the removal of duplicate options, initialization of empty contains arrays, filtering of non-existent sub-options, and handling of empty options arrays.
- Ensured comprehensive coverage of the utility's functionality to enhance reliability and maintainability.
2025-01-03 13:36:21 +05:30
Anik Dhabal Babu be5f7f83b5 fix: Zoho Bigin not pulling information from booking (#18445)
* fix: Zoho Bigin not pulling information from booking

* update

* missed

* fix contactcreation
2025-01-03 08:41:18 +05:30
amrit 02a49e2b4b fix: react incompatiblity with nextjs error (#18433) 2025-01-03 01:03:46 +00:00
Cao Hoang 22f92f1ee3 fix: improve useInViewObserver hook to trigger when observer is already in view on mount (#18446) 2025-01-02 23:58:40 +00:00
Udit Takkar c7a797c0e0 fix: get bookings ordering (#18439)
* fix: get bookings ordering

* chore: update query

* chore: add log for debuggin on prod

* chore
2025-01-02 23:41:30 +00:00
Calcom BotandReplexica 447436dfff feat: update translations via @replexica (#18438)
* chore: sync with main

* feat: update translations via @replexica

---------

Co-authored-by: Replexica <support@replexica.com>
2025-01-02 22:23:30 +00:00
Eunjae LeeandUdit Takkar c415b2d7f5 feat: apply full width automatically for DataTable (#18357)
* feat: apply full width automatically for DataTable

* change implementation

* load all columns of insights routing table at the same time

* update team member list

* sticky columns for >= sm

* fix type error

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-01-02 14:32:39 +00:00
Lauris Skraucis c10c87c98e fix: booker atom booking fields (#18441) 2025-01-02 11:31:43 +00:00
Benny Joo 85f96f492d chore: migrate /icons page to App Router (#18436)
* migrate icons page

* migrate main index page

* remove /icons page

* use i18n string

* fix imports

* add icons_showcase i18n string

* add /app dir to tailwind preset config

* use classname

* do not migrate main index page
2025-01-02 15:18:19 +05:30
Morgan b1350d0764 fix: atoms globals.css invalid class format (#18295) 2025-01-02 09:32:50 +00:00
Hariom BalharaandUdit Takkar bac2d1f6f0 feat: Add dry run mode functionality and message display in booking process (#18429)
- Introduced a new `DryRunMessage` component to inform users when in dry run mode.
- Implemented utility function `isBookingDryRun` to check for dry run status based on URL search parameters.
- Updated the `Booker` component to conditionally render the dry run message.
- Adjusted booking mutation input mapping to reuse the utility

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-01-01 11:40:53 +00:00
Anik Dhabal Babu fec504496a fix: Add to google leads to a 403 page (#18430) 2024-12-31 14:11:42 +00:00
Alex van Andel 890fc92148 fix: Some recently discovered type errors breaking build (not sure why undetected before) (#18432) 2024-12-31 13:50:43 +00:00
Benny Joo 557bd8bf25 chore: Migrate /403 and /500 pages to App Router (#18424)
* global-error is not needed

* remove /403 and /500 pages from pages router

* add 403 and 500 pages in App Router

* add i18n strings

* fix i18n string

* fix styling
2024-12-31 11:43:15 +05:30
Cao HoangandUdit Takkar d8027fe248 Fix duplicated data returned by Prisma query in team availability view (#18416)
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-12-30 21:15:27 +00:00
Anik Dhabal Babu 116c765c36 fix: Error changing location for meeting (#18401) 2024-12-30 14:59:07 +00:00
GitHub Actions c6c3e228a3 chore: release v4.8.11
Post release / release (push) Canceled after 0s
2024-12-30 13:56:52 +00:00
Vijay 7584645b8c fix: flaky OOO tests without time dependency (#18412)
* fix flaky OOO tests without time dependency

* chore
2024-12-30 14:13:53 +05:30
Benny Joo 32ff7ffed1 chore: reduce test time for onboarding e2e test (#18403) 2024-12-30 13:50:58 +05:30
55113f20fe fix: add typeform logo and fix alt text in /apps/typeform/how-to-use (#18393)
* :truck:: add typeform logo and fix alt text

* trying to fix the test

* Update testUtils.ts

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: unknown <adhabal2002@gmail.com>
2024-12-30 11:11:32 +05:30
Anik Dhabal Babu 0a293308e7 Revert "update OOO e2e tests to remove flakiness (#18367)" (#18411)
This reverts commit e6ef4e1988.
2024-12-29 15:14:20 +00:00
Nizzy e558daaa0b fix: embed showing chat (#18404)
* fix: embed showing chat

* change url check to starts with

* hashmap through pathname
2024-12-29 03:07:24 +00:00
devin-ai-integration[bot] 3f0a6718bc fix: reduce mobile navigation bottom margin from 0.625rem to 0.25rem (#18398) 2024-12-28 12:30:14 +01:00
GitHub Actions 8ffebdba44 chore: release v4.8.10
Post release / release (push) Canceled after 0s
2024-12-27 21:07:33 +00:00
Udit TakkarandBailey Pumfleet cc1101ac43 refactor: email handler (#18391)
Co-authored-by: Bailey Pumfleet <bailey@pumfleet.co.uk>
2024-12-27 21:02:05 +00:00
Anik Dhabal BabuandUdit Takkar 7a80a5f929 fix: localized date (#18388)
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-12-27 20:59:53 +00:00
NizzyandUdit Takkar a27e1498b8 fix: removed plain chat from app.cal.com/video (#18385)
* fix: removed plain chat from app.cal.com/video

* take user session and open plain out of use effect

* move undefined check and screen size check above useeffect

* turned restrcited paths into env var

* undefeined window below hooks

* chore: add window check

* fix: infinite re rendering

* remove console.log

---------

Co-authored-by: Udit Takkar <udit222001@gmail.com>
2024-12-27 18:42:36 +00:00
Calcom BotandReplexica a697857fa0 feat: update translations via @replexica (#18389)
* chore: sync with main

* feat: update translations via @replexica

---------

Co-authored-by: Replexica <support@replexica.com>
2024-12-27 17:33:26 +00:00
Udit Takkar e2f45bdf5a perf: improve checkIsAvailable in getAvailable slots (#18352)
* refactor: Update booking query to use userId and optimize availability check logic

- Changed the booking query to use userId instead of nested user object for filtering active bookings.
- Refactored availability check logic to improve readability and performance by using valueOf() for time comparisons and consolidating multiple checks into a single return statement.

* fix: update tests

* chore: use toDate()

* tests: add checkavailable unit tests
2024-12-27 16:01:54 +00:00
Hariom Balhara d2930bc243 fix: Handle more dry-run cases (#18286) 2024-12-27 16:23:14 +01:00
GitHub Actions b0b93f612e chore: release v4.8.9
Post release / release (push) Canceled after 0s
2024-12-27 11:17:18 +00:00
Udit Takkar 558c8be740 perf: getAvailableSlots improvements (#18382) 2024-12-27 11:09:49 +00:00
Alex van Andel 1aee1742d5 chore: rely less on autoinfer, be able to use initial data types in consumers (#18359) 2024-12-27 16:23:49 +05:30
Hariom BalharaandUdit Takkar ab942ed4cd Fix routing form field input loosing focus on typing (#18381)
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-12-27 14:30:10 +05:30
Hariom Balhara b5bec79354 perf: /router endpoint perf improvement (#18366) 2024-12-27 08:56:52 +00:00
Nizzy b48d0e1f48 remove yarnlock (#18377) 2024-12-27 00:44:21 -05:00
GitHub Actions 4a38b4dc89 chore: release v4.8.8
Post release / release (push) Canceled after 0s
2024-12-26 19:31:22 +00:00
Syed Ali Shahbaz ff12e387b3 fix: update contact email for CalDAV (#18351) 2024-12-26 19:24:11 +00:00
Kartik Saini 6b5e144042 feat: add name and email url params when rescheduling past bookings (#18318)
* feat: add name and email as url params when rescheduling past bookings

* remove logs

* pass booking seat name and email as url params
2024-12-26 19:23:28 +00:00
Anwar Sadath cd7b93a51e fix: Last used label in button shown in 2-factor code and backup screen (#18341) 2024-12-26 19:20:11 +00:00
Anik Dhabal Babu a76366cbcb fix: Recurring meeting creates increasing number of Zoom events (#18360) 2024-12-26 19:19:24 +00:00
Anwar Sadath 860c04bbda fix: discrepancy in description hyperlinks and calendar invite (#18365) 2024-12-26 19:18:54 +00:00
+6 225313e391 feat: Plain chat (#18284)
* plain custom desin

* No display on card

* dynamic plain chat component and hmac hash

* re-route users to plain.com chat instead of intercom chat when going to /support

* provider errors

* yarn lock fix

* plain chat removed unneeded hmac

* fix ts error

* error handling improved

* remove intercome provider from app-dir

* Create getting-started.mdx (#18342)

* Delete help directory (#18343)

* chore: moved docs/help to /help (#18345)

* chore: Delete unused guides directory (#18346)

* feat: booking filters (#18303)

Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>

* chore: Remove `HeadSeo` components where no longer needed + improve app router metadata logic (#18348)

* remove HeadSeo for already migrated pages and refactor prepareMetadata

* create _generateMetadataWithoutImage and refactor _generateMetadata

* chore: app router - /bookings status page (#18183)

* chore: app router - /bookings page

* remove env vars

* fix

* Update middleware.ts

* revert unneeded change

* refactor for the better

* fix

* cache i18n instances (#18309)

* feat: virtual queues tab in insights (#18260)

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: sean-brydon <sean@cal.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Omar López <zomars@me.com>

* feat: update translations via @replexica (#18361)

Co-authored-by: Replexica <support@replexica.com>

* update OOO e2e tests to remove flakiness (#18367)

* fix: metadata is overwritten for child managed eventType when updating parent (#18059)

* fix: metadata is overwirten

* Update

* type error

* Update

* fix test

* fix type error

* chore: added routing support link (#18369)

* Added routing form support link

* small change

* Type fix

---------

Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com>

* chore: refactor handling logic for embeds in app router (#18362)

* refactor handling logic for embeds in app router

* fix type checks

* add test for withEmbedSsrAppDir

* fix

* review changes

* yarn lock

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Calcom Bot <109866826+calcom-bot@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>
Co-authored-by: Benny Joo <sldisek783@gmail.com>
Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: sean-brydon <sean@cal.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
Co-authored-by: Omar López <zomars@me.com>
Co-authored-by: Replexica <support@replexica.com>
Co-authored-by: Vijay <vijayraghav22@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-12-26 19:07:08 +00:00
Benny Joo 3994929a51 chore: refactor handling logic for embeds in app router (#18362)
* refactor handling logic for embeds in app router

* fix type checks

* add test for withEmbedSsrAppDir

* fix
2024-12-26 10:39:07 +01:00
Peer RichelsenandJoe Au-Yeung ae38027d76 chore: added routing support link (#18369)
* Added routing form support link

* small change

* Type fix

---------

Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com>
2024-12-24 17:19:37 +00:00
Anik Dhabal Babu 9036080fcf fix: metadata is overwritten for child managed eventType when updating parent (#18059)
* fix: metadata is overwirten

* Update

* type error

* Update

* fix test

* fix type error
2024-12-24 21:21:43 +05:30
Vijay e6ef4e1988 update OOO e2e tests to remove flakiness (#18367) 2024-12-24 13:49:49 +00:00
Calcom BotandReplexica 3c2619a7a3 feat: update translations via @replexica (#18361)
Co-authored-by: Replexica <support@replexica.com>
2024-12-23 22:42:02 +00:00
cfb09a1b21 feat: virtual queues tab in insights (#18260)
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: sean-brydon <sean@cal.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Omar López <zomars@me.com>
2024-12-23 19:16:38 +00:00
Benny Joo 5fe4e09975 cache i18n instances (#18309) 2024-12-23 17:14:52 +00:00
Benny Joo 542799e2cf chore: app router - /bookings status page (#18183)
* chore: app router - /bookings page

* remove env vars

* fix

* Update middleware.ts

* revert unneeded change

* refactor for the better

* fix
2024-12-23 10:12:22 +01:00
Benny Joo 3eda7858c0 chore: Remove HeadSeo components where no longer needed + improve app router metadata logic (#18348)
* remove HeadSeo for already migrated pages and refactor prepareMetadata

* create _generateMetadataWithoutImage and refactor _generateMetadata
2024-12-23 10:02:59 +01:00
Udit TakkarandSyed Ali Shahbaz b59bf7d1ee feat: booking filters (#18303)
Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>
2024-12-23 14:06:29 +05:30
Peer Richelsen 0dadeac352 chore: Delete unused guides directory (#18346) 2024-12-22 21:44:43 +01:00
Peer Richelsen 5eb7a4d56e chore: moved docs/help to /help (#18345) 2024-12-22 21:43:53 +01:00
Calcom Bot 43fa944e2f Delete help directory (#18343) 2024-12-22 21:36:22 +01:00
Peer Richelsen 1866b2845c Create getting-started.mdx (#18342) 2024-12-22 21:35:30 +01:00
Anik Dhabal Babu 2cfc63e6e3 fix: Reschedule email for RR event shows wrong timezone to attendee (#18262)
Post release / release (push) Canceled after 0s
2024-12-20 14:02:03 -06:00
GitHub Actions 4f66f3d2c6 chore: release v4.8.7 2024-12-20 20:01:15 +00:00
Morgan ca3e7bd97d fix: hotfix hide hidden booking fields in event-types GET / (#18306) 2024-12-20 19:37:32 +00:00
Benny Joo cafa3f9cf3 fix: make sure to call refresh for pages rendered by app router (#18304) 2024-12-20 18:44:35 +00:00
Benny Joo e04faffcbb chore: add cache to static pages in app router (#18278)
* add cache

* fix

* refactor
2024-12-20 13:37:20 -05:00
Peer Richelsen 6f1556a2fd feat: added chatbase app (#18302) 2024-12-20 17:50:19 +00:00
mintlify[bot] d72a954896 Mintlify Docs Edits (#18301)
Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
2024-12-20 17:10:39 +00:00
amrit abeb20373c fix portugese (pt-BR) password validation from a required eight to seven. (#18273) 2024-12-20 17:33:46 +05:30
MorganandRajiv Sahal 422ef2f5b8 chore: add cal.com logo to platform booker embed (#18269)
* chore: add cal.com logo to platform booker embed

* fixup! chore: add cal.com logo to platform booker embed

---------

Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
2024-12-20 12:55:25 +02:00
Omar López ec920eb2a8 fix: prevents cron to be clogged with calendars with missing credentialId (#18281) 2024-12-19 23:53:51 +00:00
GitHub Actions 795eecf300 chore: release v4.8.6
Post release / release (push) Canceled after 0s
2024-12-19 22:42:27 +00:00
Calcom BotandReplexica 8ae3d6d55b feat: update translations via @replexica (#18279)
Co-authored-by: Replexica <support@replexica.com>
2024-12-19 20:51:57 +00:00
85070574da feat: Support event level conflict checking (#18052)
Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Morgan Vernay <morgan@cal.com>
Co-authored-by: Omar López <zomars@me.com>
2024-12-19 19:34:24 +00:00
Morgan d1c2872f6e fix: platform booker timezone select (#18277) 2024-12-19 17:08:34 +00:00
Morgan 42d78f8099 fix: platform booker icons and styling (#18276) 2024-12-19 16:45:05 +00:00
Lauris Skraucis f0d7a757d4 fix: Booker atom default booking fields (#18275)
* refactor: rename transformBookingFieldsApiToInternal to transformBookingFieldsApiRequestToInternal

* refactor: default booking fields can required or not required

* fix: render system fields in booker

* fix: hidden property of booking fields

* fix: default field labels and placeholders

* chore: bump platform libraries

* fix: tests

* fix: e2e tests
2024-12-19 16:30:14 +00:00
GitHub Actions 0b2f09ab7d chore: release v4.8.5
Post release / release (push) Canceled after 0s
2024-12-19 15:10:13 +00:00
Benny Joo 355aaa7010 fix: include app directory in rewrites generation logic + migrate /reschedule pages to App Router (#18261)
* chore: app router - /reschedule pages (#18150)

* app router - /reschedule pages

* add to config.matcher

* generateMetdata is not needed

* include app directory in rewrites generation logic

* make it more readable

* make code more elegant

* fix

* fix

* fix

* fix

* test and refactor
2024-12-19 06:22:19 -07:00
Rajiv Sahal c27b73aa9a fix: event type atom availability (#18263) 2024-12-19 16:38:05 +05:30
Somay Chauhan a622c7b624 fix: seats option not working for booker atom (#18265) 2024-12-19 08:07:40 +00:00
GitHub Actions 19bd3e5849 chore: release v4.8.4
Post release / release (push) Canceled after 0s
2024-12-18 23:21:28 +00:00
Benny Joo 7827028e0a Revert "chore: app router - /reschedule pages (#18150)" (#18258)
This reverts commit a7f24e777b.
2024-12-18 22:48:03 +00:00
Joe Au-Yeung ebc3ced687 chore: CRM logging, add booking uid (#18256)
* Add more logging

* Add conditional
2024-12-18 21:23:04 +01:00
Nizzy b56824e626 removed posthog identifier (#18253) 2024-12-18 15:03:17 -05:00
Benny Joo 460e511459 chore: app router - /booking pages (#18182)
* chore: app router - /booking pages

* move pages to /app

* add to config matcher
2024-12-18 14:09:34 -05:00
Benny Joo b4fd6f3442 chore: bring back removed onboarding steps (#18254)
* add connected-calendar and connected-video steps back

* adapt test

* fix name
2024-12-18 20:05:17 +01:00
Benny Joo 0a7a0e3687 chore: app router - /teams single page (#18184)
* chore: app router - /teams single page

* fix type check
2024-12-18 17:51:01 +00:00
Calcom BotandReplexica 595fffbea0 feat: update translations via @replexica (#18249)
* chore: sync with main

* feat: update translations via @replexica

---------

Co-authored-by: Replexica <support@replexica.com>
2024-12-18 17:44:50 +00:00
GitHub Actions 218c9152da chore: release v4.8.3
Post release / release (push) Canceled after 0s
2024-12-18 17:22:22 +00:00
Omar López 77fe23da49 fix: skip failed cache subscriptions from retrying (#18252) 2024-12-18 17:16:59 +00:00
sean-brydon a583db3fd4 refactor and fix bulk attribute handling (#18231) 2024-12-18 16:31:03 +00:00
cb1f803d0a feat: ooo calibration (#17864)
* first version of ooo calibration

* decrease precision when checking for full day event

Co-authored-by: Alex van Andel <me@alexvanandel.com>

* improve variable naming

* don't include hosts created after OOO

* fix failing tests

* fix all tests

* add test for ooo calibration

* first implementation to fix full day busy event reaching the current month

* allow mutiple day events

* make getAvailabilityWithTimeZones optional

* fix type error

* fix type errors

* fix tests

* fix type error

* fix test

* code clean up

* remove time adjustment from map

* code clean up

* fix tests

* getAllCalendars -> this.getAllCalendars

* fix typo

* extract mergeOverlappingRanges

* code improvements from feedback

* fix getCalIdsWithTimeZone

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: Benny Joo <sldisek783@gmail.com>
2024-12-18 16:26:59 +00:00
Peer Richelsen 479d6b5961 Update i18n.json 2024-12-18 16:28:22 +01:00
Alex van Andel 4ab3ec73c0 chore: Set the stage for a primary key with value uuid() (#18245)
* chore: Set the stage for a primary key  with value uuid()

* fix: Test and ensure it validates the id value is set and defined

* Add unique index manually, prisma doesn't support this

* revert unique
2024-12-18 15:14:04 +00:00
Joe Au-Yeung 8dda418127 feat: Salesforce skip ownership check if attendee email is a free domain (#17916)
* Add email domain array

* Create numbered email domain object

* Check email domain

* Rename function

* Add tests

* Frontend enable skip ownership check if free email domain

* Backend ignore adding ownership to return records if free email domain check is enabled

* feat: Only require confirmation for free email domains (#17917)

* Add requiresConfirmationForFreeEmail to db

* Add option to event type settings

* Get requiresConfirmationForFreeEmail for event type page

* Include requiresConfirmationForFreeEmail in fetching event type

* Pass bookerEmail to `getRequiresConfirmationFlags`

* Add free email domain check to `determineRequiresConfirmation`

* Add `requiresConfirmationForFreeEmail` to types

* Add severity to Watchlist table

* Add migration for watchlist severity

* Add `getEmailDomainInWatchlist` method to watchlist repository

* Use watchlist repository to check for free email domain

* Mock watchlist repository in test

* Update test

* Rename method

* Add severity to blocked list

* Move check free email domain to async

* Type checks

* Adjust for promise returned

* Fix tests

* Fix

* Fix tests
2024-12-18 15:02:42 +00:00
Benny Joo a7f24e777b chore: app router - /reschedule pages (#18150)
* app router - /reschedule pages

* add to config.matcher

* generateMetdata is not needed
2024-12-18 14:54:15 +01:00
Benny Joo f78fca594a chore: app router - /getting-started page (#18185)
* remove env vars

* move pages to /app

* remove Head component

* remove pages router

* add to config matcher

* fix
2024-12-18 14:41:03 +01:00
Lauris Skraucis e6a7ae7da3 fix: platform decrease usage when cancelling booking (#18241)
* fix: decrement billing upon cancelled booking

* docs: explain billing in FAQ

* update docs
2024-12-18 14:50:31 +02:00
Lauris Skraucis ad5d92dff0 refactor: v2 calendars busy-times (#18244)
* refactor: make dateFrom and dateTo required

* refactor: make dateFrom and dateTo required

* refactor: useCalendarsBusyTimes enabled only if dateFrom & dateTo passed
2024-12-18 13:36:26 +01:00
Anik Dhabal Babu 8bf46ab8b6 fix: missing n8n app screenshot and add margin to the back button (#18240)
* fix: n8n app screenshot missing

* remove log
2024-12-18 12:35:26 +00:00
sean-brydon 34b0753f8d feat: match edit user sheet designs (#18243)
* edit sheet design changes

* remove attribute header
2024-12-18 11:50:19 +00:00
Calcom BotandReplexica 0bd7227150 feat: update translations via @replexica (#18234)
* chore: sync with main

* feat: update translations via @replexica

---------

Co-authored-by: Replexica <support@replexica.com>
2024-12-17 23:22:10 -05:00
Omar López 4d192ee328 fix: single rejection caused cache cron to fail (#18239) 2024-12-17 23:04:08 -05:00
63013d402e feat: Plain integration (#18130)
* revert: "fix: Request permissions to allow events to be created on shared Office365/Outlook calendars (#17760)"

This reverts commit 1680cba5a5.

* plain.com card

* detiled error handling for get customer

* working email and id

* hmac

* Revert "fix: correct line-breaks in calendar event description (#18077)"

This reverts commit 06494a6999.

* pr changes requet

* remove pan for now

* add-new-implementation-for-early-review

* Pushing fix for createHmac stringify

* added validation and user repository for email check

* add apiRouteMiddleware which handles the error handling

* HMAC_SECRET_KEY -> PLAIN_HMAC_SECRET_KEY

* Use the right error

* Convey right error to consumer

* Fixup apiRouteMiddleware to handle handler

* Don't export handler, only export POST

* changed to app directory

* working unkown user card

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Omar López <zomars@me.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-12-17 20:24:07 -05:00
Lauris Skraucis 6b3ccbc61a fix: v2 isSystemAdmin (#18162)
* refactor: ApiAuthStrategy return isSystemAdmin and define returned type

* refactor: use ApiAuthGuardUser instead of GetUserReturnType

* regenerate docs
2024-12-17 19:32:01 +00:00
Lauris SkraucisandSomay Chauhan 2af5cba0d7 feat: v2 teams event types (#18085)
* feat: v2 teams event-types endpoints

* refactor: rely on teams event types service and repository

* finish mergin main into this branch

* test: teams event types

* refactor: move teams event types output from org to teams folder

* refactor: move teams event types output from org to teams folder

* chore: finish merge main

* refactor: logger name and unused import

* chore: finish main merge

---------

Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com>
2024-12-17 20:25:42 +01:00
Omar LópezandKeith Williams ae7bbaf414 fix: calendar cache date ranges (#18237)
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-12-17 19:20:19 +00:00
Hariom Balhara 4df4383e1e fixes:CAL-4905 (#18222) 2024-12-17 22:51:42 +05:30
1003 changed files with 39307 additions and 8162 deletions
+15 -8
View File
@@ -107,6 +107,15 @@ NEXT_PUBLIC_POSTHOG_KEY=
NEXT_PUBLIC_POSTHOG_HOST=
# plain.com config
PLAIN_API_KEY=
PLAIN_API_URL=https://api.plain.com/v1
PLAIN_HMAC_SECRET_KEY=
PLAIN_CHAT_ID=
PLAIN_CHAT_HMAC_SECRET_KEY=
NEXT_PUBLIC_PLAIN_CHAT_EXCLUDED_PATHS=
# Zendesk Config
NEXT_PUBLIC_ZENDESK_KEY=
@@ -233,6 +242,7 @@ E2E_TEST_MAILHOG_ENABLED=
# Cloudflare Turnstile
NEXT_PUBLIC_CLOUDFLARE_SITEKEY=
NEXT_PUBLIC_CLOUDFLARE_USE_TURNSTILE_IN_BOOKER=
CLOUDFLARE_TURNSTILE_SECRET=
# Set the following value to true if you wish to enable Team Impersonation
@@ -346,8 +356,6 @@ E2E_TEST_OIDC_USER_PASSWORD=
# provide a value between 0 and 100 to ensure the percentage of traffic
# redirected from the legacy to the future pages
AB_TEST_BUCKET_PROBABILITY=50
# whether we redirect to the future/event-types from event-types or not
APP_ROUTER_EVENT_TYPES_ENABLED=0
APP_ROUTER_APPS_INSTALLED_CATEGORY_ENABLED=0
APP_ROUTER_APPS_SLUG_ENABLED=0
APP_ROUTER_APPS_SLUG_SETUP_ENABLED=0
@@ -355,18 +363,12 @@ APP_ROUTER_APPS_SLUG_SETUP_ENABLED=0
APP_ROUTER_APPS_CATEGORIES_ENABLED=0
# whether we redirect to the future/apps/categories/[category] from /apps/categories/[category] or not
APP_ROUTER_APPS_CATEGORIES_CATEGORY_ENABLED=0
APP_ROUTER_BOOKING_ENABLED=0
APP_ROUTER_BOOKINGS_STATUS_ENABLED=0
APP_ROUTER_GETTING_STARTED_STEP_ENABLED=0
APP_ROUTER_APPS_ENABLED=0
APP_ROUTER_TEAM_ENABLED=0
APP_ROUTER_TEAMS_ENABLED=0
APP_ROUTER_AUTH_FORGOT_PASSWORD_ENABLED=0
APP_ROUTER_AUTH_LOGIN_ENABLED=0
APP_ROUTER_AUTH_LOGOUT_ENABLED=0
APP_ROUTER_AUTH_NEW_ENABLED=0
APP_ROUTER_AUTH_SAML_ENABLED=0
APP_ROUTER_AUTH_ERROR_ENABLED=0
APP_ROUTER_AUTH_PLATFORM_ENABLED=0
APP_ROUTER_AUTH_OAUTH2_ENABLED=0
@@ -411,3 +413,8 @@ REPLEXICA_API_KEY=
# Comma-separated list of DSyncData.directoryId to log SCIM API requests for. It can be enabled temporarily for debugging the requests being sent to SCIM server.
DIRECTORY_IDS_TO_LOG=
# Set this when Cal.com is used to serve only one organization's booking pages
# Read more about it in the README.md
NEXT_PUBLIC_SINGLE_ORG_SLUG=
@@ -1,39 +0,0 @@
# .github/workflows/chromatic.yml
# Workflow name
name: "Chromatic"
# Event for the workflow
on:
pull_request_target: # So we can test on forks
branches:
- main
paths:
- apps/storybook/**
- packages/ui/**
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
# List of jobs
jobs:
chromatic-deployment:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }} # So we can test on forks
fetch-depth: 0
- name: Install dependencies
run: yarn
# 👇 Adds Chromatic as a step in the workflow
- name: Publish to Chromatic
uses: chromaui/action@v1
# Options required to the GitHub Chromatic Action
with:
# 👇 Chromatic projectToken, refer to the manage page to obtain it.
projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
workingDir: "apps/storybook"
buildScriptName: "build"
+2 -12
View File
@@ -12,16 +12,6 @@ jobs:
- uses: actions/checkout@v4
- uses: ./.github/actions/dangerous-git-checkout
- uses: ./.github/actions/yarn-install
- name: Run Linting with Reports
run: yarn lint:report
- name: Run Lint
run: yarn lint
continue-on-error: true
- name: Merge lint reports
run: jq -s '[.[]]|flatten' lint-results/*.json &> lint-results/eslint_report.json
- name: Upload ESLint report
if: ${{ always() }}
uses: actions/upload-artifact@v4
with:
name: lint-results
path: lint-results
@@ -1,5 +1,5 @@
diff --git a/index.cjs b/index.cjs
index c83f700ae9998cd87b4c2d66ecbb2ad3d7b4603c..76a2200b57f0b9243e2c61464d578b67746ad5a4 100644
index c83f700..da6fc7e 100644
--- a/index.cjs
+++ b/index.cjs
@@ -13,8 +13,8 @@ function withMetadataArgument(func, _arguments) {
@@ -12,4 +12,4 @@ index c83f700ae9998cd87b4c2d66ecbb2ad3d7b4603c..76a2200b57f0b9243e2c61464d578b67
+// exports['default'] = min.parsePhoneNumberFromString
// `parsePhoneNumberFromString()` named export is now considered legacy:
// it has been promoted to a default export due to being too verbose.
// it has been promoted to a default export due to being too verbose.
View File
+6
View File
@@ -0,0 +1,6 @@
undecided:
- "@calcom/app-store-cli"
- "@calcom/platform-constants"
- "@calcom/platform-enums"
- "@calcom/platform-types"
- "@calcom/platform-utils"
+6
View File
@@ -0,0 +1,6 @@
undecided:
- "@calcom/app-store-cli"
- "@calcom/platform-constants"
- "@calcom/platform-enums"
- "@calcom/platform-types"
- "@calcom/platform-utils"
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"
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"
+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"
+3
View File
@@ -0,0 +1,3 @@
undecided:
- calcom-monorepo
- "@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-monorepo
+2
View File
@@ -0,0 +1,2 @@
undecided:
- "@calcom/prisma"
+7
View File
@@ -0,0 +1,7 @@
undecided:
- "@calcom/app-store-cli"
- "@calcom/platform-constants"
- "@calcom/platform-enums"
- "@calcom/platform-types"
- "@calcom/platform-utils"
- "@calcom/prisma"
+3
View File
@@ -0,0 +1,3 @@
undecided:
- calcom-monorepo
- "@calcom/prisma"
+7
View File
@@ -0,0 +1,7 @@
undecided:
- "@calcom/app-store-cli"
- "@calcom/platform-constants"
- "@calcom/platform-enums"
- "@calcom/platform-types"
- "@calcom/platform-utils"
- "@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-monorepo
+3
View File
@@ -0,0 +1,3 @@
undecided:
- calcom-monorepo
- "@calcom/prisma"
View File
View File
+9
View File
@@ -485,6 +485,15 @@ 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`.
Note: It causes root to serve the dashboard and not the organization profile page which shows all bookable users in the organization.
## Integrations
### Obtaining the Google API Credentials
+5 -5
View File
@@ -11,15 +11,15 @@ test.describe("Org", () => {
await expectPageToBeRenderedWithEmbedSsr(page);
});
test("Org User(Peer) Page should be embeddable", async ({ page }) => {
const response = await page.goto("https://i.cal.com/peer/embed");
test("Org User(Rick) Page should be embeddable", async ({ page }) => {
const response = await page.goto("https://i.cal.com/team-rick/embed");
expect(response?.status()).toBe(200);
await expect(page.locator("text=Peer Richelsen")).toBeVisible();
await expect(page.locator("text=Rick in i.cal.com")).toBeVisible();
await expectPageToBeRenderedWithEmbedSsr(page);
});
test("Org User Event(peer/meet) Page should be embeddable", async ({ page }) => {
const response = await page.goto("https://i.cal.com/peer/meet/embed");
test("Org User Event(/team-rick/test-event) Page should be embeddable", async ({ page }) => {
const response = await page.goto("https://i.cal.com/team-rick/test-event/embed");
expect(response?.status()).toBe(200);
await expect(page.locator('[data-testid="decrementMonth"]')).toBeVisible();
await expect(page.locator('[data-testid="incrementMonth"]')).toBeVisible();
+147 -4
View File
@@ -1,9 +1,12 @@
import type { RatelimitResponse } from "@unkey/ratelimit";
import type { Request, Response } from "express";
import type { NextApiResponse, NextApiRequest } from "next";
import { createMocks } from "node-mocks-http";
import { describe, it, expect, vi } from "vitest";
import { handleAutoLock } from "@calcom/lib/autoLock";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { HttpError } from "@calcom/lib/http-error";
import { rateLimitApiKey } from "~/lib/helpers/rateLimitApiKey";
@@ -14,6 +17,10 @@ vi.mock("@calcom/lib/checkRateLimitAndThrowError", () => ({
checkRateLimitAndThrowError: vi.fn(),
}));
vi.mock("@calcom/lib/autoLock", () => ({
handleAutoLock: vi.fn(),
}));
describe("rateLimitApiKey middleware", () => {
it("should return 401 if no apiKey is provided", async () => {
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
@@ -55,15 +62,20 @@ describe("rateLimitApiKey middleware", () => {
query: { apiKey: "test-key" },
});
const rateLimiterResponse = {
const rateLimiterResponse: RatelimitResponse = {
limit: 100,
remaining: 99,
reset: Date.now(),
success: true,
};
(checkRateLimitAndThrowError as any).mockImplementationOnce(({ onRateLimiterResponse }) => {
onRateLimiterResponse(rateLimiterResponse);
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
(checkRateLimitAndThrowError as any).mockImplementationOnce(
({ onRateLimiterResponse }: { onRateLimiterResponse: (response: RatelimitResponse) => void }) => {
onRateLimiterResponse(rateLimiterResponse);
}
);
// @ts-expect-error weird typing between middleware and createMocks
await rateLimitApiKey(req, res, vi.fn() as any);
@@ -87,4 +99,135 @@ describe("rateLimitApiKey middleware", () => {
expect(res._getStatusCode()).toBe(429);
expect(res._getJSONData()).toEqual({ message: "Rate limit exceeded" });
});
it("should lock API key when rate limit is repeatedly exceeded", async () => {
const { req, res } = createMocks({
method: "GET",
query: { apiKey: "test-key" },
});
const rateLimiterResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 100,
reset: Date.now(),
};
// Mock rate limiter to trigger the onRateLimiterResponse callback
(checkRateLimitAndThrowError as any).mockImplementationOnce(
({ onRateLimiterResponse }: { onRateLimiterResponse: (response: RatelimitResponse) => void }) => {
onRateLimiterResponse(rateLimiterResponse);
}
);
// Mock handleAutoLock to indicate the key was locked
vi.mocked(handleAutoLock).mockResolvedValueOnce(true);
// @ts-expect-error weird typing between middleware and createMocks
await rateLimitApiKey(req, res, vi.fn() as any);
expect(handleAutoLock).toHaveBeenCalledWith({
identifier: "test-key",
identifierType: "apiKey",
rateLimitResponse: rateLimiterResponse,
});
expect(res._getStatusCode()).toBe(429);
expect(res._getJSONData()).toEqual({ message: "Too many requests" });
});
it("should handle API key not found error during auto-lock", async () => {
const { req, res } = createMocks({
method: "GET",
query: { apiKey: "test-key" },
});
const rateLimiterResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 100,
reset: Date.now(),
};
// Mock rate limiter to trigger the onRateLimiterResponse callback
(checkRateLimitAndThrowError as any).mockImplementationOnce(
({ onRateLimiterResponse }: { onRateLimiterResponse: (response: RatelimitResponse) => void }) => {
onRateLimiterResponse(rateLimiterResponse);
}
);
// Mock handleAutoLock to throw a "No user found" error
vi.mocked(handleAutoLock).mockRejectedValueOnce(new Error("No user found for this API key."));
// @ts-expect-error weird typing between middleware and createMocks
await rateLimitApiKey(req, res, vi.fn() as any);
expect(handleAutoLock).toHaveBeenCalledWith({
identifier: "test-key",
identifierType: "apiKey",
rateLimitResponse: rateLimiterResponse,
});
expect(res._getStatusCode()).toBe(401);
expect(res._getJSONData()).toEqual({ message: "No user found for this API key." });
});
it("should continue if auto-lock returns false (not locked)", async () => {
const { req, res } = createMocks({
method: "GET",
query: { apiKey: "test-key" },
});
const rateLimiterResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 100,
reset: Date.now(),
};
// Mock rate limiter to trigger the onRateLimiterResponse callback
(checkRateLimitAndThrowError as any).mockImplementationOnce(
({ onRateLimiterResponse }: { onRateLimiterResponse: (response: RatelimitResponse) => void }) => {
onRateLimiterResponse(rateLimiterResponse);
}
);
// Mock handleAutoLock to indicate the key was not locked
vi.mocked(handleAutoLock).mockResolvedValueOnce(false);
const next = vi.fn();
// @ts-expect-error weird typing between middleware and createMocks
await rateLimitApiKey(req, res, next);
expect(handleAutoLock).toHaveBeenCalledWith({
identifier: "test-key",
identifierType: "apiKey",
rateLimitResponse: rateLimiterResponse,
});
// Verify headers were set but request continued
expect(res.getHeader("X-RateLimit-Limit")).toBe(rateLimiterResponse.limit);
expect(next).toHaveBeenCalled();
});
it("should handle HttpError during rate limiting", async () => {
const { req, res } = createMocks({
method: "GET",
query: { apiKey: "test-key" },
});
// Mock checkRateLimitAndThrowError to throw HttpError
vi.mocked(checkRateLimitAndThrowError).mockRejectedValueOnce(
new HttpError({
statusCode: 429,
message: "Custom rate limit error",
})
);
// @ts-expect-error weird typing between middleware and createMocks
await rateLimitApiKey(req, res, vi.fn() as any);
expect(res._getStatusCode()).toBe(429);
expect(res._getJSONData()).toEqual({ message: "Custom rate limit error" });
});
});
+24 -2
View File
@@ -1,6 +1,8 @@
import type { NextMiddleware } from "next-api-middleware";
import { handleAutoLock } from "@calcom/lib/autoLock";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { HttpError } from "@calcom/lib/http-error";
export const rateLimitApiKey: NextMiddleware = async (req, res, next) => {
if (!req.query.apiKey) return res.status(401).json({ message: "No apiKey provided" });
@@ -10,14 +12,34 @@ export const rateLimitApiKey: NextMiddleware = async (req, res, next) => {
await checkRateLimitAndThrowError({
identifier: req.query.apiKey as string,
rateLimitingType: "api",
onRateLimiterResponse: (response) => {
onRateLimiterResponse: async (response) => {
res.setHeader("X-RateLimit-Limit", response.limit);
res.setHeader("X-RateLimit-Remaining", response.remaining);
res.setHeader("X-RateLimit-Reset", response.reset);
try {
const didLock = await handleAutoLock({
identifier: req.query.apiKey as string, // Casting as this is verified in another middleware
identifierType: "apiKey",
rateLimitResponse: response,
});
if (didLock) {
return res.status(429).json({ message: "Too many requests" });
}
} catch (error) {
if (error instanceof Error && error.message === "No user found for this API key.") {
return res.status(401).json({ message: error.message });
}
throw error;
}
},
});
} catch (error) {
res.status(429).json({ message: "Rate limit exceeded" });
if (error instanceof HttpError) {
return res.status(error.statusCode).json({ message: error.message });
}
return res.status(429).json({ message: "Rate limit exceeded" });
}
await next();
+2 -2
View File
@@ -1,9 +1,9 @@
import type { NextApiRequest } from "next";
import { checkIfEmailInWatchlistController } from "@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller";
import { checkIfEmailIsBlockedInWatchlistController } from "@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller";
export async function isLockedOrBlocked(req: NextApiRequest) {
const user = req.user;
if (!user?.email) return false;
return user.locked || (await checkIfEmailInWatchlistController(user.email));
return user.locked || (await checkIfEmailIsBlockedInWatchlistController(user.email));
}
@@ -9,11 +9,25 @@ export const schemaSelectedCalendarBaseBodyParams = SelectedCalendar;
export const schemaSelectedCalendarPublic = SelectedCalendar.omit({});
export const schemaSelectedCalendarBodyParams = schemaSelectedCalendarBaseBodyParams.partial({
userId: true,
});
export const schemaSelectedCalendarBodyParams = schemaSelectedCalendarBaseBodyParams
.partial({
userId: true,
})
.omit({
// id will be set by the database
id: true,
// No eventTypeId support in API v1
eventTypeId: true,
});
export const schemaSelectedCalendarUpdateBodyParams = schemaSelectedCalendarBaseBodyParams.partial();
export const schemaSelectedCalendarUpdateBodyParams = schemaSelectedCalendarBaseBodyParams
.omit({
// id is decided by DB
id: true,
// No eventTypeId support in API v1
eventTypeId: true,
})
.partial();
export const selectedCalendarIdSchema = schemaQueryIdAsString.transform((v, ctx) => {
/** We can assume the first part is the userId since it's an integer */
@@ -1,9 +1,11 @@
import { z } from "zod";
// Helper schema for JSON fields
type Literal = boolean | number | string;
type Literal = boolean | number | string | null;
type Json = Literal | { [key: string]: Json } | Json[];
const literalSchema = z.union([z.string(), z.number(), z.boolean()]);
const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
const jsonObjectSchema = z.record(z.lazy(() => jsonSchema));
const jsonArraySchema = z.array(z.lazy(() => jsonSchema));
export const jsonSchema: z.ZodSchema<Json> = z.lazy(() =>
z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)])
z.union([literalSchema, jsonObjectSchema, jsonArraySchema])
);
+2 -1
View File
@@ -14,7 +14,8 @@
"lint:fix": "eslint . --ext .ts,.js,.tsx,.jsx --fix",
"start": "PORT=3003 next start",
"docker-start-api": "PORT=80 next start",
"type-check": "tsc --pretty --noEmit"
"type-check": "tsc --pretty --noEmit",
"type-check:ci": "tsc-absolute --pretty --noEmit"
},
"devDependencies": {
"@calcom/tsconfig": "*",
@@ -1,9 +1,10 @@
import type { NextApiRequest } from "next";
import type { UserWithCalendars } from "@calcom/lib/getConnectedDestinationCalendars";
import { getConnectedDestinationCalendars } from "@calcom/lib/getConnectedDestinationCalendars";
import { getConnectedDestinationCalendarsAndEnsureDefaultsInDb } from "@calcom/lib/getConnectedDestinationCalendars";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
import { UserRepository } from "@calcom/lib/server/repository/user";
import prisma from "@calcom/prisma";
import { extractUserIdsFromQuery } from "~/lib/utils/extractUserIdsFromQuery";
@@ -104,12 +105,8 @@ async function getHandler(req: NextApiRequest) {
const userIds = req.query.userId ? extractUserIdsFromQuery(req) : [userId];
const usersWithCalendars = await prisma.user.findMany({
where: { id: { in: userIds } },
include: {
selectedCalendars: true,
destinationCalendar: true,
},
const usersWithCalendars = await UserRepository.findManyByIdsIncludeDestinationAndSelectedCalendars({
ids: userIds,
});
return await getConnectedCalendars(usersWithCalendars);
@@ -117,11 +114,12 @@ async function getHandler(req: NextApiRequest) {
async function getConnectedCalendars(users: UserWithCalendars[]) {
const connectedDestinationCalendarsPromises = users.map((user) =>
getConnectedDestinationCalendars(user, false, prisma).then((connectedCalendarsResult) =>
connectedCalendarsResult.connectedCalendars.map((calendar) => ({
userId: user.id,
...calendar,
}))
getConnectedDestinationCalendarsAndEnsureDefaultsInDb({ user, onboarding: false, prisma }).then(
(connectedCalendarsResult) =>
connectedCalendarsResult.connectedCalendars.map((calendar) => ({
userId: user.id,
...calendar,
}))
)
);
const connectedDestinationCalendars = await Promise.all(connectedDestinationCalendarsPromises);
@@ -1,7 +1,7 @@
import type { NextApiRequest } from "next";
import { defaultResponder } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import { selectedCalendarIdSchema } from "~/lib/validations/selected-calendar";
@@ -49,7 +49,9 @@ import { selectedCalendarIdSchema } from "~/lib/validations/selected-calendar";
export async function deleteHandler(req: NextApiRequest) {
const { query } = req;
const userId_integration_externalId = selectedCalendarIdSchema.parse(query);
await prisma.selectedCalendar.delete({ where: { userId_integration_externalId } });
await SelectedCalendarRepository.deleteUserLevel({
where: userId_integration_externalId,
});
return { message: `Selected Calendar with id: ${query.id} deleted successfully` };
}
@@ -1,7 +1,7 @@
import type { NextApiRequest } from "next";
import { defaultResponder } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import { schemaSelectedCalendarPublic, selectedCalendarIdSchema } from "~/lib/validations/selected-calendar";
@@ -49,8 +49,8 @@ import { schemaSelectedCalendarPublic, selectedCalendarIdSchema } from "~/lib/va
export async function getHandler(req: NextApiRequest) {
const { query } = req;
const userId_integration_externalId = selectedCalendarIdSchema.parse(query);
const data = await prisma.selectedCalendar.findUniqueOrThrow({
where: { userId_integration_externalId },
const data = await SelectedCalendarRepository.findUserLevelUniqueOrThrow({
where: userId_integration_externalId,
});
return { selected_calendar: schemaSelectedCalendarPublic.parse(data) };
}
@@ -3,6 +3,8 @@ import type { NextApiRequest } from "next";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
import type { UpdateArguments } from "@calcom/lib/server/repository/selectedCalendar";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import prisma from "@calcom/prisma";
import {
@@ -56,7 +58,7 @@ export async function patchHandler(req: NextApiRequest) {
const { query, isSystemWideAdmin } = req;
const userId_integration_externalId = selectedCalendarIdSchema.parse(query);
const { userId: bodyUserId, ...data } = schemaSelectedCalendarUpdateBodyParams.parse(req.body);
const args: Prisma.SelectedCalendarUpdateArgs = { where: { userId_integration_externalId }, data };
const args: UpdateArguments = { where: { ...userId_integration_externalId }, data };
if (!isSystemWideAdmin && bodyUserId)
throw new HttpError({ statusCode: 403, message: `ADMIN required for userId` });
@@ -67,7 +69,7 @@ export async function patchHandler(req: NextApiRequest) {
args.data.userId = bodyUserId;
}
const result = await prisma.selectedCalendar.update(args);
const result = await SelectedCalendarRepository.updateUserLevel(args);
return { selected_calendar: schemaSelectedCalendarPublic.parse(result) };
}
@@ -1,9 +1,9 @@
import type { Prisma } from "@prisma/client";
import type { NextApiRequest } from "next";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import type { FindManyArgs } from "@calcom/lib/server/repository/selectedCalendar";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import { schemaSelectedCalendarPublic } from "~/lib/validations/selected-calendar";
import { schemaQuerySingleOrMultipleUserIds } from "~/lib/validations/shared/queryUserId";
@@ -34,7 +34,7 @@ import { schemaQuerySingleOrMultipleUserIds } from "~/lib/validations/shared/que
async function getHandler(req: NextApiRequest) {
const { userId, isSystemWideAdmin } = req;
/* Admin gets all selected calendar by default, otherwise only the user's ones */
const args: Prisma.SelectedCalendarFindManyArgs = isSystemWideAdmin ? {} : { where: { userId } };
const args: FindManyArgs = isSystemWideAdmin ? {} : { where: { userId } };
/** Only admins can query other users */
if (!isSystemWideAdmin && req.query.userId)
@@ -46,7 +46,7 @@ async function getHandler(req: NextApiRequest) {
if (Array.isArray(query.userId)) args.orderBy = { userId: "asc" };
}
const data = await prisma.selectedCalendar.findMany(args);
const data = await SelectedCalendarRepository.findManyUserLevel(args);
return { selected_calendars: data.map((v) => schemaSelectedCalendarPublic.parse(v)) };
}
@@ -3,6 +3,7 @@ import type { NextApiRequest } from "next";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import prisma from "@calcom/prisma";
import {
@@ -52,7 +53,11 @@ import {
async function postHandler(req: NextApiRequest) {
const { userId, isSystemWideAdmin } = req;
const { userId: bodyUserId, ...body } = schemaSelectedCalendarBodyParams.parse(req.body);
const args: Prisma.SelectedCalendarCreateArgs = { data: { ...body, userId } };
const args: {
data: Prisma.SelectedCalendarUncheckedCreateInput;
} = {
data: { ...body, userId },
};
if (!isSystemWideAdmin && bodyUserId)
throw new HttpError({ statusCode: 403, message: `ADMIN required for userId` });
@@ -63,7 +68,7 @@ async function postHandler(req: NextApiRequest) {
args.data.userId = bodyUserId;
}
const data = await prisma.selectedCalendar.create(args);
const data = await SelectedCalendarRepository.create(args.data);
return {
selected_calendar: schemaSelectedCalendarPublic.parse(data),
+18 -2
View File
@@ -2,6 +2,7 @@ import type { NextApiRequest } from "next";
import { getStripeCustomerIdFromUserId } from "@calcom/app-store/stripepayment/lib/customer";
import stripe from "@calcom/app-store/stripepayment/lib/server";
import { getDubCustomer } from "@calcom/features/auth/lib/dub";
import { IS_PRODUCTION } from "@calcom/lib/constants";
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
import { HttpError } from "@calcom/lib/http-error";
@@ -192,11 +193,26 @@ const generateTeamCheckoutSession = async ({
pendingPaymentTeamId: number;
ownerId: number;
}) => {
const customer = await getStripeCustomerIdFromUserId(ownerId);
const [customer, dubCustomer] = await Promise.all([
getStripeCustomerIdFromUserId(ownerId),
getDubCustomer(ownerId.toString()),
]);
const session = await stripe.checkout.sessions.create({
customer,
mode: "subscription",
allow_promotion_codes: true,
...(dubCustomer?.discount?.couponId
? {
discounts: [
{
coupon:
process.env.NODE_ENV !== "production" && dubCustomer.discount.couponTestId
? dubCustomer.discount.couponTestId
: dubCustomer.discount.couponId,
},
],
}
: { allow_promotion_codes: true }),
success_url: `${WEBAPP_URL}/api/teams/api/create?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${WEBAPP_URL}/settings/my-account/profile`,
line_items: [
+4 -1
View File
@@ -52,6 +52,8 @@ describe("POST /api/attendees", () => {
bookingId: 1,
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
prismaMock.attendee.create.mockResolvedValue(attendeeData);
req.isSystemWideAdmin = true;
req.userId = 123;
@@ -84,7 +86,8 @@ describe("POST /api/attendees", () => {
timeZone: "UTC",
bookingId: 1,
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
prismaMock.attendee.create.mockResolvedValue(attendeeData);
req.userId = 123;
+1 -1
View File
@@ -11,7 +11,7 @@ import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { buildBooking, buildEventType, buildWebhook } from "@calcom/lib/test/builder";
import prisma from "@calcom/prisma";
import type { Booking } from "@calcom/prisma";
import type { Booking } from "@calcom/prisma/client";
import handler from "../../../pages/api/bookings/_post";
@@ -21,6 +21,8 @@ describe("DELETE /api/event-types/[id]", () => {
beforeEach(() => {
vi.resetAllMocks();
// Mocking membership.findFirst
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
prismaMock.membership.findFirst.mockImplementation(({ where }) => {
const { userId, teamId, accepted, role } = where;
const mockData = [
@@ -72,6 +72,7 @@ describe("POST /api/event-types", () => {
},
});
req.userId = memberUserId;
// @ts-expect-error - Return type is wrong
vi.mocked(canUserAccessTeamWithRole).mockImplementationOnce(async () => false);
await handler(req, res);
@@ -114,6 +115,7 @@ describe("POST /api/event-types", () => {
req.isSystemWideAdmin = true;
req.userId = adminUserId;
// @ts-expect-error - Return type is wrong
vi.mocked(canUserAccessTeamWithRole).mockImplementationOnce(async () => false);
await handler(req, res);
@@ -138,6 +140,7 @@ describe("POST /api/event-types", () => {
req.isSystemWideAdmin = true;
req.userId = adminUserId;
// @ts-expect-error - Return type is wrong
vi.mocked(canUserAccessTeamWithRole).mockImplementationOnce(async () => true);
vi.mocked(checkParentEventOwnership).mockImplementationOnce(async () => undefined);
vi.mocked(checkUserMembership).mockImplementationOnce(async () => undefined);
@@ -5,6 +5,7 @@ import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ILicenseKeyService } from "@calcom/ee/common/server/LicenseKeyService";
import LicenseKeyService from "@calcom/ee/common/server/LicenseKeyService";
import prisma from "@calcom/prisma";
import { MembershipRole, UserPermissionRole } from "@calcom/prisma/enums";
@@ -21,7 +22,7 @@ afterEach(() => {
});
describe("Verify API key", () => {
let service: LicenseKeyService;
let service: ILicenseKeyService;
beforeEach(async () => {
service = await LicenseKeyService.create();
@@ -79,6 +79,15 @@ describe("POST /api/selected-calendars", () => {
integration: "google",
externalId: "ext123",
userId: 444444,
id: "xxx-xxx",
eventTypeId: null,
domainWideDelegationCredentialId: null,
googleChannelId: null,
googleChannelKind: null,
googleChannelResourceId: null,
googleChannelResourceUri: null,
googleChannelExpiration: null,
error: null,
});
await handler(req, res);
@@ -104,10 +113,19 @@ describe("POST /api/selected-calendars", () => {
req.userId = 333333;
prismaMock.selectedCalendar.create.mockResolvedValue({
id: "xxx-xxx",
credentialId: 1,
integration: "google",
externalId: "ext123",
userId: 333333,
googleChannelId: null,
googleChannelKind: null,
googleChannelResourceId: null,
googleChannelResourceUri: null,
googleChannelExpiration: null,
domainWideDelegationCredentialId: null,
eventTypeId: null,
error: null,
});
await handler(req, res);
@@ -2,6 +2,8 @@ import prismock from "../../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it, beforeEach } from "vitest";
import { WatchlistSeverity } from "@calcom/prisma/enums";
import { isLockedOrBlocked } from "../../../lib/utils/isLockedOrBlocked";
describe("isLockedOrBlocked", () => {
@@ -16,6 +18,7 @@ describe("isLockedOrBlocked", () => {
{
type: "DOMAIN",
value: "blocked.com",
severity: WatchlistSeverity.CRITICAL,
createdById: 1,
},
],
+2 -1
View File
@@ -29,7 +29,7 @@
"@axiomhq/winston": "^1.2.0",
"@calcom/platform-constants": "*",
"@calcom/platform-enums": "*",
"@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.73",
"@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.86",
"@calcom/platform-libraries-0.0.2": "npm:@calcom/platform-libraries@0.0.2",
"@calcom/platform-types": "*",
"@calcom/platform-utils": "*",
@@ -59,6 +59,7 @@
"googleapis": "^84.0.0",
"helmet": "^7.1.0",
"ioredis": "^5.3.2",
"jsforce": "^1.11.0",
"luxon": "^3.4.4",
"nest-winston": "^1.9.4",
"next-auth": "^4.22.1",
+2
View File
@@ -18,6 +18,7 @@ import {
CAL_API_VERSION_HEADER,
X_CAL_CLIENT_ID,
X_CAL_SECRET_KEY,
X_CAL_PLATFORM_EMBED,
} from "@calcom/platform-constants";
import { TRPCExceptionFilter } from "./filters/trpc-exception.filter";
@@ -45,6 +46,7 @@ export const bootstrap = (app: NestExpressApplication): NestExpressApplication =
allowedHeaders: [
X_CAL_CLIENT_ID,
X_CAL_SECRET_KEY,
X_CAL_PLATFORM_EMBED,
CAL_API_VERSION_HEADER,
"Accept",
"Authorization",
@@ -37,7 +37,7 @@ import { Request } from "express";
import { NextApiRequest } from "next/types";
import { v4 as uuidv4 } from "uuid";
import { X_CAL_CLIENT_ID } from "@calcom/platform-constants";
import { X_CAL_CLIENT_ID, X_CAL_PLATFORM_EMBED } from "@calcom/platform-constants";
import { BOOKING_READ, SUCCESS_STATUS, BOOKING_WRITE } from "@calcom/platform-constants";
import {
handleNewRecurringBooking,
@@ -161,14 +161,15 @@ export class BookingsController_2024_04_15 {
async createBooking(
@Req() req: BookingRequest,
@Body() body: CreateBookingInput_2024_04_15,
@Headers(X_CAL_CLIENT_ID) clientId?: string
@Headers(X_CAL_CLIENT_ID) clientId?: string,
@Headers(X_CAL_PLATFORM_EMBED) isEmbed?: string
): Promise<ApiResponse<Partial<BookingResponse>>> {
const oAuthClientId = clientId?.toString();
const { orgSlug, locationUrl } = body;
req.headers["x-cal-force-slug"] = orgSlug;
try {
const booking = await handleNewBooking(
await this.createNextApiBookingRequest(req, oAuthClientId, locationUrl)
await this.createNextApiBookingRequest(req, oAuthClientId, locationUrl, isEmbed)
);
if (booking.userId && booking.uid && booking.startTime) {
void (await this.billingService.increaseUsageByUserId(booking.userId, {
@@ -192,13 +193,16 @@ export class BookingsController_2024_04_15 {
@Req() req: BookingRequest,
@Param("bookingId") bookingId: string,
@Body() _: CancelBookingInput_2024_04_15,
@Headers(X_CAL_CLIENT_ID) clientId?: string
@Headers(X_CAL_CLIENT_ID) clientId?: string,
@Headers(X_CAL_PLATFORM_EMBED) isEmbed?: string
): Promise<ApiResponse<{ bookingId: number; bookingUid: string; onlyRemovedAttendee: boolean }>> {
const oAuthClientId = clientId?.toString();
if (bookingId) {
try {
req.body.id = parseInt(bookingId);
const res = await handleCancelBooking(await this.createNextApiBookingRequest(req, oAuthClientId));
const res = await handleCancelBooking(
await this.createNextApiBookingRequest(req, oAuthClientId, undefined, isEmbed)
);
if (!res.onlyRemovedAttendee) {
void (await this.billingService.cancelUsageByBookingUid(res.bookingUid));
}
@@ -246,7 +250,8 @@ export class BookingsController_2024_04_15 {
async createRecurringBooking(
@Req() req: BookingRequest,
@Body() _: CreateRecurringBookingInput_2024_04_15[],
@Headers(X_CAL_CLIENT_ID) clientId?: string
@Headers(X_CAL_CLIENT_ID) clientId?: string,
@Headers(X_CAL_PLATFORM_EMBED) isEmbed?: string
): Promise<ApiResponse<BookingResponse[]>> {
const oAuthClientId = clientId?.toString();
try {
@@ -258,7 +263,7 @@ export class BookingsController_2024_04_15 {
}
const createdBookings: BookingResponse[] = await handleNewRecurringBooking(
await this.createNextApiRecurringBookingRequest(req, oAuthClientId)
await this.createNextApiRecurringBookingRequest(req, oAuthClientId, undefined, isEmbed)
);
createdBookings.forEach(async (booking) => {
@@ -284,13 +289,14 @@ export class BookingsController_2024_04_15 {
async createInstantBooking(
@Req() req: BookingRequest,
@Body() _: CreateBookingInput_2024_04_15,
@Headers(X_CAL_CLIENT_ID) clientId?: string
@Headers(X_CAL_CLIENT_ID) clientId?: string,
@Headers(X_CAL_PLATFORM_EMBED) isEmbed?: string
): Promise<ApiResponse<Awaited<ReturnType<typeof handleInstantMeeting>>>> {
const oAuthClientId = clientId?.toString();
req.userId = (await this.getOwnerId(req)) ?? -1;
try {
const instantMeeting = await handleInstantMeeting(
await this.createNextApiBookingRequest(req, oAuthClientId)
await this.createNextApiBookingRequest(req, oAuthClientId, undefined, isEmbed)
);
if (instantMeeting.userId && instantMeeting.bookingUid) {
@@ -332,8 +338,14 @@ export class BookingsController_2024_04_15 {
}
}
private async getOAuthClientsParams(clientId: string): Promise<OAuthRequestParams> {
private async getOAuthClientsParams(clientId: string, isEmbed = false): Promise<OAuthRequestParams> {
const res = { ...DEFAULT_PLATFORM_PARAMS };
if (isEmbed) {
// embed should ignore oauth client settings and enable emails by default
return { ...res, arePlatformEmailsEnabled: true };
}
try {
const client = await this.oAuthClientRepository.getOAuthClient(clientId);
// fetch oAuthClient from db and use data stored in db to set these values
@@ -354,13 +366,14 @@ export class BookingsController_2024_04_15 {
private async createNextApiBookingRequest(
req: BookingRequest,
oAuthClientId?: string,
platformBookingLocation?: string
platformBookingLocation?: string,
isEmbed?: string
): Promise<NextApiRequest & { userId?: number } & OAuthRequestParams> {
const requestId = req.get("X-Request-Id");
const clone = { ...req };
const userId = (await this.getOwnerId(req)) ?? -1;
const oAuthParams = oAuthClientId
? await this.getOAuthClientsParams(oAuthClientId)
? await this.getOAuthClientsParams(oAuthClientId, this.transformToBoolean(isEmbed))
: DEFAULT_PLATFORM_PARAMS;
this.logger.log(`createNextApiBookingRequest_2024_04_15`, {
requestId,
@@ -377,12 +390,13 @@ export class BookingsController_2024_04_15 {
private async createNextApiRecurringBookingRequest(
req: BookingRequest,
oAuthClientId?: string,
platformBookingLocation?: string
platformBookingLocation?: string,
isEmbed?: string
): Promise<NextApiRequest & { userId?: number } & OAuthRequestParams> {
const clone = { ...req };
const userId = (await this.getOwnerId(req)) ?? -1;
const oAuthParams = oAuthClientId
? await this.getOAuthClientsParams(oAuthClientId)
? await this.getOAuthClientsParams(oAuthClientId, this.transformToBoolean(isEmbed))
: DEFAULT_PLATFORM_PARAMS;
const requestId = req.get("X-Request-Id");
this.logger.log(`createNextApiRecurringBookingRequest_2024_04_15`, {
@@ -424,4 +438,8 @@ export class BookingsController_2024_04_15 {
throw new InternalServerErrorException(errMsg);
}
private transformToBoolean(v?: string): boolean {
return v && typeof v === "string" ? v.toLowerCase() === "true" : false;
}
}
@@ -5,7 +5,7 @@ import { MarkAbsentBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/out
import { ReassignBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/reassign-booking.output";
import { RescheduleBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/reschedule-booking.output";
import { BookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/bookings.service";
import { VERSION_2024_08_13_VALUE } from "@/lib/api-versions";
import { VERSION_2024_08_13_VALUE, VERSION_2024_08_13 } from "@/lib/api-versions";
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";
@@ -65,6 +65,7 @@ import {
@ApiHeader({
name: "cal-api-version",
description: `Must be set to \`2024-08-13\``,
example: VERSION_2024_08_13,
required: true,
})
export class BookingsController_2024_08_13 {
@@ -952,7 +952,10 @@ describe("Bookings Endpoints 2024-08-13", () => {
slug: recurringSeatedTventTypeSlug,
});
expect(firstBooking.attendees.length).toEqual(2);
expect(firstBooking.attendees[0]).toEqual({
const firstAttendee = firstBooking.attendees.find(
(attendee) => attendee.name === nameAttendeeOne
);
expect(firstAttendee).toEqual({
name: nameAttendeeOne,
email: emailAttendeeOne,
timeZone: body.attendee.timeZone,
@@ -965,7 +968,10 @@ describe("Bookings Endpoints 2024-08-13", () => {
},
metadata: createdRecurringSeatedBooking[0].attendees[0].metadata,
});
expect(firstBooking.attendees[1]).toEqual({
const secondAttendee = firstBooking.attendees.find(
(attendee) => attendee.name === nameAttendeeTwo
);
expect(secondAttendee).toEqual({
name: nameAttendeeTwo,
email: emailAttendeeTwo,
timeZone: body.attendee.timeZone,
@@ -59,6 +59,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
let team1EventTypeId: number;
let team2EventTypeId: number;
let phoneOnlyEventTypeId: number;
beforeAll(async () => {
const moduleRef = await withApiAuth(
@@ -205,6 +206,83 @@ describe("Bookings Endpoints 2024-08-13", () => {
team1EventTypeId = team1EventType.id;
const phoneOnlyEventType = await eventTypesRepositoryFixture.createTeamEventType({
schedulingType: "ROUND_ROBIN",
team: {
connect: { id: team1.id },
},
title: "Phone Only Event Type",
slug: "phone-only-event-type",
length: 15,
assignAllTeamMembers: false,
hosts: {
connectOrCreate: [
{
where: {
userId_eventTypeId: {
userId: teamUser.id,
eventTypeId: team1EventTypeId,
},
},
create: {
userId: teamUser.id,
isFixed: true,
},
},
],
},
bookingFields: [
{
name: "name",
type: "name",
label: "your name",
sources: [{ id: "default", type: "default", label: "Default" }],
variant: "fullName",
editable: "system",
required: true,
defaultLabel: "your_name",
variantsConfig: {
variants: {
fullName: {
fields: [{ name: "fullName", type: "text", label: "your name", required: true }],
},
},
},
},
{
name: "email",
type: "email",
label: "your email",
sources: [{ id: "default", type: "default", label: "Default" }],
editable: "system",
required: false,
defaultLabel: "email_address",
},
{
name: "attendeePhoneNumber",
type: "phone",
label: "phone_number",
sources: [{ id: "user", type: "user", label: "User", fieldRequired: true }],
editable: "user",
required: true,
placeholder: "",
},
{
name: "rescheduleReason",
type: "textarea",
views: [{ id: "reschedule", label: "Reschedule View" }],
sources: [{ id: "default", type: "default", label: "Default" }],
editable: "system-but-optional",
required: false,
defaultLabel: "reason_for_reschedule",
defaultPlaceholder: "reschedule_placeholder",
},
],
locations: [],
});
phoneOnlyEventTypeId = phoneOnlyEventType.id;
const team2EventType = await eventTypesRepositoryFixture.createTeamEventType({
schedulingType: "COLLECTIVE",
team: {
@@ -322,6 +400,60 @@ describe("Bookings Endpoints 2024-08-13", () => {
});
});
it("should create a phone based booking", async () => {
const body: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 0, 8, 15, 0, 0)).toISOString(),
eventTypeId: phoneOnlyEventTypeId,
attendee: {
name: "alice",
phoneNumber: "+919876543210",
timeZone: "Europe/Madrid",
language: "es",
},
meetingUrl: "https://meet.google.com/abc-def-ghi",
};
return request(app.getHttpServer())
.post("/v2/bookings")
.send(body)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201)
.then(async (response) => {
const responseBody: CreateBookingOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
expect(responseDataIsBooking(responseBody.data)).toBe(true);
if (responseDataIsBooking(responseBody.data)) {
const data: BookingOutput_2024_08_13 = responseBody.data;
expect(data.id).toBeDefined();
expect(data.uid).toBeDefined();
expect(data.hosts.length).toEqual(1);
expect(data.hosts[0].id).toEqual(teamUser.id);
expect(data.status).toEqual("accepted");
expect(data.start).toEqual(body.start);
expect(data.end).toEqual(new Date(Date.UTC(2030, 0, 8, 15, 15, 0)).toISOString());
expect(data.duration).toEqual(15);
expect(data.eventTypeId).toEqual(phoneOnlyEventTypeId);
expect(data.attendees.length).toEqual(1);
expect(data.attendees[0]).toEqual({
name: body.attendee.name,
email: "919876543210@sms.cal.com",
phoneNumber: body.attendee.phoneNumber,
timeZone: body.attendee.timeZone,
language: body.attendee.language,
absent: false,
});
expect(data.meetingUrl).toEqual(body.meetingUrl);
expect(data.absentHost).toEqual(false);
} else {
throw new Error(
"Invalid response data - expected booking but received array of possibily recurring bookings"
);
}
});
});
it("should create a team 2 booking", async () => {
const body: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 0, 8, 10, 0, 0)).toISOString(),
@@ -398,7 +530,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
| RecurringBookingOutput_2024_08_13
| GetSeatedBookingOutput_2024_08_13
)[] = responseBody.data;
expect(data.length).toEqual(1);
expect(data.length).toEqual(2);
expect(data[0].eventTypeId).toEqual(team1EventTypeId);
});
});
@@ -436,7 +568,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
| RecurringBookingOutput_2024_08_13
| GetSeatedBookingOutput_2024_08_13
)[] = responseBody.data;
expect(data.length).toEqual(2);
expect(data.length).toEqual(3);
expect(data.find((booking) => booking.eventTypeId === team1EventTypeId)).toBeDefined();
expect(data.find((booking) => booking.eventTypeId === team2EventTypeId)).toBeDefined();
});
@@ -332,6 +332,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
metadata: {
userId: "100",
},
guests: ["bob@gmail.com"],
};
const beforeCreate = new Date();
@@ -376,7 +377,9 @@ describe("Bookings Endpoints 2024-08-13", () => {
name: body.attendee.name,
email: body.attendee.email,
...body.bookingFieldsResponses,
guests: body.guests,
});
expect(data.guests).toEqual(body.guests);
// Check createdAt date is between the time of the request and after the request
const createdAtDate = new Date(data.createdAt);
@@ -13,7 +13,6 @@ import { Request } from "express";
import { z } from "zod";
import {
handleNewBooking,
handleNewRecurringBooking,
getAllUserBookings,
handleInstantMeeting,
@@ -23,6 +22,7 @@ import {
handleMarkNoShow,
confirmBookingHandler,
} from "@calcom/platform-libraries";
import { handleNewBooking } from "@calcom/platform-libraries";
import {
CreateBookingInput_2024_08_13,
CreateBookingInput,
@@ -340,7 +340,10 @@ export class BookingsService_2024_08_13 {
}
const bookingRequest = await this.inputService.createCancelBookingRequest(request, bookingUid, body);
await handleCancelBooking(bookingRequest);
const res = await handleCancelBooking(bookingRequest);
if (!res.onlyRemovedAttendee) {
await this.billingService.cancelUsageByBookingUid(res.bookingUid);
}
if ("cancelSubsequentBookings" in body && body.cancelSubsequentBookings) {
return this.getAllRecurringBookingsByIndividualUid(bookingUid);
@@ -146,6 +146,8 @@ export class InputBookingsService_2024_08_13 {
);
const endTime = startTime.plus({ minutes: lengthInMinutes });
const guests = inputBooking.guests;
return {
start: startTime.toISO(),
end: endTime.toISO(),
@@ -154,15 +156,22 @@ export class InputBookingsService_2024_08_13 {
language: inputBooking.attendee.language || "en",
metadata: inputBooking.metadata || {},
hasHashedBookingLink: false,
guests: inputBooking.guests,
guests,
// note(Lauris): responses with name and email are required by the handleNewBooking
responses: inputBooking.bookingFieldsResponses
? {
...inputBooking.bookingFieldsResponses,
name: inputBooking.attendee.name,
email: inputBooking.attendee.email,
email: inputBooking.attendee.email ?? "",
attendeePhoneNumber: inputBooking.attendee.phoneNumber,
guests,
}
: { name: inputBooking.attendee.name, email: inputBooking.attendee.email },
: {
name: inputBooking.attendee.name,
email: inputBooking.attendee.email ?? "",
attendeePhoneNumber: inputBooking.attendee.phoneNumber,
guests,
},
};
}
@@ -246,6 +255,8 @@ export class InputBookingsService_2024_08_13 {
inputBooking.attendee.timeZone
);
const guests = inputBooking.guests;
for (let i = 0; i < repeatsTimes; i++) {
const endTime = startTime.plus({ minutes: eventType.length });
@@ -258,15 +269,16 @@ export class InputBookingsService_2024_08_13 {
language: inputBooking.attendee.language || "en",
metadata: inputBooking.metadata || {},
hasHashedBookingLink: false,
guests: inputBooking.guests,
guests,
// note(Lauris): responses with name and email are required by the handleNewBooking
responses: inputBooking.bookingFieldsResponses
? {
...inputBooking.bookingFieldsResponses,
name: inputBooking.attendee.name,
email: inputBooking.attendee.email,
guests,
}
: { name: inputBooking.attendee.name, email: inputBooking.attendee.email },
: { name: inputBooking.attendee.name, email: inputBooking.attendee.email, guests },
schedulingType: eventType.schedulingType,
});
@@ -72,6 +72,7 @@ type DatabaseBooking = Booking & {
email: string;
timeZone: string;
locale: string | null;
phoneNumber?: string | null;
noShow: boolean | null;
bookingSeat?: BookingSeat | null;
}[];
@@ -121,6 +122,7 @@ export class OutputBookingsService_2024_08_13 {
timeZone: attendee.timeZone,
language: attendee.locale,
absent: !!attendee.noShow,
phoneNumber: attendee.phoneNumber ?? undefined,
})),
guests: bookingResponses.guests,
location,
@@ -86,18 +86,16 @@ export class CalendarsController {
@UseGuards(ApiAuthGuard)
@Get("/busy-times")
@ApiOperation({ summary: "Get busy times" })
@ApiOperation({
summary: "Get busy times",
description:
"Get busy times from a calendar. Example request URL is `https://api.cal.com/v2/calendars/busy-times?loggedInUsersTz=Europe%2FMadrid&dateFrom=2024-12-18&dateTo=2024-12-18&calendarsToLoad[0][credentialId]=135&calendarsToLoad[0][externalId]=skrauciz%40gmail.com`",
})
async getBusyTimes(
@Query() queryParams: CalendarBusyTimesInput,
@GetUser() user: UserWithProfile
): Promise<GetBusyTimesOutput> {
const { loggedInUsersTz, dateFrom, dateTo, calendarsToLoad } = queryParams;
if (!dateFrom || !dateTo) {
return {
status: SUCCESS_STATUS,
data: [],
};
}
const busyTimes = await this.calendarsService.getBusyTimes(
calendarsToLoad,
@@ -19,7 +19,10 @@ import { DateTime } from "luxon";
import { z } from "zod";
import { APPS_TYPE_ID_MAPPING } from "@calcom/platform-constants";
import { getConnectedDestinationCalendars, getBusyCalendarTimes } from "@calcom/platform-libraries";
import {
getConnectedDestinationCalendarsAndEnsureDefaultsInDb,
getBusyCalendarTimes,
} from "@calcom/platform-libraries";
import { Calendar } from "@calcom/platform-types";
import { PrismaClient } from "@calcom/prisma";
@@ -41,12 +44,18 @@ export class CalendarsService {
if (!userWithCalendars) {
throw new NotFoundException("User not found");
}
return getConnectedDestinationCalendars(
userWithCalendars,
false,
this.dbWrite.prisma as unknown as PrismaClient
);
return getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
user: {
...userWithCalendars,
allSelectedCalendars: userWithCalendars.selectedCalendars,
userLevelSelectedCalendars: userWithCalendars.selectedCalendars.filter(
(calendar) => !calendar.eventTypeId
),
},
onboarding: false,
eventTypeId: null,
prisma: this.dbWrite.prisma as unknown as PrismaClient,
});
}
async getBusyTimes(
@@ -64,7 +73,6 @@ export class CalendarsService {
);
try {
const calendarBusyTimes = await getBusyCalendarTimes(
"",
credentials,
dateFrom,
dateTo,
@@ -33,11 +33,18 @@ import {
ApiSuccessResponse,
CreateEventTypeInput_2024_06_14,
EventTypeOutput_2024_06_14,
NameFieldInput_2024_06_14,
NameDefaultFieldInput_2024_06_14,
NotesDefaultFieldInput_2024_06_14,
UpdateEventTypeInput_2024_06_14,
} from "@calcom/platform-types";
import { SchedulingType } from "@calcom/prisma/enums";
const orderBySlug = (a: { slug: string }, b: { slug: string }) => {
if (a.slug < b.slug) return -1;
if (a.slug > b.slug) return 1;
return 0;
};
describe("Event types Endpoints", () => {
describe("Not authenticated", () => {
let app: INestApplication;
@@ -93,6 +100,67 @@ describe("Event types Endpoints", () => {
let orgUserEventType1: EventType;
let orgUserEventType2: EventType;
let orgUserEventType3: EventType;
const defaultResponseBookingFieldName = {
isDefault: true,
type: "name",
slug: "name",
required: true,
disableOnPrefill: false,
};
const defaultResponseBookingFieldEmail = {
isDefault: true,
type: "email",
slug: "email",
required: true,
disableOnPrefill: false,
};
const defaultResponseBookingFieldLocation = {
isDefault: true,
type: "radioInput",
slug: "location",
required: false,
hidden: false,
};
const defaultResponseBookingFieldTitle = {
isDefault: true,
type: "text",
slug: "title",
required: true,
hidden: true,
disableOnPrefill: false,
};
const defaultResponseBookingFieldNotes = {
isDefault: true,
type: "textarea",
slug: "notes",
required: false,
hidden: false,
disableOnPrefill: false,
};
const defaultResponseBookingFieldGuests = {
isDefault: true,
type: "multiemail",
slug: "guests",
required: false,
hidden: false,
disableOnPrefill: false,
};
const defaultResponseBookingFieldRescheduleReason = {
isDefault: true,
type: "textarea",
slug: "rescheduleReason",
required: false,
hidden: false,
disableOnPrefill: false,
};
beforeAll(async () => {
const moduleRef = await withApiAuth(
userEmail,
@@ -253,7 +321,7 @@ describe("Event types Endpoints", () => {
});
it("should create an event type", async () => {
const nameBookingField: NameFieldInput_2024_06_14 = {
const nameBookingField: NameDefaultFieldInput_2024_06_14 = {
type: "name",
label: "Your name sir / madam",
placeholder: "john doe",
@@ -291,6 +359,7 @@ describe("Event types Endpoints", () => {
placeholder: "select language",
options: ["javascript", "python", "cobol"],
disableOnPrefill: true,
hidden: false,
},
],
scheduleId: firstSchedule.id,
@@ -378,16 +447,25 @@ describe("Event types Endpoints", () => {
);
expect(createdEventType.color).toEqual(body.color);
const requestBookingFields = body.bookingFields || [];
const expectedBookingFields = [
{ isDefault: true, required: true, slug: "name", ...nameBookingField },
{ isDefault: true, required: true, slug: "email", type: "email" },
// note(Lauris): location booking field is added if multiple locations are passed
{ isDefault: true, required: false, slug: "location", type: "radioInput" },
{ isDefault: true, required: false, slug: "rescheduleReason", type: "textarea" },
...requestBookingFields
.filter((field) => field.type !== "name" && field.type !== "email")
.map((field) => ({ isDefault: false, ...field })),
{ ...defaultResponseBookingFieldName, ...nameBookingField },
{ ...defaultResponseBookingFieldEmail },
{ ...defaultResponseBookingFieldLocation },
{
type: "select",
label: "select which language you want to learn",
slug: "select-language",
required: true,
placeholder: "select language",
options: ["javascript", "python", "cobol"],
disableOnPrefill: true,
hidden: false,
isDefault: false,
},
{ ...defaultResponseBookingFieldTitle },
{ ...defaultResponseBookingFieldNotes },
{ ...defaultResponseBookingFieldGuests },
{ ...defaultResponseBookingFieldRescheduleReason },
];
expect(createdEventType.bookingFields).toEqual(expectedBookingFields);
@@ -417,7 +495,9 @@ describe("Event types Endpoints", () => {
expect(fetchedEventType?.lengthInMinutes).toEqual(eventType.lengthInMinutes);
expect(fetchedEventType?.lengthInMinutesOptions).toEqual(eventType.lengthInMinutesOptions);
expect(fetchedEventType?.locations).toEqual(eventType.locations);
expect(fetchedEventType?.bookingFields).toEqual(eventType.bookingFields);
expect(fetchedEventType?.bookingFields.sort(orderBySlug)).toEqual(
eventType.bookingFields.sort(orderBySlug).filter((f) => ("hidden" in f ? !f?.hidden : true))
);
expect(fetchedEventType?.ownerId).toEqual(user.id);
expect(fetchedEventType.bookingLimitsCount).toEqual(eventType.bookingLimitsCount);
expect(fetchedEventType.onlyShowFirstAvailableSlot).toEqual(eventType.onlyShowFirstAvailableSlot);
@@ -440,7 +520,6 @@ describe("Event types Endpoints", () => {
});
it(`/GET/event-types by username and orgSlug`, async () => {
console.log(organization);
const response = await request(app.getHttpServer())
.get(`/api/v2/event-types?username=${orgUser.username}&orgSlug=${organization.slug}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_14)
@@ -621,7 +700,6 @@ describe("Event types Endpoints", () => {
.expect(201);
const createdEventType = createResponse.body.data;
console.log("createdEventType: ", createdEventType);
expect(createdEventType).toMatchObject({
id: expect.any(Number),
@@ -764,13 +842,20 @@ describe("Event types Endpoints", () => {
});
it("should update event type", async () => {
const nameBookingField: NameFieldInput_2024_06_14 = {
const nameBookingField: NameDefaultFieldInput_2024_06_14 = {
type: "name",
label: "Your name sir / madam",
placeholder: "john doe",
disableOnPrefill: true,
};
const notesBookingField: NotesDefaultFieldInput_2024_06_14 = {
slug: "notes",
label: "lemme take some notes",
placeholder: "write your notes here",
required: true,
};
const newTitle = "Coding class in Italian!";
const body: UpdateEventTypeInput_2024_06_14 = {
@@ -787,7 +872,9 @@ describe("Event types Endpoints", () => {
placeholder: "select language",
options: ["javascript", "python", "cobol"],
disableOnPrefill: false,
hidden: false,
},
notesBookingField,
],
bookingLimitsCount: {
day: 4,
@@ -850,14 +937,25 @@ describe("Event types Endpoints", () => {
expect(updatedEventType.lengthInMinutes).toEqual(eventType.lengthInMinutes);
expect(updatedEventType.locations).toEqual(eventType.locations);
const requestBookingFields = body.bookingFields || [];
const expectedBookingFields = [
{ isDefault: true, required: true, slug: "name", ...nameBookingField },
{ isDefault: true, required: true, slug: "email", type: "email" },
{ isDefault: true, required: false, slug: "rescheduleReason", type: "textarea" },
...requestBookingFields
.filter((field) => field.type !== "name" && field.type !== "email")
.map((field) => ({ isDefault: false, ...field })),
{ ...defaultResponseBookingFieldName, ...nameBookingField },
{ ...defaultResponseBookingFieldEmail },
{ ...defaultResponseBookingFieldLocation },
{
type: "select",
label: "select which language you want to learn",
slug: "select-language",
required: true,
placeholder: "select language",
options: ["javascript", "python", "cobol"],
disableOnPrefill: false,
hidden: false,
isDefault: false,
},
{ ...defaultResponseBookingFieldTitle },
{ ...defaultResponseBookingFieldNotes, ...notesBookingField },
{ ...defaultResponseBookingFieldGuests },
{ ...defaultResponseBookingFieldRescheduleReason },
];
expect(updatedEventType.bookingFields).toEqual(expectedBookingFields);
@@ -974,7 +1072,9 @@ describe("Event types Endpoints", () => {
expect(fetchedEventType?.lengthInMinutes).toEqual(eventType.lengthInMinutes);
expect(fetchedEventType?.lengthInMinutesOptions).toEqual(eventType.lengthInMinutesOptions);
expect(fetchedEventType?.locations).toEqual(eventType.locations);
expect(fetchedEventType?.bookingFields).toEqual(eventType.bookingFields);
expect(fetchedEventType?.bookingFields.sort(orderBySlug)).toEqual(
eventType.bookingFields.sort(orderBySlug).filter((f) => ("hidden" in f ? !f?.hidden : true))
);
expect(fetchedEventType?.ownerId).toEqual(user.id);
expect(fetchedEventType.bookingLimitsCount).toEqual(eventType.bookingLimitsCount);
expect(fetchedEventType.onlyShowFirstAvailableSlot).toEqual(eventType.onlyShowFirstAvailableSlot);
@@ -1055,14 +1155,48 @@ describe("Event types Endpoints", () => {
let legacyEventTypeId2: number;
const expectedReturnSystemFields = [
{ isDefault: true, required: true, slug: "name", type: "name" },
{ isDefault: true, required: true, slug: "email", type: "email" },
{ isDefault: true, type: "radioInput", slug: "location", required: false },
{ isDefault: true, required: true, slug: "title", type: "text" },
{ isDefault: true, required: false, slug: "notes", type: "textarea" },
{ isDefault: true, required: false, slug: "guests", type: "multiemail" },
{ isDefault: true, required: false, slug: "rescheduleReason", type: "textarea" },
{ isDefault: true, type: "phone", slug: "attendeePhoneNumber", required: false },
{ isDefault: true, required: true, slug: "name", type: "name", disableOnPrefill: false },
{ isDefault: true, required: true, slug: "email", type: "email", disableOnPrefill: false },
{
isDefault: true,
type: "radioInput",
slug: "location",
required: false,
hidden: false,
},
{ isDefault: true, required: true, slug: "title", type: "text", disableOnPrefill: false, hidden: true },
{
isDefault: true,
required: false,
slug: "guests",
type: "multiemail",
disableOnPrefill: false,
hidden: false,
},
{
isDefault: true,
required: false,
slug: "rescheduleReason",
type: "textarea",
disableOnPrefill: false,
hidden: false,
},
{
disableOnPrefill: false,
isDefault: true,
type: "phone",
slug: "attendeePhoneNumber",
required: false,
hidden: true,
},
{
isDefault: true,
required: false,
slug: "notes",
type: "textarea",
disableOnPrefill: false,
hidden: false,
},
];
beforeAll(async () => {
@@ -1186,15 +1320,6 @@ describe("Event types Endpoints", () => {
defaultLabel: "what_is_this_meeting_about",
defaultPlaceholder: "",
},
{
name: "notes",
type: "textarea",
sources: [{ id: "default", type: "default", label: "Default" }],
editable: "system-but-optional",
required: false,
defaultLabel: "additional_notes",
defaultPlaceholder: "share_additional_notes",
},
{
name: "guests",
type: "multiemail",
@@ -1230,6 +1355,15 @@ describe("Event types Endpoints", () => {
required: false,
defaultLabel: "phone_number",
},
{
name: "notes",
type: "textarea",
sources: [{ id: "default", type: "default", label: "Default" }],
editable: "system-but-optional",
required: false,
defaultLabel: "additional_notes",
defaultPlaceholder: "share_additional_notes",
},
],
};
const legacyEventType = await eventTypesRepositoryFixture.create(legacyEventTypeInput, user.id);
@@ -1316,15 +1450,6 @@ describe("Event types Endpoints", () => {
defaultLabel: "what_is_this_meeting_about",
defaultPlaceholder: "",
},
{
name: "notes",
type: "textarea",
sources: [{ id: "default", type: "default", label: "Default" }],
editable: "system-but-optional",
required: false,
defaultLabel: "additional_notes",
defaultPlaceholder: "share_additional_notes",
},
{
name: "guests",
type: "multiemail",
@@ -1360,6 +1485,15 @@ describe("Event types Endpoints", () => {
required: false,
defaultLabel: "phone_number",
},
{
name: "notes",
type: "textarea",
sources: [{ id: "default", type: "default", label: "Default" }],
editable: "system-but-optional",
required: false,
defaultLabel: "additional_notes",
defaultPlaceholder: "share_additional_notes",
},
],
};
const legacyEventType = await eventTypesRepositoryFixture.create(legacyEventTypeInput, user.id);
@@ -1373,17 +1507,21 @@ describe("Event types Endpoints", () => {
const responseBody: ApiSuccessResponse<EventTypeOutput_2024_06_14> = response.body;
const fetchedEventType = responseBody.data;
expect(fetchedEventType.bookingFields).toEqual([
...expectedReturnSystemFields,
{
isDefault: false,
type: userDefinedBookingField.type,
slug: userDefinedBookingField.name,
label: userDefinedBookingField.label,
required: userDefinedBookingField.required,
placeholder: userDefinedBookingField.placeholder,
},
]);
expect(fetchedEventType.bookingFields.sort(orderBySlug)).toEqual(
[
{
isDefault: false,
type: userDefinedBookingField.type,
slug: userDefinedBookingField.name,
label: userDefinedBookingField.label,
required: userDefinedBookingField.required,
placeholder: userDefinedBookingField.placeholder,
disableOnPrefill: false,
hidden: false,
},
...expectedReturnSystemFields,
].sort(orderBySlug)
);
});
});
@@ -1461,42 +1599,53 @@ describe("Event types Endpoints", () => {
type: "name",
slug: "name",
required: true,
disableOnPrefill: false,
},
{
isDefault: true,
type: "email",
slug: "email",
required: true,
disableOnPrefill: false,
},
{
isDefault: true,
type: "radioInput",
slug: "location",
required: false,
hidden: false,
},
{
isDefault: true,
type: "text",
slug: "title",
required: true,
disableOnPrefill: false,
hidden: true,
},
{
isDefault: true,
type: "textarea",
slug: "notes",
required: false,
disableOnPrefill: false,
hidden: false,
},
{
isDefault: true,
type: "multiemail",
slug: "guests",
required: false,
disableOnPrefill: false,
hidden: false,
},
{
isDefault: true,
type: "textarea",
slug: "rescheduleReason",
required: false,
disableOnPrefill: false,
hidden: false,
},
]);
});
@@ -34,6 +34,7 @@ import {
UpdateEventTypeInput_2024_06_14,
GetEventTypesQuery_2024_06_14,
CreateEventTypeInput_2024_06_14,
EventTypeOutput_2024_06_14,
} from "@calcom/platform-types";
@Controller({
@@ -113,10 +114,26 @@ export class EventTypesController_2024_06_14 {
@Query() queryParams: GetEventTypesQuery_2024_06_14
): Promise<GetEventTypesOutput_2024_06_14> {
const eventTypes = await this.eventTypesService.getEventTypes(queryParams);
const eventTypesFormatted = this.eventTypeResponseTransformPipe.transform(eventTypes);
const eventTypesWithoutHiddenFields = eventTypesFormatted.map((eventType) => {
return {
...eventType,
bookingFields: Array.isArray(eventType?.bookingFields)
? eventType?.bookingFields
.map((field) => {
if ("hidden" in field) {
return field.hidden !== true ? field : null;
}
return field;
})
.filter((f) => f)
: [],
};
}) as EventTypeOutput_2024_06_14[];
return {
status: SUCCESS_STATUS,
data: this.eventTypeResponseTransformPipe.transform(eventTypes),
data: eventTypesWithoutHiddenFields,
};
}
@@ -12,9 +12,12 @@ import {
transformRecurrenceApiToInternal,
systemBeforeFieldName,
systemBeforeFieldEmail,
systemBeforeFieldLocation,
systemAfterFieldTitle,
systemAfterFieldNotes,
systemAfterFieldGuests,
systemAfterFieldRescheduleReason,
EventTypeMetaDataSchema,
systemBeforeFieldLocation,
transformBookerLayoutsApiToInternal,
transformConfirmationPolicyApiToInternal,
transformEventColorsApiToInternal,
@@ -217,27 +220,46 @@ export class InputEventTypesService_2024_06_14 {
inputBookingFields: CreateEventTypeInput_2024_06_14["bookingFields"],
hasMultipleLocations: boolean
) {
const customFields: (SystemField | CustomField)[] = inputBookingFields
const internalFields: (SystemField | CustomField)[] = inputBookingFields
? transformBookingFieldsApiToInternal(inputBookingFields)
: [];
const customFieldsWithoutNameEmail = customFields.filter(
(field) => field.type !== "name" && field.type !== "email"
const systemCustomFields = internalFields.filter((field) => !this.isUserCustomField(field));
const userCustomFields = internalFields.filter((field) => this.isUserCustomField(field));
const systemCustomNameField = systemCustomFields?.find((field) => field.type === "name");
const systemCustomEmailField = systemCustomFields?.find((field) => field.type === "email");
const systemCustomTitleField = systemCustomFields?.find((field) => field.name === "title");
const systemCustomNotesField = systemCustomFields?.find((field) => field.name === "notes");
const systemCustomGuestsField = systemCustomFields?.find((field) => field.name === "guests");
const systemCustomRescheduleReasonField = systemCustomFields?.find(
(field) => field.name === "rescheduleReason"
);
const customNameField = customFields?.find((field) => field.type === "name");
const customEmailField = customFields?.find((field) => field.type === "email");
const defaultFieldsBefore: (SystemField | CustomField)[] = [
customNameField || systemBeforeFieldName,
customEmailField || systemBeforeFieldEmail,
systemCustomNameField || systemBeforeFieldName,
systemCustomEmailField || systemBeforeFieldEmail,
systemBeforeFieldLocation,
];
// note(Lauris): if event type has multiple locations then a radio button booking field has to be displayed to allow booker to pick location
if (hasMultipleLocations) {
defaultFieldsBefore.push(systemBeforeFieldLocation);
}
const defaultFieldsAfter = [systemAfterFieldRescheduleReason];
const defaultFieldsAfter = [
systemCustomTitleField || systemAfterFieldTitle,
systemCustomNotesField || systemAfterFieldNotes,
systemCustomGuestsField || systemAfterFieldGuests,
systemCustomRescheduleReasonField || systemAfterFieldRescheduleReason,
];
return [...defaultFieldsBefore, ...customFieldsWithoutNameEmail, ...defaultFieldsAfter];
return [...defaultFieldsBefore, ...userCustomFields, ...defaultFieldsAfter];
}
isUserCustomField(field: SystemField | CustomField): field is CustomField {
return (
field.type !== "name" &&
field.type !== "email" &&
field.name !== "title" &&
field.name !== "notes" &&
field.name !== "guests" &&
field.name !== "rescheduleReason"
);
}
transformInputIntervalLimits(inputBookingFields: CreateEventTypeInput_2024_06_14["bookingLimitsCount"]) {
@@ -128,6 +128,7 @@ export class OutputEventTypesService_2024_06_14 {
const bookingFields = databaseEventType.bookingFields
? this.transformBookingFields(databaseEventType.bookingFields)
: this.getDefaultBookingFields(isOrgTeamEvent);
const recurrence = this.transformRecurringEvent(databaseEventType.recurringEvent);
const metadata = this.transformMetadata(databaseEventType.metadata) || {};
const users = this.transformUsers(databaseEventType.users || []);
@@ -9,6 +9,7 @@ import { ProviderModule } from "@/ee/provider/provider.module";
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
import { SchedulesModule_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/schedules.module";
import { SlotsModule } from "@/modules/slots/slots.module";
import { TeamsEventTypesModule } from "@/modules/teams/event-types/teams-event-types.module";
import { TeamsModule } from "@/modules/teams/teams/teams.module";
import { TeamsMembershipsModule } from "@/modules/teams/memberships/teams-memberships.module";
import type { MiddlewareConsumer, NestModule } from "@nestjs/common";
@@ -20,6 +21,7 @@ import { Module } from "@nestjs/common";
ProviderModule,
SchedulesModule_2024_04_15,
SchedulesModule_2024_06_11,
TeamsEventTypesModule,
MeModule,
EventTypesModule_2024_04_15,
EventTypesModule_2024_06_14,
@@ -10,7 +10,7 @@ export class OutputSchedulesService_2024_06_11 {
async getResponseSchedule(databaseSchedule: Schedule & { availability: Availability[] }) {
if (!databaseSchedule.timeZone) {
throw new Error("Failed to create schedule because its timezone is not set.");
databaseSchedule.timeZone = "Europe/London";
}
const ownerDefaultScheduleId = await this.usersRepository.getUserScheduleDefaultId(
@@ -41,6 +41,18 @@ describe("isOriginAllowed", () => {
const origin = "https://sub.mydomain.com/path/to/resource";
expect(isOriginAllowed(origin, allowedOrigins)).toBe(true);
});
it("should handle patterns with wildcard for routes correctly", () => {
const allowedOrigins = ["https://domain.com/*"];
const origin = "https://domain.com/dashboard";
expect(isOriginAllowed(origin, allowedOrigins)).toBe(true);
});
it("should handle patterns with wildcard for root route correctly", () => {
const allowedOrigins = ["https://domain.com*"];
const origin = "https://domain.com";
expect(isOriginAllowed(origin, allowedOrigins)).toBe(true);
});
});
describe("is not allowed", () => {
@@ -8,12 +8,13 @@ import { CredentialsRepository } from "@/modules/credentials/credentials.reposit
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
import { OrganizationsModule } from "@/modules/organizations/organizations.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { TeamsEventTypesModule } from "@/modules/teams/event-types/teams-event-types.module";
import { UsersService } from "@/modules/users/services/users.service";
import { UsersRepository } from "@/modules/users/users.repository";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule, EventTypesModule_2024_06_14, OrganizationsModule],
imports: [PrismaModule, EventTypesModule_2024_06_14, OrganizationsModule, TeamsEventTypesModule],
providers: [
EventTypesAtomService,
ConferencingAtomsService,
@@ -2,10 +2,9 @@ import { EventTypesService_2024_06_14 } from "@/ee/event-types/event-types_2024_
import { AtomsRepository } from "@/modules/atoms/atoms.repository";
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
import { OrganizationsEventTypesService } from "@/modules/organizations/services/event-types/organizations-event-types.service";
import { TeamsEventTypesService } from "@/modules/teams/event-types/services/teams-event-types.service";
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { TeamsRepository } from "@/modules/teams/teams/teams.repository";
import { UsersService } from "@/modules/users/services/users.service";
import { UserWithProfile } from "@/modules/users/users.repository";
import { Injectable, NotFoundException, ForbiddenException } from "@nestjs/common";
@@ -50,7 +49,7 @@ export class EventTypesAtomService {
private readonly dbWrite: PrismaWriteService,
private readonly dbRead: PrismaReadService,
private readonly eventTypeService: EventTypesService_2024_06_14,
private readonly teamEventTypeService: OrganizationsEventTypesService
private readonly teamEventTypeService: TeamsEventTypesService
) {}
async getUserEventType(user: UserWithProfile, eventTypeId: number) {
@@ -1,22 +1,18 @@
import { UserWithProfile } from "@/modules/users/users.repository";
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { ExecutionContext } from "@nestjs/common";
import { createParamDecorator } from "@nestjs/common";
export type GetUserReturnType = UserWithProfile & { isSystemAdmin: boolean };
export const GetUser = createParamDecorator<
keyof GetUserReturnType | (keyof GetUserReturnType)[],
keyof ApiAuthGuardUser | (keyof ApiAuthGuardUser)[],
ExecutionContext
>((data, ctx) => {
const request = ctx.switchToHttp().getRequest();
const user = request.user as GetUserReturnType;
const user = request.user as ApiAuthGuardUser;
if (!user) {
throw new Error("GetUser decorator : User not found");
}
user.isSystemAdmin = user.role === "ADMIN";
if (Array.isArray(data)) {
return data.reduce((prev, curr) => {
return {
@@ -1,5 +1,5 @@
import { PlatformPlan } from "@/modules/auth/decorators/billing/platform-plan.decorator";
import { GetUserReturnType } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { PlatformPlanType } from "@/modules/billing/types";
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { RedisService } from "@/modules/redis/redis.service";
@@ -19,7 +19,7 @@ export class PlatformPlanGuard implements CanActivate {
const request = context.switchToHttp().getRequest<Request>();
const teamId = request.params.teamId as string;
const orgId = request.params.orgId as string;
const user = request.user as GetUserReturnType;
const user = request.user as ApiAuthGuardUser;
const minimumPlan = this.reflector.get(PlatformPlan, context.getHandler()) as PlatformPlanType;
const REDIS_CACHE_KEY = `apiv2:user:${user?.id ?? "none"}:org:${orgId ?? "none"}:team:${
@@ -1,6 +1,6 @@
import { ORG_ROLES, TEAM_ROLES, SYSTEM_ADMIN_ROLE } from "@/lib/roles/constants";
import { GetUserReturnType } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Roles } from "@/modules/auth/decorators/roles/roles.decorator";
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
import { RedisService } from "@/modules/redis/redis.service";
import { Injectable, CanActivate, ExecutionContext, ForbiddenException, Logger } from "@nestjs/common";
@@ -22,7 +22,7 @@ export class RolesGuard implements CanActivate {
const request = context.switchToHttp().getRequest<Request & { team: Team }>();
const teamId = request.params.teamId as string;
const orgId = request.params.orgId as string;
const user = request.user as GetUserReturnType;
const user = request.user as ApiAuthGuardUser;
const allowedRole = this.reflector.get(Roles, context.getHandler());
const REDIS_CACHE_KEY = `apiv2:user:${user.id ?? "none"}:org:${orgId ?? "none"}:team:${
teamId ?? "none"
@@ -17,6 +17,8 @@ import { getToken } from "next-auth/jwt";
import { INVALID_ACCESS_TOKEN, X_CAL_CLIENT_ID, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
export type ApiAuthGuardUser = UserWithProfile & { isSystemAdmin: boolean };
@Injectable()
export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth") {
constructor(
@@ -75,12 +77,19 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
async authenticateNextAuth(token: { email?: string | null }) {
const user = await this.nextAuthStrategy(token);
return this.success(user);
return this.success(this.getSuccessUser(user));
}
getSuccessUser(user: UserWithProfile): ApiAuthGuardUser {
return {
...user,
isSystemAdmin: user.role === "ADMIN",
};
}
async authenticateOAuthClient(oAuthClientId: string, oAuthClientSecret: string) {
const user = await this.oAuthClientStrategy(oAuthClientId, oAuthClientSecret);
return this.success(user);
return this.success(this.getSuccessUser(user));
}
async oAuthClientStrategy(oAuthClientId: string, oAuthClientSecret: string) {
@@ -119,7 +128,7 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
return this.error(new UnauthorizedException("No user associated with the provided token"));
}
return this.success(user);
return this.success(this.getSuccessUser(user));
} catch (err) {
if (err instanceof Error) {
return this.error(err);
@@ -170,7 +179,7 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
if (origin && !isOriginAllowed(origin, client.redirectUris)) {
throw new UnauthorizedException(
`Invalid request origin - please open https://app.cal.com/settings/platform and add the origin '${origin}' to the 'Redirect uris' of your OAuth client.`
`Invalid request origin - please open https://app.cal.com/settings/platform and add the origin '${origin}' to the 'Redirect uris' of your OAuth client with ID '${client.id}'`
);
}
@@ -220,6 +220,7 @@ describe("OAuth Client Users Endpoints", () => {
await userConnectedToOAuth(responseBody.data.user.email);
await userHasDefaultEventTypes(responseBody.data.user.id);
await userHasDefaultSchedule(responseBody.data.user.id, responseBody.data.user.defaultScheduleId);
await userHasOnlyOneSchedule(responseBody.data.user.id);
});
async function userConnectedToOAuth(userEmail: string) {
@@ -260,6 +261,11 @@ describe("OAuth Client Users Endpoints", () => {
expect(schedule?.userId).toEqual(userId);
}
async function userHasOnlyOneSchedule(userId: number) {
const schedules = await schedulesRepositoryFixture.getByUserId(userId);
expect(schedules?.length).toEqual(1);
}
it(`should fail /POST using already used managed user email`, async () => {
const requestBody: CreateManagedUserInput = {
email: userEmail,
@@ -1,4 +1,4 @@
import { GetUserReturnType } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
import { UsersService } from "@/modules/users/services/users.service";
import {
@@ -15,8 +15,8 @@ export class OAuthClientGuard implements CanActivate {
constructor(private oAuthClientRepository: OAuthClientRepository, private usersService: UsersService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request & { user: GetUserReturnType }>();
const user: GetUserReturnType = request.user;
const request = context.switchToHttp().getRequest<Request & { user: ApiAuthGuardUser }>();
const user: ApiAuthGuardUser = request.user;
const organizationId = user ? this.usersService.getUserMainOrgId(user) : null;
const oAuthClientId = request.params.clientId;
@@ -0,0 +1,30 @@
import { UserOOORepository } from "@/modules/ooo/repositories/ooo.repository";
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
import { Request } from "express";
@Injectable()
export class IsUserOOO implements CanActivate {
constructor(private oooRepo: UserOOORepository) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const oooId: string = request.params.oooId;
const userId: string = request.params.userId;
if (!userId) {
throw new ForbiddenException("No user id found in request params.");
}
if (!oooId) {
throw new ForbiddenException("No ooo entry id found in request params.");
}
const ooo = await this.oooRepo.getUserOOOByIdAndUserId(Number(oooId), Number(userId));
if (ooo) {
return true;
}
throw new ForbiddenException("This OOO entry does not belong to this user.");
}
}
@@ -0,0 +1,128 @@
import { BadRequestException } from "@nestjs/common";
import { ApiProperty, ApiPropertyOptional, PartialType } from "@nestjs/swagger";
import { Transform } from "class-transformer";
import { IsDate, IsInt, IsOptional, IsString, IsEnum, isDate } from "class-validator";
import { SkipTakePagination } from "@calcom/platform-types";
export enum OutOfOfficeReason {
UNSPECIFIED = "unspecified",
VACATION = "vacation",
TRAVEL = "travel",
SICK_LEAVE = "sick",
PUBLIC_HOLIDAY = "public_holiday",
}
export type OutOfOfficeReasonType = `${OutOfOfficeReason}`;
const isDateString = (dateString: string) => {
try {
const isoDateRegex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{3})?Z$/;
return isoDateRegex.test(dateString);
} catch {
throw new BadRequestException("Invalid Date.");
}
};
export class CreateOutOfOfficeEntryDto {
@Transform(({ value }: { value: string }) => {
if (isDateString(value)) {
const date = new Date(value);
date.setUTCHours(0, 0, 0, 0);
return date;
}
throw new BadRequestException("Invalid Date.");
})
@IsDate()
@ApiProperty({
description: "The start date and time of the out of office period in ISO 8601 format in UTC timezone.",
example: "2023-05-01T00:00:00.000Z",
})
start!: Date;
@Transform(({ value }: { value: string }) => {
if (isDateString(value)) {
const date = new Date(value);
date.setUTCHours(23, 59, 59, 999);
return date;
}
throw new BadRequestException("Invalid Date.");
})
@IsDate()
@ApiProperty({
description: "The end date and time of the out of office period in ISO 8601 format in UTC timezone.",
example: "2023-05-10T23:59:59.999Z",
})
end!: Date;
@IsString()
@IsOptional()
@ApiPropertyOptional({
description: "Optional notes for the out of office entry.",
example: "Vacation in Hawaii",
})
notes?: string;
@IsInt()
@IsOptional()
@ApiPropertyOptional({
description: "The ID of the user covering for the out of office period, if applicable.",
example: 2,
})
toUserId?: number;
@IsEnum(OutOfOfficeReason)
@IsOptional()
@ApiPropertyOptional({
description: "the reason for the out of office entry, if applicable",
example: "vacation",
enum: OutOfOfficeReason,
})
reason?: OutOfOfficeReasonType;
}
export class UpdateOutOfOfficeEntryDto extends PartialType(CreateOutOfOfficeEntryDto) {}
export enum SortOrder {
asc = "asc",
desc = "desc",
}
type SortOrderType = keyof typeof SortOrder;
export class GetOutOfOfficeEntryFiltersDTO extends SkipTakePagination {
@IsOptional()
@IsEnum(SortOrder, {
message: 'SortStart must be either "asc" or "desc".',
})
@ApiProperty({
required: false,
description: "Sort results by their start time in ascending or descending order.",
example: "?sortStart=asc OR ?sortStart=desc",
enum: SortOrder,
})
sortStart?: SortOrderType;
@IsOptional()
@IsEnum(SortOrder, {
message: 'SortEnd must be either "asc" or "desc".',
})
@ApiProperty({
required: false,
description: "Sort results by their end time in ascending or descending order.",
example: "?sortEnd=asc OR ?sortEnd=desc",
enum: SortOrder,
})
sortEnd?: SortOrderType;
}
export class GetOrgUsersOutOfOfficeEntryFiltersDTO extends GetOutOfOfficeEntryFiltersDTO {
@IsString()
@IsOptional()
@ApiProperty({
type: String,
required: false,
description: "Filter ooo entries by the user email address. user must be within your organization.",
example: "example@domain.com",
})
email?: string;
}
@@ -0,0 +1,100 @@
import { OutOfOfficeReason } from "@/modules/ooo/inputs/ooo.input";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import { IsInt, IsEnum, ValidateNested, IsString, IsDateString, IsOptional } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class UserOooOutputDto {
@IsInt()
@Expose()
@ApiProperty({
description: "The ID of the user.",
example: 2,
})
readonly userId!: number;
@IsInt()
@IsOptional()
@ApiPropertyOptional({
description: "The ID of the user covering for the out of office period, if applicable.",
example: 2,
})
@Expose()
readonly toUserId?: number;
@IsInt()
@Expose()
@ApiProperty({
description: "The ID of the ooo entry.",
example: 2,
})
readonly id!: number;
@IsString()
@Expose()
@ApiProperty({
description: "The UUID of the ooo entry.",
example: 2,
})
readonly uuid!: string;
@IsDateString()
@ApiProperty({
description: "The start date and time of the out of office period in ISO 8601 format in UTC timezone.",
example: "2023-05-01T00:00:00.000Z",
})
@Expose()
start!: Date;
@IsDateString()
@ApiProperty({
description: "The end date and time of the out of office period in ISO 8601 format in UTC timezone.",
example: "2023-05-10T23:59:59.999Z",
})
@Expose()
end!: Date;
@IsString()
@IsOptional()
@ApiPropertyOptional({
description: "Optional notes for the out of office entry.",
example: "Vacation in Hawaii",
})
@Expose()
notes?: string;
@IsEnum(OutOfOfficeReason)
@IsOptional()
@ApiPropertyOptional({
description: "the reason for the out of office entry, if applicable",
example: "vacation",
enum: OutOfOfficeReason,
})
@Expose()
reason?: OutOfOfficeReason;
}
export class UserOooOutputResponseDto {
@Expose()
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@Expose()
@ValidateNested()
@Type(() => UserOooOutputDto)
data!: UserOooOutputDto;
}
export class UserOoosOutputResponseDto {
@Expose()
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@Expose()
@ValidateNested()
@Type(() => UserOooOutputDto)
data!: UserOooOutputDto[];
}
@@ -0,0 +1,107 @@
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 { PrismaWriteService } from "../../prisma/prisma-write.service";
type OOOInputData = Omit<Prisma.OutOfOfficeEntryCreateInput, "user" | "toUser" | "reason" | "uuid"> & {
toUserId?: number;
userId: number;
reasonId?: number;
};
@Injectable()
export class UserOOORepository {
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
async createUserOOO(data: OOOInputData) {
const uuid = uuidv4();
return this.dbWrite.prisma.outOfOfficeEntry.create({
data: { ...data, uuid },
include: { reason: true },
});
}
async updateUserOOO(oooId: number, data: Partial<OOOInputData>) {
return this.dbWrite.prisma.outOfOfficeEntry.update({
where: { id: oooId },
data,
include: { reason: true },
});
}
async getUserOOOById(oooId: number) {
return this.dbRead.prisma.outOfOfficeEntry.findFirst({
where: { id: oooId },
include: { reason: true },
});
}
async getUserOOOByIdAndUserId(oooId: number, userId: number) {
return this.dbRead.prisma.outOfOfficeEntry.findFirst({
where: { id: oooId, userId },
include: { reason: true },
});
}
async getUserOOOPaginated(
userId: number,
skip: number,
take: number,
sort?: { sortStart?: "asc" | "desc"; sortEnd?: "asc" | "desc" }
) {
return this.dbRead.prisma.outOfOfficeEntry.findMany({
where: { userId },
skip,
take,
include: { reason: true },
...(sort?.sortStart && { orderBy: { start: sort.sortStart } }),
...(sort?.sortEnd && { orderBy: { end: sort.sortEnd } }),
});
}
async deleteUserOOO(oooId: number) {
return this.dbWrite.prisma.outOfOfficeEntry.delete({
where: { id: oooId },
include: { reason: true },
});
}
async findExistingOooRedirect(userId: number, start: Date, end: Date, toUserId?: number) {
const existingOutOfOfficeEntry = await this.dbRead.prisma.outOfOfficeEntry.findFirst({
select: {
userId: true,
toUserId: true,
},
where: {
...(toUserId && { userId: toUserId }),
toUserId: userId,
// Check for time overlap or collision
OR: [
// Outside of range
{
AND: [{ start: { lte: end } }, { end: { gte: start } }],
},
// Inside of range
{
AND: [{ start: { gte: start } }, { end: { lte: end } }],
},
],
},
});
return existingOutOfOfficeEntry;
}
async getOooByUserIdAndTime(userId: number, start: Date, end: Date) {
return await this.dbRead.prisma.outOfOfficeEntry.findFirst({
where: {
userId,
start,
end,
},
});
}
}
@@ -0,0 +1,142 @@
import {
CreateOutOfOfficeEntryDto,
UpdateOutOfOfficeEntryDto,
OutOfOfficeReason,
GetOutOfOfficeEntryFiltersDTO,
SortOrder,
} from "@/modules/ooo/inputs/ooo.input";
import { UserOOORepository } from "@/modules/ooo/repositories/ooo.repository";
import { UsersRepository } from "@/modules/users/users.repository";
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
import { OutOfOfficeEntry } from "@calcom/prisma/client";
const OOO_REASON_ID_TO_REASON = {
1: OutOfOfficeReason["UNSPECIFIED"],
2: OutOfOfficeReason["VACATION"],
3: OutOfOfficeReason["TRAVEL"],
4: OutOfOfficeReason["SICK_LEAVE"],
5: OutOfOfficeReason["PUBLIC_HOLIDAY"],
};
const OOO_REASON_TO_REASON_ID = {
[OutOfOfficeReason["UNSPECIFIED"]]: 1,
[OutOfOfficeReason["VACATION"]]: 2,
[OutOfOfficeReason["TRAVEL"]]: 3,
[OutOfOfficeReason["SICK_LEAVE"]]: 4,
[OutOfOfficeReason["PUBLIC_HOLIDAY"]]: 5,
};
@Injectable()
export class UserOOOService {
constructor(
private readonly oooRepository: UserOOORepository,
private readonly usersRepository: UsersRepository
) {}
formatOooReason(ooo: OutOfOfficeEntry) {
return {
...ooo,
reason: ooo.reasonId
? OOO_REASON_ID_TO_REASON[ooo.reasonId as keyof typeof OOO_REASON_ID_TO_REASON]
: OOO_REASON_ID_TO_REASON[1],
};
}
isStartBeforeEnd(start?: Date, end?: Date) {
if ((end && !start) || (start && !end)) {
throw new BadRequestException("Please specify both ooo start and end time.");
}
if (start && end) {
if (start.getTime() > end.getTime()) {
throw new BadRequestException("Start date must be before end date.");
}
}
return true;
}
async checkUserEligibleForRedirect(userId: number, toUserId?: number) {
if (toUserId) {
const user = await this.usersRepository.findUserOOORedirectEligible(userId, toUserId);
if (!user) {
throw new BadRequestException("Cannot redirect to this user.");
}
}
}
async checkExistingOooRedirect(userId: number, start?: Date, end?: Date, toUserId?: number) {
if (start && end) {
const existingOooRedirect = await this.oooRepository.findExistingOooRedirect(
userId,
start,
end,
toUserId
);
if (existingOooRedirect) {
throw new BadRequestException("Booking redirect infinite not allowed.");
}
}
}
async checkDuplicateOOOEntry(userId: number, start?: Date, end?: Date) {
if (start && end) {
const duplicateEntry = await this.oooRepository.getOooByUserIdAndTime(userId, start, end);
if (duplicateEntry) {
throw new ConflictException("Ooo entry already exists.");
}
}
}
checkRedirectToSelf(userId: number, toUserId?: number) {
if (toUserId && toUserId === userId) {
throw new BadRequestException("Cannot redirect to self.");
}
}
async checkIsValidOOO(userId: number, ooo: CreateOutOfOfficeEntryDto | UpdateOutOfOfficeEntryDto) {
this.isStartBeforeEnd(ooo.start, ooo.end);
await this.checkExistingOooRedirect(userId, ooo.start, ooo.end, ooo.toUserId);
await this.checkDuplicateOOOEntry(userId, ooo.start, ooo.end);
await this.checkRedirectToSelf(userId, ooo.toUserId);
await this.checkUserEligibleForRedirect(userId, ooo.toUserId);
}
async createUserOOO(userId: number, body: CreateOutOfOfficeEntryDto) {
await this.checkIsValidOOO(userId, body);
const { reason, ...rest } = body;
const ooo = await this.oooRepository.createUserOOO({
...rest,
userId,
reasonId: OOO_REASON_TO_REASON_ID[reason ?? OutOfOfficeReason["UNSPECIFIED"]],
});
return this.formatOooReason(ooo);
}
async updateUserOOO(userId: number, oooId: number, body: UpdateOutOfOfficeEntryDto) {
await this.checkIsValidOOO(userId, body);
const { reason, ...rest } = body;
const data = reason
? { ...rest, reasonId: OOO_REASON_TO_REASON_ID[reason ?? OutOfOfficeReason["UNSPECIFIED"]] }
: rest;
const ooo = await this.oooRepository.updateUserOOO(oooId, data);
return this.formatOooReason(ooo);
}
async deleteUserOOO(oooId: number) {
const ooo = await this.oooRepository.deleteUserOOO(oooId);
return this.formatOooReason(ooo);
}
async getUserOOOPaginated(
userId: number,
skip: number,
take: number,
sort?: { sortStart?: "asc" | "desc"; sortEnd?: "asc" | "desc" }
) {
const ooos = await this.oooRepository.getUserOOOPaginated(userId, skip, take, sort);
return ooos.map((ooo) => this.formatOooReason(ooo));
}
}
@@ -1,6 +1,5 @@
import { CreatePhoneCallInput } from "@/ee/event-types/event-types_2024_06_14/inputs/create-phone-call.input";
import { CreatePhoneCallOutput } from "@/ee/event-types/event-types_2024_06_14/outputs/create-phone-call.output";
import { InputEventTypesService_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/services/input-event-types.service";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { PlatformPlan } from "@/modules/auth/decorators/billing/platform-plan.decorator";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
@@ -11,15 +10,15 @@ import { IsAdminAPIEnabledGuard } from "@/modules/auth/guards/organizations/is-a
import { IsOrgGuard } from "@/modules/auth/guards/organizations/is-org.guard";
import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard";
import { IsTeamInOrg } from "@/modules/auth/guards/teams/is-team-in-org.guard";
import { CreateTeamEventTypeOutput } from "@/modules/organizations/controllers/event-types/outputs/teams/create-team-event-type.output";
import { DeleteTeamEventTypeOutput } from "@/modules/organizations/controllers/event-types/outputs/teams/delete-team-event-type.output";
import { GetTeamEventTypeOutput } from "@/modules/organizations/controllers/event-types/outputs/teams/get-team-event-type.output";
import { GetTeamEventTypesOutput } from "@/modules/organizations/controllers/event-types/outputs/teams/get-team-event-types.output";
import { UpdateTeamEventTypeOutput } from "@/modules/organizations/controllers/event-types/outputs/teams/update-team-event-type.output";
import { OutputTeamEventTypesResponsePipe } from "@/modules/organizations/controllers/pipes/event-types/team-event-types-response.transformer";
import { InputOrganizationsEventTypesService } from "@/modules/organizations/services/event-types/input.service";
import { OrganizationsEventTypesService } from "@/modules/organizations/services/event-types/organizations-event-types.service";
import { DatabaseTeamEventType } from "@/modules/organizations/services/event-types/output.service";
import { CreateTeamEventTypeOutput } from "@/modules/teams/event-types/outputs/create-team-event-type.output";
import { DeleteTeamEventTypeOutput } from "@/modules/teams/event-types/outputs/delete-team-event-type.output";
import { GetTeamEventTypeOutput } from "@/modules/teams/event-types/outputs/get-team-event-type.output";
import { GetTeamEventTypesOutput } from "@/modules/teams/event-types/outputs/get-team-event-types.output";
import { UpdateTeamEventTypeOutput } from "@/modules/teams/event-types/outputs/update-team-event-type.output";
import { UserWithProfile } from "@/modules/users/users.repository";
import {
Controller,
@@ -62,7 +61,6 @@ export class OrganizationsEventTypesController {
constructor(
private readonly organizationsEventTypesService: OrganizationsEventTypesService,
private readonly inputService: InputOrganizationsEventTypesService,
private readonly inputUserEventTypesService: InputEventTypesService_2024_06_14,
private readonly outputTeamEventTypesResponsePipe: OutputTeamEventTypesResponsePipe
) {}
@@ -180,7 +178,11 @@ export class OrganizationsEventTypesController {
@Query() queryParams: SkipTakePagination
): Promise<GetTeamEventTypesOutput> {
const { skip, take } = queryParams;
const eventTypes = await this.organizationsEventTypesService.getTeamsEventTypes(orgId, skip, take);
const eventTypes = await this.organizationsEventTypesService.getOrganizationsTeamsEventTypes(
orgId,
skip,
take
);
return {
status: SUCCESS_STATUS,
@@ -577,6 +577,100 @@ describe("Organizations Event Types Endpoints", () => {
});
});
it("should be able to configure phone-only event type", async () => {
const body: UpdateTeamEventTypeInput_2024_06_14 = {
bookingFields: [
{
type: "email",
required: false,
label: "Email",
},
{
type: "phone",
slug: "attendeePhoneNumber",
required: true,
label: "Phone number",
hidden: true,
},
],
};
return request(app.getHttpServer())
.patch(`/v2/organizations/${org.id}/teams/${team.id}/event-types/${collectiveEventType.id}`)
.send(body)
.expect(200)
.then(async (response) => {
const responseBody: ApiSuccessResponse<TeamEventTypeOutput_2024_06_14> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data;
expect(data.bookingFields).toEqual([
{
isDefault: true,
type: "name",
slug: "name",
required: true,
disableOnPrefill: false,
},
{
isDefault: true,
type: "email",
slug: "email",
required: false,
label: "Email",
disableOnPrefill: false,
},
{
isDefault: true,
type: "radioInput",
slug: "location",
required: false,
hidden: false,
},
{
isDefault: true,
type: "phone",
slug: "attendeePhoneNumber",
required: true,
hidden: true,
label: "Phone number",
disableOnPrefill: false,
},
{
isDefault: true,
type: "text",
slug: "title",
required: true,
disableOnPrefill: false,
hidden: true,
},
{
isDefault: true,
type: "textarea",
slug: "notes",
required: false,
disableOnPrefill: false,
hidden: false,
},
{
isDefault: true,
type: "multiemail",
slug: "guests",
required: false,
disableOnPrefill: false,
hidden: false,
},
{
isDefault: true,
type: "textarea",
slug: "rescheduleReason",
required: false,
disableOnPrefill: false,
hidden: false,
},
]);
});
});
it("should assign all members to managed event-type", async () => {
const body: UpdateTeamEventTypeInput_2024_06_14 = {
assignAllTeamMembers: true,
@@ -677,53 +771,54 @@ describe("Organizations Event Types Endpoints", () => {
const fetchedEventType = responseBody.data;
expect(fetchedEventType.bookingFields).toEqual([
{ isDefault: true, required: true, slug: "name", type: "name", disableOnPrefill: false },
{ isDefault: true, required: true, slug: "email", type: "email", disableOnPrefill: false },
{
disableOnPrefill: false,
isDefault: true,
type: "name",
slug: "name",
required: true,
},
{
isDefault: true,
type: "email",
slug: "email",
required: true,
},
{
isDefault: true,
required: false,
slug: "attendeePhoneNumber",
type: "phone",
slug: "attendeePhoneNumber",
required: false,
hidden: true,
},
{
isDefault: true,
type: "radioInput",
slug: "location",
required: false,
hidden: false,
},
{
isDefault: true,
type: "text",
slug: "title",
required: true,
slug: "title",
type: "text",
disableOnPrefill: false,
hidden: true,
},
{
isDefault: true,
type: "textarea",
required: false,
slug: "notes",
required: false,
},
{
isDefault: true,
type: "multiemail",
slug: "guests",
required: false,
},
{
isDefault: true,
type: "textarea",
slug: "rescheduleReason",
disableOnPrefill: false,
hidden: false,
},
{
isDefault: true,
required: false,
slug: "guests",
type: "multiemail",
disableOnPrefill: false,
hidden: false,
},
{
isDefault: true,
required: false,
slug: "rescheduleReason",
type: "textarea",
disableOnPrefill: false,
hidden: false,
},
]);
});
@@ -15,8 +15,8 @@ import {
OrgTeamMembershipsOutputResponseDto,
OrgTeamMembershipOutputResponseDto,
} from "@/modules/organizations/outputs/organization-teams-memberships.output";
import { OrganizationsEventTypesService } from "@/modules/organizations/services/event-types/organizations-event-types.service";
import { OrganizationsTeamsMembershipsService } from "@/modules/organizations/services/organizations-teams-memberships.service";
import { TeamsEventTypesService } from "@/modules/teams/event-types/services/teams-event-types.service";
import {
Controller,
UseGuards,
@@ -51,7 +51,7 @@ export class OrganizationsTeamsMembershipsController {
constructor(
private organizationsTeamsMembershipsService: OrganizationsTeamsMembershipsService,
private oganizationsEventTypesService: OrganizationsEventTypesService,
private teamsEventTypesService: TeamsEventTypesService,
private readonly organizationsRepository: OrganizationsRepository
) {}
@@ -119,7 +119,7 @@ export class OrganizationsTeamsMembershipsController {
membershipId
);
await this.oganizationsEventTypesService.deleteUserTeamEventTypesAndHosts(membership.userId, teamId);
await this.teamsEventTypesService.deleteUserTeamEventTypesAndHosts(membership.userId, teamId);
return {
status: SUCCESS_STATUS,
@@ -0,0 +1,142 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { PlatformPlan } from "@/modules/auth/decorators/billing/platform-plan.decorator";
import { Roles } from "@/modules/auth/decorators/roles/roles.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { PlatformPlanGuard } from "@/modules/auth/guards/billing/platform-plan.guard";
import { IsAdminAPIEnabledGuard } from "@/modules/auth/guards/organizations/is-admin-api-enabled.guard";
import { IsOrgGuard } from "@/modules/auth/guards/organizations/is-org.guard";
import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard";
import { IsUserInOrg } from "@/modules/auth/guards/users/is-user-in-org.guard";
import { IsUserOOO } from "@/modules/ooo/guards/is-user-ooo";
import {
CreateOutOfOfficeEntryDto,
UpdateOutOfOfficeEntryDto,
GetOutOfOfficeEntryFiltersDTO,
GetOrgUsersOutOfOfficeEntryFiltersDTO,
} from "@/modules/ooo/inputs/ooo.input";
import {
UserOooOutputDto,
UserOooOutputResponseDto,
UserOoosOutputResponseDto,
} from "@/modules/ooo/outputs/ooo.output";
import { UserOOOService } from "@/modules/ooo/services/ooo.service";
import { OrgUsersOOOService } from "@/modules/organizations/controllers/users/ooo/services/organization-users-ooo.service";
import {
Controller,
UseGuards,
Get,
Post,
Patch,
Delete,
Param,
ParseIntPipe,
Body,
UseInterceptors,
Query,
} from "@nestjs/common";
import { ClassSerializerInterceptor } from "@nestjs/common";
import { ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { plainToInstance } from "class-transformer";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
@Controller({
path: "/v2/organizations/:orgId",
version: API_VERSIONS_VALUES,
})
@UseInterceptors(ClassSerializerInterceptor)
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, PlatformPlanGuard, IsAdminAPIEnabledGuard)
@UseGuards(IsOrgGuard)
@DocsTags("Orgs / Users / OOO")
export class OrganizationsUsersOOOController {
constructor(
private readonly userOOOService: UserOOOService,
private readonly orgUsersOOOService: OrgUsersOOOService
) {}
@Get("/users/:userId/ooo")
@Roles("ORG_ADMIN")
@PlatformPlan("ESSENTIALS")
@UseGuards(IsUserInOrg)
@ApiOperation({ summary: "Get all ooo entries of a user" })
async getOrganizationUserOOO(
@Param("userId", ParseIntPipe) userId: number,
@Query() query: GetOutOfOfficeEntryFiltersDTO
): Promise<UserOoosOutputResponseDto> {
const { skip, take, ...rest } = query ?? { skip: 0, take: 250 };
const ooos = await this.userOOOService.getUserOOOPaginated(userId, skip ?? 0, take ?? 250, rest);
return {
status: SUCCESS_STATUS,
data: ooos.map((ooo) => plainToInstance(UserOooOutputDto, ooo, { strategy: "excludeAll" })),
};
}
@Post("/users/:userId/ooo")
@Roles("ORG_ADMIN")
@PlatformPlan("ESSENTIALS")
@UseGuards(IsUserInOrg)
@ApiOperation({ summary: "Create an ooo entry for user" })
async createOrganizationUserOOO(
@Param("userId", ParseIntPipe) userId: number,
@Body() input: CreateOutOfOfficeEntryDto
): Promise<UserOooOutputResponseDto> {
const ooo = await this.userOOOService.createUserOOO(userId, input);
return {
status: SUCCESS_STATUS,
data: plainToInstance(UserOooOutputDto, ooo, { strategy: "excludeAll" }),
};
}
@Patch("/users/:userId/ooo/:oooId")
@Roles("ORG_ADMIN")
@PlatformPlan("ESSENTIALS")
@UseGuards(IsUserInOrg, IsUserOOO)
@ApiOperation({ summary: "Update ooo entry of a user" })
async updateOrganizationUserOOO(
@Param("userId", ParseIntPipe) userId: number,
@Param("oooId", ParseIntPipe) oooId: number,
@Body() input: UpdateOutOfOfficeEntryDto
): Promise<UserOooOutputResponseDto> {
const ooo = await this.userOOOService.updateUserOOO(userId, oooId, input);
return {
status: SUCCESS_STATUS,
data: plainToInstance(UserOooOutputDto, ooo, { strategy: "excludeAll" }),
};
}
@Delete("/users/:userId/ooo/:oooId")
@Roles("ORG_ADMIN")
@PlatformPlan("ESSENTIALS")
@UseGuards(IsUserInOrg, IsUserOOO)
@ApiOperation({ summary: "Delete ooo entry of a user" })
async deleteOrganizationUserOOO(
@Param("oooId", ParseIntPipe) oooId: number
): Promise<UserOooOutputResponseDto> {
const ooo = await this.userOOOService.deleteUserOOO(oooId);
return {
status: SUCCESS_STATUS,
data: plainToInstance(UserOooOutputDto, ooo, { strategy: "excludeAll" }),
};
}
@Get("/ooo")
@Roles("ORG_ADMIN")
@PlatformPlan("ESSENTIALS")
@ApiOperation({ summary: "Get all OOO entries of org users" })
async getOrganizationUsersOOO(
@Param("orgId", ParseIntPipe) orgId: number,
@Query() query: GetOrgUsersOutOfOfficeEntryFiltersDTO
): Promise<UserOoosOutputResponseDto> {
const { skip, take, email, ...rest } = query ?? { skip: 0, take: 250 };
const ooos = await this.orgUsersOOOService.getOrgUsersOOOPaginated(orgId, skip ?? 0, take ?? 250, rest, {
email,
});
return {
status: SUCCESS_STATUS,
data: ooos.map((ooo) => plainToInstance(UserOooOutputDto, ooo, { strategy: "excludeAll" })),
};
}
}
@@ -0,0 +1,445 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { UserOooOutputDto } from "@/modules/ooo/outputs/ooo.output";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
import { INestApplication } from "@nestjs/common";
import { NestExpressApplication } from "@nestjs/platform-express";
import { Test } from "@nestjs/testing";
import { User } from "@prisma/client";
import * as request from "supertest";
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
import { OrganizationRepositoryFixture } from "test/fixtures/repository/organization.repository.fixture";
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
import { withApiAuth } from "test/utils/withApiAuth";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { Team } from "@calcom/prisma/client";
describe("Organizations User OOO Endpoints", () => {
describe("User Authentication - User is Org Admin", () => {
let app: INestApplication;
let oooCreatedViaApiId: number;
let userRepositoryFixture: UserRepositoryFixture;
let organizationsRepositoryFixture: OrganizationRepositoryFixture;
let teamsRepositoryFixture: TeamRepositoryFixture;
let membershipsRepositoryFixture: MembershipRepositoryFixture;
let profileRepositoryFixture: ProfileRepositoryFixture;
let org: Team;
let team: Team;
let falseTestOrg: Team;
let falseTestTeam: Team;
const userEmail = "org-admin-ooo-controller-e222e@api.com";
let userAdmin: User;
const teammate1Email = "teammate111ooo@team.com";
const teammate2Email = "teammate221ooo@team.com";
const falseTestUserEmail = "false-user-ooo@false-team.com";
let teammate1: User;
let teammate2: User;
let falseTestUser: User;
beforeAll(async () => {
const moduleRef = await withApiAuth(
userEmail,
Test.createTestingModule({
imports: [AppModule, PrismaModule, UsersModule, TokensModule],
})
).compile();
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);
teamsRepositoryFixture = new TeamRepositoryFixture(moduleRef);
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
profileRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
userAdmin = await userRepositoryFixture.create({
email: userEmail,
username: userEmail,
role: "ADMIN",
});
teammate1 = await userRepositoryFixture.create({
email: teammate1Email,
username: teammate1Email,
});
teammate2 = await userRepositoryFixture.create({
email: teammate2Email,
username: teammate2Email,
});
falseTestUser = await userRepositoryFixture.create({
email: falseTestUserEmail,
username: falseTestUserEmail,
});
org = await organizationsRepositoryFixture.create({
name: "Test Organization ooo",
isOrganization: true,
});
falseTestOrg = await organizationsRepositoryFixture.create({
name: "False test org ooo",
isOrganization: true,
});
team = await teamsRepositoryFixture.create({
name: "Test org team ooo",
isOrganization: false,
parent: { connect: { id: org.id } },
});
falseTestTeam = await teamsRepositoryFixture.create({
name: "Outside org team ooo",
isOrganization: false,
parent: { connect: { id: falseTestOrg.id } },
});
await profileRepositoryFixture.create({
uid: `usr-${userAdmin.id}`,
username: userEmail,
organization: {
connect: {
id: org.id,
},
},
user: {
connect: {
id: userAdmin.id,
},
},
});
await profileRepositoryFixture.create({
uid: `usr-${teammate1.id}`,
username: teammate1Email,
organization: {
connect: {
id: org.id,
},
},
user: {
connect: {
id: teammate1.id,
},
},
});
await membershipsRepositoryFixture.create({
role: "ADMIN",
user: { connect: { id: userAdmin.id } },
team: { connect: { id: org.id } },
accepted: true,
});
await membershipsRepositoryFixture.create({
role: "MEMBER",
user: { connect: { id: teammate1.id } },
team: { connect: { id: team.id } },
accepted: true,
});
await membershipsRepositoryFixture.create({
role: "MEMBER",
user: { connect: { id: teammate2.id } },
team: { connect: { id: team.id } },
accepted: true,
});
await membershipsRepositoryFixture.create({
role: "MEMBER",
user: { connect: { id: falseTestUser.id } },
team: { connect: { id: falseTestTeam.id } },
accepted: true,
});
app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication);
await app.init();
});
it("should be defined", () => {
expect(userRepositoryFixture).toBeDefined();
expect(organizationsRepositoryFixture).toBeDefined();
expect(userAdmin).toBeDefined();
expect(org).toBeDefined();
});
it("should create a ooo entry without redirect", async () => {
const body = {
start: "2025-05-01T01:00:00.000Z",
end: "2025-05-10T13:59:59.999Z",
notes: "ooo numero uno",
};
return request(app.getHttpServer())
.post(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo`)
.send(body)
.expect(201)
.then((response) => {
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data as UserOooOutputDto;
expect(data.reason).toEqual("unspecified");
expect(data.userId).toEqual(teammate1.id);
expect(data.start).toEqual("2025-05-01T00:00:00.000Z");
expect(data.end).toEqual("2025-05-10T23:59:59.999Z");
oooCreatedViaApiId = data.id;
});
});
it("should create a ooo entry with redirect", async () => {
const body = {
start: "2025-08-01T01:00:00.000Z",
end: "2025-10-10T13:59:59.999Z",
notes: "ooo numero dos with redirect",
toUserId: teammate2.id,
};
return request(app.getHttpServer())
.post(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo`)
.send(body)
.expect(201)
.then((response) => {
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data as UserOooOutputDto;
expect(data.reason).toEqual("unspecified");
expect(data.userId).toEqual(teammate1.id);
expect(data.start).toEqual("2025-08-01T00:00:00.000Z");
expect(data.end).toEqual("2025-10-10T23:59:59.999Z");
expect(data.toUserId).toEqual(teammate2.id);
});
});
it("should fail to create a ooo entry with start after end", async () => {
const body = {
start: "2025-07-01T00:00:00.000Z",
end: "2025-05-10T23:59:59.999Z",
notes: "ooo numero uno duplicate",
};
return request(app.getHttpServer())
.post(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo`)
.send(body)
.expect(400);
});
it("should fail to create a duplicate ooo entry", async () => {
const body = {
start: "2025-05-01T00:00:00.000Z",
end: "2025-05-10T23:59:59.999Z",
notes: "ooo numero uno duplicate",
};
return request(app.getHttpServer())
.post(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo`)
.send(body)
.expect(409);
});
it("should fail to create an ooo entry that redirects to self", async () => {
const body = {
start: "2025-05-02T00:00:00.000Z",
end: "2025-05-03T23:59:59.999Z",
notes: "ooo infinite redirect",
toUserId: teammate1.id,
};
return request(app.getHttpServer())
.post(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo`)
.send(body)
.expect(400);
});
it("should fail to create an ooo entry that redirects to member outside of org", async () => {
const body = {
start: "2025-05-02T00:00:00.000Z",
end: "2025-05-03T23:59:59.999Z",
notes: "ooo invalid redirect",
toUserId: falseTestUser.id,
};
return request(app.getHttpServer())
.post(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo`)
.send(body)
.expect(400);
});
it("should update a ooo entry without redirect", async () => {
const body = {
start: "2025-06-01T01:00:00.000Z",
end: "2025-06-10T13:59:59.999Z",
notes: "ooo numero uno",
reason: "vacation",
};
return request(app.getHttpServer())
.patch(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo/${oooCreatedViaApiId}`)
.send(body)
.expect(200)
.then((response) => {
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data as UserOooOutputDto;
expect(data.reason).toEqual("vacation");
expect(data.userId).toEqual(teammate1.id);
expect(data.start).toEqual("2025-06-01T00:00:00.000Z");
expect(data.end).toEqual("2025-06-10T23:59:59.999Z");
});
});
it("should fail to update a ooo entry with redirect outside of org", async () => {
const body = {
toUserId: falseTestUser.id,
};
return request(app.getHttpServer())
.patch(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo/${oooCreatedViaApiId}`)
.send(body)
.expect(400);
});
it("should fail to update a ooo entry with start after end ", async () => {
const body = {
start: "2025-07-01T00:00:00.000Z",
end: "2025-05-10T23:59:59.999Z",
};
return request(app.getHttpServer())
.patch(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo/${oooCreatedViaApiId}`)
.send(body)
.expect(400);
});
it("should fail to update a ooo entry with redirect to self ", async () => {
const body = {
toUserId: teammate1.id,
};
return request(app.getHttpServer())
.patch(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo/${oooCreatedViaApiId}`)
.send(body)
.expect(400);
});
it("should fail to update a ooo entry with duplicate time", async () => {
const body = {
start: "2025-06-01T01:00:00.000Z",
end: "2025-06-10T13:59:59.999Z",
};
return request(app.getHttpServer())
.patch(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo/${oooCreatedViaApiId}`)
.send(body)
.expect(409);
});
it("should update a ooo entry without redirect", async () => {
const body = {
toUserId: teammate2.id,
};
return request(app.getHttpServer())
.patch(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo/${oooCreatedViaApiId}`)
.send(body)
.expect(200)
.then((response) => {
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data as UserOooOutputDto;
expect(data.reason).toEqual("vacation");
expect(data.toUserId).toEqual(teammate2.id);
expect(data.userId).toEqual(teammate1.id);
expect(data.start).toEqual("2025-06-01T00:00:00.000Z");
expect(data.end).toEqual("2025-06-10T23:59:59.999Z");
});
});
it("should get 2 ooo entries", async () => {
return request(app.getHttpServer())
.get(`/v2/organizations/${org.id}/ooo?sortEnd=desc&email=${teammate1Email}`)
.expect(200)
.then((response) => {
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data as UserOooOutputDto[];
expect(data.length).toEqual(2);
const oooUno = data.find((ooo) => ooo.id === oooCreatedViaApiId);
expect(oooUno).toBeDefined();
if (oooUno) {
expect(oooUno.reason).toEqual("vacation");
expect(oooUno.toUserId).toEqual(teammate2.id);
expect(oooUno.userId).toEqual(teammate1.id);
expect(oooUno.start).toEqual("2025-06-01T00:00:00.000Z");
expect(oooUno.end).toEqual("2025-06-10T23:59:59.999Z");
}
// test sort
expect(data[1].id).toEqual(oooCreatedViaApiId);
});
});
it("should get 2 ooo entries", async () => {
return request(app.getHttpServer())
.get(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo`)
.expect(200)
.then((response) => {
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data as UserOooOutputDto[];
expect(data.length).toEqual(2);
const oooUno = data.find((ooo) => ooo.id === oooCreatedViaApiId);
expect(oooUno).toBeDefined();
if (oooUno) {
expect(oooUno.reason).toEqual("vacation");
expect(oooUno.toUserId).toEqual(teammate2.id);
expect(oooUno.userId).toEqual(teammate1.id);
expect(oooUno.start).toEqual("2025-06-01T00:00:00.000Z");
expect(oooUno.end).toEqual("2025-06-10T23:59:59.999Z");
}
});
});
it("should delete ooo entry", async () => {
return request(app.getHttpServer())
.delete(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo/${oooCreatedViaApiId}`)
.expect(200);
});
it("user should have 1 ooo entries", async () => {
return request(app.getHttpServer())
.get(`/v2/organizations/${org.id}/users/${teammate1.id}/ooo`)
.expect(200)
.then((response) => {
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data as UserOooOutputDto[];
expect(data.length).toEqual(1);
});
});
afterAll(async () => {
await userRepositoryFixture.deleteByEmail(userAdmin.email);
await userRepositoryFixture.deleteByEmail(teammate1.email);
await userRepositoryFixture.deleteByEmail(teammate2.email);
await userRepositoryFixture.deleteByEmail(falseTestUser.email);
await teamsRepositoryFixture.delete(team.id);
await teamsRepositoryFixture.delete(falseTestTeam.id);
await organizationsRepositoryFixture.delete(org.id);
await organizationsRepositoryFixture.delete(falseTestOrg.id);
await app.close();
});
});
});
@@ -0,0 +1,33 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { Injectable } from "@nestjs/common";
@Injectable()
export class OrgUsersOOORepository {
constructor(private readonly dbRead: PrismaReadService) {}
async getOrgUsersOOOPaginated(
orgId: number,
skip: number,
take: number,
sort?: { sortStart?: "asc" | "desc"; sortEnd?: "asc" | "desc" },
filters?: { email?: string }
) {
console.log({ sort, filters });
return this.dbRead.prisma.outOfOfficeEntry.findMany({
where: {
user: {
...(filters?.email && { email: filters.email }),
profiles: {
some: {
organizationId: orgId,
},
},
},
},
skip,
take,
include: { reason: true },
...(sort?.sortStart && { orderBy: { start: sort.sortStart } }),
...(sort?.sortEnd && { orderBy: { end: sort.sortEnd } }),
});
}
}
@@ -0,0 +1,26 @@
import { UserOOORepository } from "@/modules/ooo/repositories/ooo.repository";
import { UserOOOService } from "@/modules/ooo/services/ooo.service";
import { OrgUsersOOORepository } from "@/modules/organizations/controllers/users/ooo/repositories/organizations-users-ooo.repository";
import { UsersRepository } from "@/modules/users/users.repository";
import { Injectable } from "@nestjs/common";
@Injectable()
export class OrgUsersOOOService {
constructor(
private readonly oooRepository: UserOOORepository,
private readonly oooUserService: UserOOOService,
private readonly usersRepository: UsersRepository,
private readonly orgUsersOOORepository: OrgUsersOOORepository
) {}
async getOrgUsersOOOPaginated(
orgId: number,
skip: number,
take: number,
sort?: { sortStart?: "asc" | "desc"; sortEnd?: "asc" | "desc" },
filters?: { email?: string }
) {
const ooos = await this.orgUsersOOORepository.getOrgUsersOOOPaginated(orgId, skip, take, sort, filters);
return ooos.map((ooo) => this.oooUserService.formatOooReason(ooo));
}
}
@@ -3,6 +3,8 @@ import { SchedulesModule_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/
import { EmailModule } from "@/modules/email/email.module";
import { EmailService } from "@/modules/email/email.service";
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
import { UserOOORepository } from "@/modules/ooo/repositories/ooo.repository";
import { UserOOOService } from "@/modules/ooo/services/ooo.service";
import { OrganizationsOptionsAttributesController } from "@/modules/organizations/controllers/attributes/organizations-attributes-options.controller";
import { OrganizationsAttributesController } from "@/modules/organizations/controllers/attributes/organizations-attributes.controller";
import { OrganizationsEventTypesController } from "@/modules/organizations/controllers/event-types/organizations-event-types.controller";
@@ -12,6 +14,9 @@ import { OrganizationsSchedulesController } from "@/modules/organizations/contro
import { OrganizationsTeamsMembershipsController } from "@/modules/organizations/controllers/teams/memberships/organizations-teams-memberships.controller";
import { OrganizationsTeamsController } from "@/modules/organizations/controllers/teams/organizations-teams.controller";
import { OrganizationsTeamsSchedulesController } from "@/modules/organizations/controllers/teams/schedules/organizations-teams-schedules.controller";
import { OrganizationsUsersOOOController } from "@/modules/organizations/controllers/users/ooo/organizations-users-ooo-controller";
import { OrgUsersOOORepository } from "@/modules/organizations/controllers/users/ooo/repositories/organizations-users-ooo.repository";
import { OrgUsersOOOService } from "@/modules/organizations/controllers/users/ooo/services/organization-users-ooo.service";
import { OrganizationsUsersController } from "@/modules/organizations/controllers/users/organizations-users.controller";
import { OrganizationsWebhooksController } from "@/modules/organizations/controllers/webhooks/organizations-webhooks.controller";
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
@@ -39,6 +44,7 @@ import { OrganizationsService } from "@/modules/organizations/services/organizat
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { RedisModule } from "@/modules/redis/redis.module";
import { StripeModule } from "@/modules/stripe/stripe.module";
import { TeamsEventTypesModule } from "@/modules/teams/event-types/teams-event-types.module";
import { TeamsModule } from "@/modules/teams/teams/teams.module";
import { UsersModule } from "@/modules/users/users.module";
import { WebhooksService } from "@/modules/webhooks/services/webhooks.service";
@@ -54,6 +60,7 @@ import { Module } from "@nestjs/common";
RedisModule,
EmailModule,
EventTypesModule_2024_06_14,
TeamsEventTypesModule,
TeamsModule,
],
providers: [
@@ -84,6 +91,10 @@ import { Module } from "@nestjs/common";
WebhooksRepository,
WebhooksService,
OutputTeamEventTypesResponsePipe,
UserOOOService,
UserOOORepository,
OrgUsersOOOService,
OrgUsersOOORepository,
],
exports: [
OrganizationsService,
@@ -116,6 +127,7 @@ import { Module } from "@nestjs/common";
OrganizationsOptionsAttributesController,
OrganizationsWebhooksController,
OrganizationsTeamsSchedulesController,
OrganizationsUsersOOOController,
],
})
export class OrganizationsModule {}
@@ -1,91 +1,10 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
@Injectable()
export class OrganizationsEventTypesRepository {
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
async getTeamEventType(teamId: number, eventTypeId: number) {
return this.dbRead.prisma.eventType.findUnique({
where: {
id: eventTypeId,
teamId,
},
include: { users: true, schedule: true, hosts: true, destinationCalendar: true },
});
}
async getTeamEventTypeBySlug(teamId: number, eventTypeSlug: string) {
return this.dbRead.prisma.eventType.findUnique({
where: {
teamId_slug: {
teamId,
slug: eventTypeSlug,
},
},
include: {
users: true,
schedule: true,
hosts: true,
destinationCalendar: true,
team: {
select: {
bannerUrl: true,
name: true,
logoUrl: true,
slug: true,
weekStart: true,
brandColor: true,
darkBrandColor: true,
theme: true,
},
},
},
});
}
async getTeamEventTypes(teamId: number) {
return this.dbRead.prisma.eventType.findMany({
where: {
teamId,
},
include: {
users: true,
schedule: true,
hosts: true,
destinationCalendar: true,
team: {
select: {
bannerUrl: true,
name: true,
logoUrl: true,
slug: true,
weekStart: true,
brandColor: true,
darkBrandColor: true,
theme: true,
},
},
},
});
}
async getEventTypeById(eventTypeId: number) {
return this.dbRead.prisma.eventType.findUnique({
where: { id: eventTypeId },
include: { users: true, schedule: true, hosts: true, destinationCalendar: true },
});
}
async getEventTypeChildren(eventTypeId: number) {
return this.dbRead.prisma.eventType.findMany({
where: { parentId: eventTypeId },
include: { users: true, schedule: true, hosts: true, destinationCalendar: true },
});
}
async getTeamsEventTypes(orgId: number, skip: number, take: number) {
constructor(private readonly dbRead: PrismaReadService) {}
async getOrganizationTeamsEventTypes(orgId: number, skip: number, take: number) {
return this.dbRead.prisma.eventType.findMany({
where: {
team: {
@@ -97,33 +16,4 @@ export class OrganizationsEventTypesRepository {
include: { users: true, schedule: true, hosts: true, destinationCalendar: true },
});
}
async getEventTypeByIdWithChildren(eventTypeId: number) {
return this.dbRead.prisma.eventType.findUnique({
where: { id: eventTypeId },
include: { children: true },
});
}
async deleteUserManagedTeamEventTypes(userId: number, teamId: number) {
return this.dbWrite.prisma.eventType.deleteMany({
where: {
parent: {
teamId,
},
userId,
},
});
}
async removeUserFromTeamEventTypesHosts(userId: number, teamId: number) {
return this.dbWrite.prisma.host.deleteMany({
where: {
userId,
eventType: {
teamId,
},
},
});
}
}
@@ -1,5 +1,5 @@
import { InputEventTypesService_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/services/input-event-types.service";
import { OrganizationsEventTypesRepository } from "@/modules/organizations/repositories/organizations-event-types.repository";
import { TeamsEventTypesRepository } from "@/modules/teams/event-types/teams-event-types.repository";
import { TeamsRepository } from "@/modules/teams/teams/teams.repository";
import { UsersRepository } from "@/modules/users/users.repository";
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
@@ -17,7 +17,7 @@ export class InputOrganizationsEventTypesService {
private readonly inputEventTypesService: InputEventTypesService_2024_06_14,
private readonly teamsRepository: TeamsRepository,
private readonly usersRepository: UsersRepository,
private readonly orgEventTypesRepository: OrganizationsEventTypesRepository
private readonly teamsEventTypesRepository: TeamsEventTypesRepository
) {}
async transformAndValidateCreateTeamEventTypeInput(
userId: number,
@@ -115,7 +115,7 @@ export class InputOrganizationsEventTypesService {
const { hosts, assignAllTeamMembers, ...rest } = inputEventType;
const eventType = await this.inputEventTypesService.transformInputUpdateEventType(rest, eventTypeId);
const dbEventType = await this.orgEventTypesRepository.getTeamEventType(teamId, eventTypeId);
const dbEventType = await this.teamsEventTypesRepository.getTeamEventType(teamId, eventTypeId);
if (!dbEventType) {
throw new BadRequestException("Event type to update not found");
@@ -144,7 +144,7 @@ export class InputOrganizationsEventTypesService {
) {
let eventType = null;
if (eventTypeId) {
eventType = await this.orgEventTypesRepository.getEventTypeByIdWithChildren(eventTypeId);
eventType = await this.teamsEventTypesRepository.getEventTypeByIdWithChildren(eventTypeId);
if (!eventType || eventType.schedulingType !== "MANAGED") {
return undefined;
}
@@ -1,14 +1,13 @@
import { EventTypesRepository_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.repository";
import { EventTypesService_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/services/event-types.service";
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
import { OrganizationsEventTypesRepository } from "@/modules/organizations/repositories/organizations-event-types.repository";
import { DatabaseTeamEventType } from "@/modules/organizations/services/event-types/output.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { TeamsEventTypesService } from "@/modules/teams/event-types/services/teams-event-types.service";
import { UsersService } from "@/modules/users/services/users.service";
import { UserWithProfile } from "@/modules/users/users.repository";
import { Injectable, NotFoundException, Logger } from "@nestjs/common";
import { Injectable, Logger } from "@nestjs/common";
import { createEventType, updateEventType } from "@calcom/platform-libraries";
import { createEventType } from "@calcom/platform-libraries";
import { InputTeamEventTransformed_2024_06_14 } from "@calcom/platform-types";
@Injectable()
@@ -16,10 +15,9 @@ export class OrganizationsEventTypesService {
private readonly logger = new Logger("OrganizationsEventTypesService");
constructor(
private readonly eventTypesService: EventTypesService_2024_06_14,
private readonly dbWrite: PrismaWriteService,
private readonly organizationEventTypesRepository: OrganizationsEventTypesRepository,
private readonly eventTypesRepository: EventTypesRepository_2024_06_14,
private readonly teamsEventTypesService: TeamsEventTypesService,
private readonly membershipsRepository: MembershipsRepository,
private readonly usersService: UsersService
) {}
@@ -44,15 +42,7 @@ export class OrganizationsEventTypesService {
},
});
return this.updateTeamEventType(eventTypeCreated.id, teamId, body, user);
}
async validateEventTypeExists(teamId: number, eventTypeId: number) {
const eventType = await this.organizationEventTypesRepository.getTeamEventType(teamId, eventTypeId);
if (!eventType) {
throw new NotFoundException(`Event type with id ${eventTypeId} not found`);
}
return this.teamsEventTypesService.updateTeamEventType(eventTypeCreated.id, teamId, body, user);
}
async getUserToCreateTeamEvent(user: UserWithProfile, organizationId: number) {
@@ -71,34 +61,23 @@ export class OrganizationsEventTypesService {
}
async getTeamEventType(teamId: number, eventTypeId: number): Promise<DatabaseTeamEventType | null> {
const eventType = await this.organizationEventTypesRepository.getTeamEventType(teamId, eventTypeId);
if (!eventType) {
return null;
}
return eventType;
return this.teamsEventTypesService.getTeamEventType(teamId, eventTypeId);
}
async getTeamEventTypeBySlug(teamId: number, eventTypeSlug: string): Promise<DatabaseTeamEventType | null> {
const eventType = await this.organizationEventTypesRepository.getTeamEventTypeBySlug(
teamId,
eventTypeSlug
);
if (!eventType) {
return null;
}
return eventType;
return this.teamsEventTypesService.getTeamEventTypeBySlug(teamId, eventTypeSlug);
}
async getTeamEventTypes(teamId: number): Promise<DatabaseTeamEventType[]> {
return await this.organizationEventTypesRepository.getTeamEventTypes(teamId);
return await this.teamsEventTypesService.getTeamEventTypes(teamId);
}
async getTeamsEventTypes(orgId: number, skip = 0, take = 250): Promise<DatabaseTeamEventType[]> {
return await this.organizationEventTypesRepository.getTeamsEventTypes(orgId, skip, take);
async getOrganizationsTeamsEventTypes(
orgId: number,
skip = 0,
take = 250
): Promise<DatabaseTeamEventType[]> {
return await this.organizationEventTypesRepository.getOrganizationTeamsEventTypes(orgId, skip, take);
}
async updateTeamEventType(
@@ -107,57 +86,10 @@ export class OrganizationsEventTypesService {
body: InputTeamEventTransformed_2024_06_14,
user: UserWithProfile
): Promise<DatabaseTeamEventType | DatabaseTeamEventType[]> {
await this.validateEventTypeExists(teamId, eventTypeId);
const eventTypeUser = await this.eventTypesService.getUserToUpdateEvent(user);
await updateEventType({
input: { id: eventTypeId, ...body },
ctx: {
user: eventTypeUser,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
prisma: this.dbWrite.prisma,
},
});
const eventType = await this.organizationEventTypesRepository.getEventTypeById(eventTypeId);
if (!eventType) {
throw new NotFoundException(`Event type with id ${eventTypeId} not found`);
}
if (eventType.schedulingType !== "MANAGED") {
return eventType;
}
const childrenEventTypes = await this.organizationEventTypesRepository.getEventTypeChildren(eventType.id);
return [eventType, ...childrenEventTypes];
return this.teamsEventTypesService.updateTeamEventType(eventTypeId, teamId, body, user);
}
async deleteTeamEventType(teamId: number, eventTypeId: number) {
const existingEventType = await this.organizationEventTypesRepository.getTeamEventType(
teamId,
eventTypeId
);
if (!existingEventType) {
throw new NotFoundException(`Event type with ID=${eventTypeId} does not exist.`);
}
return this.eventTypesRepository.deleteEventType(eventTypeId);
}
async deleteUserTeamEventTypesAndHosts(userId: number, teamId: number) {
try {
await this.organizationEventTypesRepository.deleteUserManagedTeamEventTypes(userId, teamId);
await this.organizationEventTypesRepository.removeUserFromTeamEventTypesHosts(userId, teamId);
} catch (err) {
this.logger.error("Could not remove user from all team event-types.", {
error: err,
userId,
teamId,
});
}
return this.teamsEventTypesService.deleteTeamEventType(teamId, eventTypeId);
}
}
@@ -1,5 +1,5 @@
import { OutputEventTypesService_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/services/output-event-types.service";
import { OrganizationsEventTypesRepository } from "@/modules/organizations/repositories/organizations-event-types.repository";
import { TeamsEventTypesRepository } from "@/modules/teams/event-types/teams-event-types.repository";
import { UsersRepository } from "@/modules/users/users.repository";
import { Injectable } from "@nestjs/common";
import type { EventType, User, Schedule, Host, DestinationCalendar } from "@prisma/client";
@@ -77,7 +77,7 @@ type Input = Pick<
export class OutputOrganizationsEventTypesService {
constructor(
private readonly outputEventTypesService: OutputEventTypesService_2024_06_14,
private readonly organizationEventTypesRepository: OrganizationsEventTypesRepository,
private readonly teamsEventTypesRepository: TeamsEventTypesRepository,
private readonly usersRepository: UsersRepository
) {}
@@ -117,7 +117,7 @@ export class OutputOrganizationsEventTypesService {
}
async getManagedEventTypeHosts(eventTypeId: number) {
const children = await this.organizationEventTypesRepository.getEventTypeChildren(eventTypeId);
const children = await this.teamsEventTypesRepository.getEventTypeChildren(eventTypeId);
const transformedHosts: TeamEventTypeResponseHost[] = [];
for (const child of children) {
if (child.userId) {
@@ -2,50 +2,62 @@ import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
// It ensures that we work on userLevel calendars only
const ensureUserLevelWhere = {
eventTypeId: null,
};
@Injectable()
export class SelectedCalendarsRepository {
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
upsertSelectedCalendar(externalId: string, credentialId: number, userId: number, integration: string) {
return this.dbWrite.prisma.selectedCalendar.upsert({
create: {
userId,
externalId,
credentialId,
integration,
},
update: {
userId,
externalId,
credentialId,
integration,
},
where: {
userId_integration_externalId: {
userId,
integration,
externalId,
async upsertSelectedCalendar(
externalId: string,
credentialId: number,
userId: number,
integration: string
) {
// Why we can't use .upsert here, see server/repository/selectedCalendar.ts#upsert
const existingUserSelectedCalendar = await this.getUserSelectedCalendar(userId, integration, externalId);
const data = {
userId,
externalId,
credentialId,
integration,
...ensureUserLevelWhere,
};
if (existingUserSelectedCalendar) {
return this.dbWrite.prisma.selectedCalendar.update({
where: {
id: existingUserSelectedCalendar.id,
},
},
data,
});
}
return this.dbWrite.prisma.selectedCalendar.create({
data,
});
}
getUserSelectedCalendars(userId: number) {
// It would be unique result but we can't use .findUnique here because of eventTypeId being nullable
return this.dbRead.prisma.selectedCalendar.findMany({
where: {
userId,
...ensureUserLevelWhere,
},
});
}
getUserSelectedCalendar(userId: number, integration: string, externalId: string) {
return this.dbRead.prisma.selectedCalendar.findUnique({
return this.dbRead.prisma.selectedCalendar.findFirst({
where: {
userId_integration_externalId: {
userId,
externalId,
integration,
},
userId,
externalId,
integration,
...ensureUserLevelWhere,
},
});
}
@@ -56,33 +68,46 @@ export class SelectedCalendarsRepository {
externalId: string,
credentialId: number
) {
return await this.dbWrite.prisma.selectedCalendar.upsert({
where: {
userId_integration_externalId: {
userId,
integration,
externalId,
},
},
create: {
const existingUserSelectedCalendar = await this.getUserSelectedCalendar(userId, integration, externalId);
if (existingUserSelectedCalendar) {
return;
}
return await this.dbWrite.prisma.selectedCalendar.create({
data: {
userId,
integration,
externalId,
credentialId,
...ensureUserLevelWhere,
},
// already exists
update: {},
});
}
async removeUserSelectedCalendar(userId: number, integration: string, externalId: string) {
// Using deleteMany because userId_externalId_integration_eventTypeId is a unique constraint but with eventTypeId being nullable, causing it to be not used as a unique constraint
const records = await this.dbWrite.prisma.selectedCalendar.findMany({
where: {
userId,
externalId,
integration,
...ensureUserLevelWhere,
},
});
// Make the behaviour same as .delete which throws error if no record is found
if (records.length === 0) {
throw new Error("No SelectedCalendar found.");
}
if (records.length > 1) {
throw new Error("Multiple SelecteCalendars found. Skipping deletion");
}
return await this.dbWrite.prisma.selectedCalendar.delete({
where: {
userId_integration_externalId: {
userId,
externalId,
integration,
},
id: records[0].id,
},
});
}
@@ -0,0 +1,490 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { SchedulesModule_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/schedules.module";
import { SchedulesService_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/services/schedules.service";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { SlotsModule } from "@/modules/slots/slots.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
import { INestApplication } from "@nestjs/common";
import { NestExpressApplication } from "@nestjs/platform-express";
import { Test } from "@nestjs/testing";
import { User } from "@prisma/client";
import * as request from "supertest";
import { BookingsRepositoryFixture } from "test/fixtures/repository/bookings.repository.fixture";
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
import { SelectedSlotsRepositoryFixture } from "test/fixtures/repository/selected-slots.repository.fixture";
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
import { randomNumber } from "test/utils/randomNumber";
import { withApiAuth } from "test/utils/withApiAuth";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
const expectedSlotsUTC = {
slots: {
"2050-09-05": [
{ time: "2050-09-05T07:00:00.000Z" },
{ time: "2050-09-05T08:00:00.000Z" },
{ time: "2050-09-05T09:00:00.000Z" },
{ time: "2050-09-05T10:00:00.000Z" },
{ time: "2050-09-05T11:00:00.000Z" },
{ time: "2050-09-05T12:00:00.000Z" },
{ time: "2050-09-05T13:00:00.000Z" },
{ time: "2050-09-05T14:00:00.000Z" },
],
"2050-09-06": [
{ time: "2050-09-06T07:00:00.000Z" },
{ time: "2050-09-06T08:00:00.000Z" },
{ time: "2050-09-06T09:00:00.000Z" },
{ time: "2050-09-06T10:00:00.000Z" },
{ time: "2050-09-06T11:00:00.000Z" },
{ time: "2050-09-06T12:00:00.000Z" },
{ time: "2050-09-06T13:00:00.000Z" },
{ time: "2050-09-06T14:00:00.000Z" },
],
"2050-09-07": [
{ time: "2050-09-07T07:00:00.000Z" },
{ time: "2050-09-07T08:00:00.000Z" },
{ time: "2050-09-07T09:00:00.000Z" },
{ time: "2050-09-07T10:00:00.000Z" },
{ time: "2050-09-07T11:00:00.000Z" },
{ time: "2050-09-07T12:00:00.000Z" },
{ time: "2050-09-07T13:00:00.000Z" },
{ time: "2050-09-07T14:00:00.000Z" },
],
"2050-09-08": [
{ time: "2050-09-08T07:00:00.000Z" },
{ time: "2050-09-08T08:00:00.000Z" },
{ time: "2050-09-08T09:00:00.000Z" },
{ time: "2050-09-08T10:00:00.000Z" },
{ time: "2050-09-08T11:00:00.000Z" },
{ time: "2050-09-08T12:00:00.000Z" },
{ time: "2050-09-08T13:00:00.000Z" },
{ time: "2050-09-08T14:00:00.000Z" },
],
"2050-09-09": [
{ time: "2050-09-09T07:00:00.000Z" },
{ time: "2050-09-09T08:00:00.000Z" },
{ time: "2050-09-09T09:00:00.000Z" },
{ time: "2050-09-09T10:00:00.000Z" },
{ time: "2050-09-09T11:00:00.000Z" },
{ time: "2050-09-09T12:00:00.000Z" },
{ time: "2050-09-09T13:00:00.000Z" },
{ time: "2050-09-09T14:00:00.000Z" },
],
},
};
const expectedSlotsRome = {
slots: {
"2050-09-05": [
{ time: "2050-09-05T09:00:00.000+02:00" },
{ time: "2050-09-05T10:00:00.000+02:00" },
{ time: "2050-09-05T11:00:00.000+02:00" },
{ time: "2050-09-05T12:00:00.000+02:00" },
{ time: "2050-09-05T13:00:00.000+02:00" },
{ time: "2050-09-05T14:00:00.000+02:00" },
{ time: "2050-09-05T15:00:00.000+02:00" },
{ time: "2050-09-05T16:00:00.000+02:00" },
],
"2050-09-06": [
{ time: "2050-09-06T09:00:00.000+02:00" },
{ time: "2050-09-06T10:00:00.000+02:00" },
{ time: "2050-09-06T11:00:00.000+02:00" },
{ time: "2050-09-06T12:00:00.000+02:00" },
{ time: "2050-09-06T13:00:00.000+02:00" },
{ time: "2050-09-06T14:00:00.000+02:00" },
{ time: "2050-09-06T15:00:00.000+02:00" },
{ time: "2050-09-06T16:00:00.000+02:00" },
],
"2050-09-07": [
{ time: "2050-09-07T09:00:00.000+02:00" },
{ time: "2050-09-07T10:00:00.000+02:00" },
{ time: "2050-09-07T11:00:00.000+02:00" },
{ time: "2050-09-07T12:00:00.000+02:00" },
{ time: "2050-09-07T13:00:00.000+02:00" },
{ time: "2050-09-07T14:00:00.000+02:00" },
{ time: "2050-09-07T15:00:00.000+02:00" },
{ time: "2050-09-07T16:00:00.000+02:00" },
],
"2050-09-08": [
{ time: "2050-09-08T09:00:00.000+02:00" },
{ time: "2050-09-08T10:00:00.000+02:00" },
{ time: "2050-09-08T11:00:00.000+02:00" },
{ time: "2050-09-08T12:00:00.000+02:00" },
{ time: "2050-09-08T13:00:00.000+02:00" },
{ time: "2050-09-08T14:00:00.000+02:00" },
{ time: "2050-09-08T15:00:00.000+02:00" },
{ time: "2050-09-08T16:00:00.000+02:00" },
],
"2050-09-09": [
{ time: "2050-09-09T09:00:00.000+02:00" },
{ time: "2050-09-09T10:00:00.000+02:00" },
{ time: "2050-09-09T11:00:00.000+02:00" },
{ time: "2050-09-09T12:00:00.000+02:00" },
{ time: "2050-09-09T13:00:00.000+02:00" },
{ time: "2050-09-09T14:00:00.000+02:00" },
{ time: "2050-09-09T15:00:00.000+02:00" },
{ time: "2050-09-09T16:00:00.000+02:00" },
],
},
};
const expectedSlotsUTCRange = {
slots: {
"2050-09-05": [
{ startTime: "2050-09-05T07:00:00.000Z", endTime: "2050-09-05T08:00:00.000Z" },
{ startTime: "2050-09-05T08:00:00.000Z", endTime: "2050-09-05T09:00:00.000Z" },
{ startTime: "2050-09-05T09:00:00.000Z", endTime: "2050-09-05T10:00:00.000Z" },
{ startTime: "2050-09-05T10:00:00.000Z", endTime: "2050-09-05T11:00:00.000Z" },
{ startTime: "2050-09-05T11:00:00.000Z", endTime: "2050-09-05T12:00:00.000Z" },
{ startTime: "2050-09-05T12:00:00.000Z", endTime: "2050-09-05T13:00:00.000Z" },
{ startTime: "2050-09-05T13:00:00.000Z", endTime: "2050-09-05T14:00:00.000Z" },
{ startTime: "2050-09-05T14:00:00.000Z", endTime: "2050-09-05T15:00:00.000Z" },
],
"2050-09-06": [
{ startTime: "2050-09-06T07:00:00.000Z", endTime: "2050-09-06T08:00:00.000Z" },
{ startTime: "2050-09-06T08:00:00.000Z", endTime: "2050-09-06T09:00:00.000Z" },
{ startTime: "2050-09-06T09:00:00.000Z", endTime: "2050-09-06T10:00:00.000Z" },
{ startTime: "2050-09-06T10:00:00.000Z", endTime: "2050-09-06T11:00:00.000Z" },
{ startTime: "2050-09-06T11:00:00.000Z", endTime: "2050-09-06T12:00:00.000Z" },
{ startTime: "2050-09-06T12:00:00.000Z", endTime: "2050-09-06T13:00:00.000Z" },
{ startTime: "2050-09-06T13:00:00.000Z", endTime: "2050-09-06T14:00:00.000Z" },
{ startTime: "2050-09-06T14:00:00.000Z", endTime: "2050-09-06T15:00:00.000Z" },
],
"2050-09-07": [
{ startTime: "2050-09-07T07:00:00.000Z", endTime: "2050-09-07T08:00:00.000Z" },
{ startTime: "2050-09-07T08:00:00.000Z", endTime: "2050-09-07T09:00:00.000Z" },
{ startTime: "2050-09-07T09:00:00.000Z", endTime: "2050-09-07T10:00:00.000Z" },
{ startTime: "2050-09-07T10:00:00.000Z", endTime: "2050-09-07T11:00:00.000Z" },
{ startTime: "2050-09-07T11:00:00.000Z", endTime: "2050-09-07T12:00:00.000Z" },
{ startTime: "2050-09-07T12:00:00.000Z", endTime: "2050-09-07T13:00:00.000Z" },
{ startTime: "2050-09-07T13:00:00.000Z", endTime: "2050-09-07T14:00:00.000Z" },
{ startTime: "2050-09-07T14:00:00.000Z", endTime: "2050-09-07T15:00:00.000Z" },
],
"2050-09-08": [
{ startTime: "2050-09-08T07:00:00.000Z", endTime: "2050-09-08T08:00:00.000Z" },
{ startTime: "2050-09-08T08:00:00.000Z", endTime: "2050-09-08T09:00:00.000Z" },
{ startTime: "2050-09-08T09:00:00.000Z", endTime: "2050-09-08T10:00:00.000Z" },
{ startTime: "2050-09-08T10:00:00.000Z", endTime: "2050-09-08T11:00:00.000Z" },
{ startTime: "2050-09-08T11:00:00.000Z", endTime: "2050-09-08T12:00:00.000Z" },
{ startTime: "2050-09-08T12:00:00.000Z", endTime: "2050-09-08T13:00:00.000Z" },
{ startTime: "2050-09-08T13:00:00.000Z", endTime: "2050-09-08T14:00:00.000Z" },
{ startTime: "2050-09-08T14:00:00.000Z", endTime: "2050-09-08T15:00:00.000Z" },
],
"2050-09-09": [
{ startTime: "2050-09-09T07:00:00.000Z", endTime: "2050-09-09T08:00:00.000Z" },
{ startTime: "2050-09-09T08:00:00.000Z", endTime: "2050-09-09T09:00:00.000Z" },
{ startTime: "2050-09-09T09:00:00.000Z", endTime: "2050-09-09T10:00:00.000Z" },
{ startTime: "2050-09-09T10:00:00.000Z", endTime: "2050-09-09T11:00:00.000Z" },
{ startTime: "2050-09-09T11:00:00.000Z", endTime: "2050-09-09T12:00:00.000Z" },
{ startTime: "2050-09-09T12:00:00.000Z", endTime: "2050-09-09T13:00:00.000Z" },
{ startTime: "2050-09-09T13:00:00.000Z", endTime: "2050-09-09T14:00:00.000Z" },
{ startTime: "2050-09-09T14:00:00.000Z", endTime: "2050-09-09T15:00:00.000Z" },
],
},
};
const expectedSlotsRomeRange = {
slots: {
"2050-09-05": [
{ startTime: "2050-09-05T09:00:00.000+02:00", endTime: "2050-09-05T10:00:00.000+02:00" },
{ startTime: "2050-09-05T10:00:00.000+02:00", endTime: "2050-09-05T11:00:00.000+02:00" },
{ startTime: "2050-09-05T11:00:00.000+02:00", endTime: "2050-09-05T12:00:00.000+02:00" },
{ startTime: "2050-09-05T12:00:00.000+02:00", endTime: "2050-09-05T13:00:00.000+02:00" },
{ startTime: "2050-09-05T13:00:00.000+02:00", endTime: "2050-09-05T14:00:00.000+02:00" },
{ startTime: "2050-09-05T14:00:00.000+02:00", endTime: "2050-09-05T15:00:00.000+02:00" },
{ startTime: "2050-09-05T15:00:00.000+02:00", endTime: "2050-09-05T16:00:00.000+02:00" },
{ startTime: "2050-09-05T16:00:00.000+02:00", endTime: "2050-09-05T17:00:00.000+02:00" },
],
"2050-09-06": [
{ startTime: "2050-09-06T09:00:00.000+02:00", endTime: "2050-09-06T10:00:00.000+02:00" },
{ startTime: "2050-09-06T10:00:00.000+02:00", endTime: "2050-09-06T11:00:00.000+02:00" },
{ startTime: "2050-09-06T11:00:00.000+02:00", endTime: "2050-09-06T12:00:00.000+02:00" },
{ startTime: "2050-09-06T12:00:00.000+02:00", endTime: "2050-09-06T13:00:00.000+02:00" },
{ startTime: "2050-09-06T13:00:00.000+02:00", endTime: "2050-09-06T14:00:00.000+02:00" },
{ startTime: "2050-09-06T14:00:00.000+02:00", endTime: "2050-09-06T15:00:00.000+02:00" },
{ startTime: "2050-09-06T15:00:00.000+02:00", endTime: "2050-09-06T16:00:00.000+02:00" },
{ startTime: "2050-09-06T16:00:00.000+02:00", endTime: "2050-09-06T17:00:00.000+02:00" },
],
"2050-09-07": [
{ startTime: "2050-09-07T09:00:00.000+02:00", endTime: "2050-09-07T10:00:00.000+02:00" },
{ startTime: "2050-09-07T10:00:00.000+02:00", endTime: "2050-09-07T11:00:00.000+02:00" },
{ startTime: "2050-09-07T11:00:00.000+02:00", endTime: "2050-09-07T12:00:00.000+02:00" },
{ startTime: "2050-09-07T12:00:00.000+02:00", endTime: "2050-09-07T13:00:00.000+02:00" },
{ startTime: "2050-09-07T13:00:00.000+02:00", endTime: "2050-09-07T14:00:00.000+02:00" },
{ startTime: "2050-09-07T14:00:00.000+02:00", endTime: "2050-09-07T15:00:00.000+02:00" },
{ startTime: "2050-09-07T15:00:00.000+02:00", endTime: "2050-09-07T16:00:00.000+02:00" },
{ startTime: "2050-09-07T16:00:00.000+02:00", endTime: "2050-09-07T17:00:00.000+02:00" },
],
"2050-09-08": [
{ startTime: "2050-09-08T09:00:00.000+02:00", endTime: "2050-09-08T10:00:00.000+02:00" },
{ startTime: "2050-09-08T10:00:00.000+02:00", endTime: "2050-09-08T11:00:00.000+02:00" },
{ startTime: "2050-09-08T11:00:00.000+02:00", endTime: "2050-09-08T12:00:00.000+02:00" },
{ startTime: "2050-09-08T12:00:00.000+02:00", endTime: "2050-09-08T13:00:00.000+02:00" },
{ startTime: "2050-09-08T13:00:00.000+02:00", endTime: "2050-09-08T14:00:00.000+02:00" },
{ startTime: "2050-09-08T14:00:00.000+02:00", endTime: "2050-09-08T15:00:00.000+02:00" },
{ startTime: "2050-09-08T15:00:00.000+02:00", endTime: "2050-09-08T16:00:00.000+02:00" },
{ startTime: "2050-09-08T16:00:00.000+02:00", endTime: "2050-09-08T17:00:00.000+02:00" },
],
"2050-09-09": [
{ startTime: "2050-09-09T09:00:00.000+02:00", endTime: "2050-09-09T10:00:00.000+02:00" },
{ startTime: "2050-09-09T10:00:00.000+02:00", endTime: "2050-09-09T11:00:00.000+02:00" },
{ startTime: "2050-09-09T11:00:00.000+02:00", endTime: "2050-09-09T12:00:00.000+02:00" },
{ startTime: "2050-09-09T12:00:00.000+02:00", endTime: "2050-09-09T13:00:00.000+02:00" },
{ startTime: "2050-09-09T13:00:00.000+02:00", endTime: "2050-09-09T14:00:00.000+02:00" },
{ startTime: "2050-09-09T14:00:00.000+02:00", endTime: "2050-09-09T15:00:00.000+02:00" },
{ startTime: "2050-09-09T15:00:00.000+02:00", endTime: "2050-09-09T16:00:00.000+02:00" },
{ startTime: "2050-09-09T16:00:00.000+02:00", endTime: "2050-09-09T17:00:00.000+02:00" },
],
},
};
describe("Slots Endpoints", () => {
describe("Individual user slots", () => {
let app: INestApplication;
let userRepositoryFixture: UserRepositoryFixture;
let schedulesService: SchedulesService_2024_06_11;
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
let selectedSlotsRepositoryFixture: SelectedSlotsRepositoryFixture;
let bookingsRepositoryFixture: BookingsRepositoryFixture;
const userEmail = `slots-${randomNumber()}-controller-e2e@api.com`;
const userName = "bob";
let user: User;
let eventTypeId: number;
let eventTypeSlug: string;
let reservedSlotUid: string;
beforeAll(async () => {
const moduleRef = await withApiAuth(
userEmail,
Test.createTestingModule({
imports: [
AppModule,
PrismaModule,
UsersModule,
TokensModule,
SchedulesModule_2024_06_11,
SlotsModule,
],
})
)
.overrideGuard(PermissionsGuard)
.useValue({
canActivate: () => true,
})
.compile();
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
schedulesService = moduleRef.get<SchedulesService_2024_06_11>(SchedulesService_2024_06_11);
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
selectedSlotsRepositoryFixture = new SelectedSlotsRepositoryFixture(moduleRef);
bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef);
user = await userRepositoryFixture.create({
email: userEmail,
name: "bob slot",
username: userName,
});
// nxte(Lauris): this creates default schedule monday to friday from 9AM to 5PM in Europe/Rome timezone
await schedulesService.createUserDefaultSchedule(user.id, "Europe/Rome");
const event = await eventTypesRepositoryFixture.create(
{ title: "frisbee match", slug: "frisbee-match", length: 60 },
user.id
);
eventTypeId = event.id;
eventTypeSlug = event.slug;
app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication);
await app.init();
});
it("should get slots in UTC by event type id", async () => {
return request(app.getHttpServer())
.get(`/api/v2/slots/available?eventTypeId=${eventTypeId}&startTime=2050-09-05&endTime=2050-09-10`)
.expect(200)
.expect((res) => {
expect(res.body).toEqual({
status: SUCCESS_STATUS,
data: expectedSlotsUTC,
});
});
});
it("should get slots in specified time zone by event type id", async () => {
return request(app.getHttpServer())
.get(
`/api/v2/slots/available?eventTypeId=${eventTypeId}&startTime=2050-09-05&endTime=2050-09-10&timeZone=Europe/Rome`
)
.expect(200)
.expect((res) => {
expect(res.body).toEqual({
status: SUCCESS_STATUS,
data: expectedSlotsRome,
});
});
});
it("should get slots in UTC by event type id in range format", async () => {
return request(app.getHttpServer())
.get(
`/api/v2/slots/available?eventTypeId=${eventTypeId}&startTime=2050-09-05&endTime=2050-09-10&slotFormat=range`
)
.expect(200)
.expect((res) => {
expect(res.body).toEqual({
status: SUCCESS_STATUS,
data: expectedSlotsUTCRange,
});
});
});
it("should get slots in specified time zone by event type id in range format", async () => {
return request(app.getHttpServer())
.get(
`/api/v2/slots/available?eventTypeId=${eventTypeId}&startTime=2050-09-05&endTime=2050-09-10&timeZone=Europe/Rome&slotFormat=range`
)
.expect(200)
.expect((res) => {
expect(res.body).toEqual({
status: SUCCESS_STATUS,
data: expectedSlotsRomeRange,
});
});
});
it("should get slots in UTC by event type slug", async () => {
return request(app.getHttpServer())
.get(
`/api/v2/slots/available?eventTypeSlug=${eventTypeSlug}&usernameList[]=${userName}&startTime=2050-09-05&endTime=2050-09-10`
)
.expect(200)
.expect((res) => {
expect(res.body).toEqual({
status: SUCCESS_STATUS,
data: expectedSlotsUTC,
});
});
});
it("should get slots in specified time zone by event type slug", async () => {
return request(app.getHttpServer())
.get(
`/api/v2/slots/available?eventTypeSlug=${eventTypeSlug}&usernameList[]=${userName}&startTime=2050-09-05&endTime=2050-09-10&timeZone=Europe/Rome`
)
.expect(200)
.expect((res) => {
expect(res.body).toEqual({
status: SUCCESS_STATUS,
data: expectedSlotsRome,
});
});
});
it("should reserve a slot and it should not appear in available slots", async () => {
const slotStartTime = "2050-09-05T10:00:00.000Z";
const reserveResponse = await request(app.getHttpServer())
.post(`/api/v2/slots/reserve`)
.send({
eventTypeId,
slotUtcStartDate: slotStartTime,
slotUtcEndDate: "2050-09-05T11:00:00.000Z",
})
.expect(201);
const reserveResponseBody = reserveResponse.body;
expect(reserveResponseBody.status).toEqual(SUCCESS_STATUS);
const uid: string = reserveResponseBody.data;
expect(uid).toBeDefined();
if (!uid) {
throw new Error("Reserved slot uid is undefined");
}
reservedSlotUid = uid;
const response = await request(app.getHttpServer())
.get(`/api/v2/slots/available?eventTypeId=${eventTypeId}&startTime=2050-09-05&endTime=2050-09-10`)
.expect(200);
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const slots = responseBody.data;
expect(slots).toBeDefined();
const days = Object.keys(slots.slots);
expect(days.length).toEqual(5);
const expectedSlotsUTC2050_09_05 = expectedSlotsUTC.slots["2050-09-05"].filter(
(slot) => slot.time !== slotStartTime
);
expect(slots).toEqual({
slots: { ...expectedSlotsUTC.slots, "2050-09-05": expectedSlotsUTC2050_09_05 },
});
});
it("should delete reserved slot", async () => {
await request(app.getHttpServer())
.delete(`/api/v2/slots/selected-slot?uid=${reservedSlotUid}`)
.expect(200);
});
it("should do a booking and slot should not be available at that time", async () => {
const startTime = "2050-09-05T11:00:00.000Z";
await bookingsRepositoryFixture.create({
uid: `booking-uid-${eventTypeId}`,
title: "booking title",
startTime,
endTime: "2050-09-05T12:00:00.000Z",
eventType: {
connect: {
id: eventTypeId,
},
},
metadata: {},
responses: {
name: "tester",
email: "tester@example.com",
guests: [],
},
user: {
connect: {
id: user.id,
},
},
});
const response = await request(app.getHttpServer())
.get(`/api/v2/slots/available?eventTypeId=${eventTypeId}&startTime=2050-09-05&endTime=2050-09-10`)
.expect(200);
const responseBody = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const slots = responseBody.data;
expect(slots).toBeDefined();
const days = Object.keys(slots.slots);
expect(days.length).toEqual(5);
const expectedSlotsUTC2050_09_05 = expectedSlotsUTC.slots["2050-09-05"].filter(
(slot) => slot.time !== startTime
);
expect(slots).toEqual({
slots: { ...expectedSlotsUTC.slots, "2050-09-05": expectedSlotsUTC2050_09_05 },
});
});
afterAll(async () => {
await userRepositoryFixture.deleteByEmail(user.email);
await selectedSlotsRepositoryFixture.deleteByUId(reservedSlotUid);
await bookingsRepositoryFixture.deleteAllBookings(user.id, user.email);
await app.close();
});
});
});
@@ -1,11 +1,11 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { SlotsOutputService } from "@/modules/slots/services/slots-output.service";
import { SlotsService } from "@/modules/slots/services/slots.service";
import { Query, Body, Controller, Get, Delete, Post, Req, Res } from "@nestjs/common";
import { ApiTags as DocsTags, ApiCreatedResponse, ApiOkResponse, ApiOperation } from "@nestjs/swagger";
import { Response as ExpressResponse, Request as ExpressRequest } from "express";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { SlotFormat } from "@calcom/platform-enums";
import { getAvailableSlots } from "@calcom/platform-libraries";
import type { AvailableSlotsType } from "@calcom/platform-libraries";
import { RemoveSelectedSlotInput, ReserveSlotInput } from "@calcom/platform-types";
@@ -17,7 +17,10 @@ import { ApiResponse, GetAvailableSlotsInput } from "@calcom/platform-types";
})
@DocsTags("Slots")
export class SlotsController {
constructor(private readonly slotsService: SlotsService) {}
constructor(
private readonly slotsService: SlotsService,
private readonly slotsOutputService: SlotsOutputService
) {}
@Post("/reserve")
@ApiCreatedResponse({
@@ -159,19 +162,17 @@ export class SlotsController {
},
});
const transformedSlots =
query.slotFormat === SlotFormat.Range
? await this.slotsService.formatSlots(
availableSlots,
query.duration,
query.eventTypeId,
query.slotFormat
)
: availableSlots.slots;
const { slots } = await this.slotsOutputService.getOutputSlots(
availableSlots,
query.duration,
query.eventTypeId,
query.slotFormat,
query.timeZone
);
return {
data: {
slots: transformedSlots,
slots,
},
status: SUCCESS_STATUS,
};
@@ -0,0 +1,96 @@
import { EventTypesRepository_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/event-types.repository";
import { Injectable, BadRequestException } from "@nestjs/common";
import { DateTime } from "luxon";
import { SlotFormat } from "@calcom/platform-enums";
type TimeSlots = { slots: Record<string, { time: string }[]> };
type RangeSlots = { slots: Record<string, { startTime: string; endTime: string }[]> };
@Injectable()
export class SlotsOutputService {
constructor(private readonly eventTypesRepository: EventTypesRepository_2024_04_15) {}
async getOutputSlots(
availableSlots: TimeSlots,
duration?: number,
eventTypeId?: number,
slotFormat?: SlotFormat,
timeZone?: string
): Promise<TimeSlots | RangeSlots> {
if (!slotFormat) {
return timeZone ? this.setTimeZone(availableSlots, timeZone) : availableSlots;
}
const formattedSlots = await this.formatSlots(availableSlots, duration, eventTypeId, slotFormat);
return timeZone ? this.setTimeZoneRange(formattedSlots, timeZone) : formattedSlots;
}
private setTimeZone(slots: TimeSlots, timeZone: string): TimeSlots {
const formattedSlots = Object.entries(slots.slots).reduce((acc, [date, daySlots]) => {
acc[date] = daySlots.map((slot) => ({
time: DateTime.fromISO(slot.time).setZone(timeZone).toISO() || "unknown-time",
}));
return acc;
}, {} as Record<string, { time: string }[]>);
return { slots: formattedSlots };
}
private setTimeZoneRange(slots: RangeSlots, timeZone: string): RangeSlots {
const formattedSlots = Object.entries(slots.slots).reduce((acc, [date, daySlots]) => {
acc[date] = daySlots.map((slot) => ({
startTime: DateTime.fromISO(slot.startTime).setZone(timeZone).toISO() || "unknown-start-time",
endTime: DateTime.fromISO(slot.endTime).setZone(timeZone).toISO() || "unknown-end-time",
}));
return acc;
}, {} as Record<string, { startTime: string; endTime: string }[]>);
return { slots: formattedSlots };
}
private async formatSlots(
availableSlots: TimeSlots,
duration?: number,
eventTypeId?: number,
slotFormat?: SlotFormat
): Promise<RangeSlots> {
if (slotFormat && !Object.values(SlotFormat).includes(slotFormat)) {
throw new BadRequestException("Invalid slot format. Must be either 'range' or 'time'");
}
const slotDuration = await this.getDuration(duration, eventTypeId);
const slots = Object.entries(availableSlots.slots).reduce<
Record<string, { startTime: string; endTime: string }[]>
>((acc, [date, slots]) => {
acc[date] = (slots as { time: string }[]).map((slot) => {
const startTime = new Date(slot.time);
const endTime = new Date(startTime.getTime() + slotDuration * 60000);
return {
startTime: startTime.toISOString(),
endTime: endTime.toISOString(),
};
});
return acc;
}, {});
return { slots };
}
private async getDuration(duration?: number, eventTypeId?: number): Promise<number> {
if (duration) {
return duration;
}
if (eventTypeId) {
const eventType = await this.eventTypesRepository.getEventTypeWithDuration(eventTypeId);
if (!eventType) {
throw new Error("Event type not found");
}
return eventType.length;
}
throw new Error("duration or eventTypeId is required");
}
}
@@ -1,6 +1,7 @@
import { EventTypesRepository_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/event-types.repository";
import { SlotsRepository } from "@/modules/slots/slots.repository";
import { Injectable, NotFoundException, BadRequestException } from "@nestjs/common";
import { DateTime } from "luxon";
import { v4 as uuid } from "uuid";
import { SlotFormat } from "@calcom/platform-enums";
@@ -55,51 +56,4 @@ export class SlotsService {
const event = await this.eventTypeRepo.getEventTypeById(eventTypeId);
return !!event?.teamId;
}
async getEventTypeWithDuration(eventTypeId: number) {
return await this.eventTypeRepo.getEventTypeWithDuration(eventTypeId);
}
async getDuration(duration?: number, eventTypeId?: number): Promise<number> {
if (duration) {
return duration;
}
if (eventTypeId) {
const eventType = await this.eventTypeRepo.getEventTypeWithDuration(eventTypeId);
if (!eventType) {
throw new Error("Event type not found");
}
return eventType.length;
}
throw new Error("duration or eventTypeId is required");
}
async formatSlots(
availableSlots: { slots: Record<string, { time: string }[]> },
duration?: number,
eventTypeId?: number,
slotFormat?: SlotFormat
): Promise<Record<string, { startTime: string; endTime: string }[]>> {
if (slotFormat && !Object.values(SlotFormat).includes(slotFormat)) {
throw new BadRequestException("Invalid slot format. Must be either 'range' or 'time'");
}
const slotDuration = await this.getDuration(duration, eventTypeId);
return Object.entries(availableSlots.slots).reduce<
Record<string, { startTime: string; endTime: string }[]>
>((acc, [date, slots]) => {
acc[date] = (slots as { time: string }[]).map((slot) => {
const startTime = new Date(slot.time);
const endTime = new Date(startTime.getTime() + slotDuration * 60000);
return {
startTime: startTime.toISOString(),
endTime: endTime.toISOString(),
};
});
return acc;
}, {});
}
}
@@ -1,13 +1,14 @@
import { EventTypesModule_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/event-types.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { SlotsController } from "@/modules/slots/controllers/slots.controller";
import { SlotsOutputService } from "@/modules/slots/services/slots-output.service";
import { SlotsService } from "@/modules/slots/services/slots.service";
import { SlotsRepository } from "@/modules/slots/slots.repository";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule, EventTypesModule_2024_04_15],
providers: [SlotsRepository, SlotsService],
providers: [SlotsRepository, SlotsService, SlotsOutputService],
controllers: [SlotsController],
exports: [SlotsService],
})
@@ -0,0 +1,570 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
import { INestApplication } from "@nestjs/common";
import { NestExpressApplication } from "@nestjs/platform-express";
import { Test } from "@nestjs/testing";
import { User } from "@prisma/client";
import * as request from "supertest";
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
import { OrganizationRepositoryFixture } from "test/fixtures/repository/organization.repository.fixture";
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
import { randomNumber } from "test/utils/randomNumber";
import { withApiAuth } from "test/utils/withApiAuth";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import {
BookingWindowPeriodInputTypeEnum_2024_06_14,
BookerLayoutsInputEnum_2024_06_14,
ConfirmationPolicyEnum,
NoticeThresholdUnitEnum,
} from "@calcom/platform-enums";
import {
ApiSuccessResponse,
CreateTeamEventTypeInput_2024_06_14,
Host,
TeamEventTypeOutput_2024_06_14,
UpdateTeamEventTypeInput_2024_06_14,
} from "@calcom/platform-types";
import { Team } from "@calcom/prisma/client";
describe("Organizations Event Types Endpoints", () => {
describe("User Authentication - User is Org Admin", () => {
let app: INestApplication;
let userRepositoryFixture: UserRepositoryFixture;
let organizationsRepositoryFixture: OrganizationRepositoryFixture;
let teamsRepositoryFixture: TeamRepositoryFixture;
let membershipsRepositoryFixture: MembershipRepositoryFixture;
let profileRepositoryFixture: ProfileRepositoryFixture;
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
let team: Team;
let falseTestTeam: Team;
const userEmail = `auth-${randomNumber()}@api.com`;
let userAdmin: User;
const teammate1Email = "teammate111@team.com";
const teammate2Email = "teammate221@team.com";
const falseTestUserEmail = "false-user@false-team.com";
let teamMember1: User;
let teamMember2: User;
let falseTestUser: User;
let collectiveEventType: TeamEventTypeOutput_2024_06_14;
let managedEventType: TeamEventTypeOutput_2024_06_14;
beforeAll(async () => {
const moduleRef = await withApiAuth(
userEmail,
Test.createTestingModule({
imports: [AppModule, PrismaModule, UsersModule, TokensModule],
})
).compile();
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);
teamsRepositoryFixture = new TeamRepositoryFixture(moduleRef);
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
profileRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
userAdmin = await userRepositoryFixture.create({
email: userEmail,
username: userEmail,
role: "ADMIN",
});
teamMember1 = await userRepositoryFixture.create({
email: teammate1Email,
username: teammate1Email,
});
teamMember2 = await userRepositoryFixture.create({
email: teammate2Email,
username: teammate2Email,
});
falseTestUser = await userRepositoryFixture.create({
email: falseTestUserEmail,
username: falseTestUserEmail,
});
team = await teamsRepositoryFixture.create({
name: "Test org team",
isOrganization: false,
});
falseTestTeam = await teamsRepositoryFixture.create({
name: "Outside org team",
isOrganization: false,
});
await membershipsRepositoryFixture.create({
role: "ADMIN",
user: { connect: { id: userAdmin.id } },
team: { connect: { id: team.id } },
accepted: true,
});
await membershipsRepositoryFixture.create({
role: "MEMBER",
user: { connect: { id: teamMember1.id } },
team: { connect: { id: team.id } },
accepted: true,
});
await membershipsRepositoryFixture.create({
role: "MEMBER",
user: { connect: { id: teamMember2.id } },
team: { connect: { id: team.id } },
accepted: true,
});
await membershipsRepositoryFixture.create({
role: "MEMBER",
user: { connect: { id: falseTestUser.id } },
team: { connect: { id: falseTestTeam.id } },
accepted: true,
});
app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication);
await app.init();
});
it("should not be able to create event-type for user outside team", async () => {
const userId = falseTestUser.id;
const body: CreateTeamEventTypeInput_2024_06_14 = {
title: "Coding consultation",
slug: "coding-consultation",
description: "Our team will review your codebase.",
lengthInMinutes: 60,
locations: [
{
type: "integration",
integration: "cal-video",
},
],
schedulingType: "COLLECTIVE",
hosts: [
{
userId,
mandatory: true,
priority: "high",
},
],
};
return request(app.getHttpServer()).post(`/v2/teams/${team.id}/event-types`).send(body).expect(404);
});
it("should create a collective team event-type", async () => {
const body: CreateTeamEventTypeInput_2024_06_14 = {
title: "Coding consultation collective",
slug: "coding-consultation collective",
description: "Our team will review your codebase.",
lengthInMinutes: 60,
locations: [
{
type: "integration",
integration: "cal-video",
},
],
bookingFields: [
{
type: "select",
label: "select which language is your codebase in",
slug: "select-language",
required: true,
placeholder: "select language",
options: ["javascript", "python", "cobol"],
},
],
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
schedulingType: "collective",
hosts: [
{
userId: teamMember1.id,
},
{
userId: teamMember2.id,
},
],
bookingLimitsCount: {
day: 2,
week: 5,
},
onlyShowFirstAvailableSlot: true,
bookingLimitsDuration: {
day: 60,
week: 100,
},
offsetStart: 30,
bookingWindow: {
type: BookingWindowPeriodInputTypeEnum_2024_06_14.calendarDays,
value: 30,
rolling: true,
},
bookerLayouts: {
enabledLayouts: [
BookerLayoutsInputEnum_2024_06_14.column,
BookerLayoutsInputEnum_2024_06_14.month,
BookerLayoutsInputEnum_2024_06_14.week,
],
defaultLayout: BookerLayoutsInputEnum_2024_06_14.month,
},
confirmationPolicy: {
type: ConfirmationPolicyEnum.TIME,
noticeThreshold: {
count: 60,
unit: NoticeThresholdUnitEnum.MINUTES,
},
blockUnconfirmedBookingsInBooker: true,
},
requiresBookerEmailVerification: true,
hideCalendarNotes: true,
hideCalendarEventDetails: true,
lockTimeZoneToggleOnBookingPage: true,
color: {
darkThemeHex: "#292929",
lightThemeHex: "#fafafa",
},
};
return request(app.getHttpServer())
.post(`/v2/teams/${team.id}/event-types`)
.send(body)
.expect(201)
.then((response) => {
const responseBody: ApiSuccessResponse<TeamEventTypeOutput_2024_06_14> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data;
expect(data.title).toEqual(body.title);
expect(data.hosts.length).toEqual(2);
expect(data.schedulingType).toEqual("COLLECTIVE");
evaluateHost(body.hosts[0], data.hosts[0]);
evaluateHost(body.hosts[1], data.hosts[1]);
expect(data.bookingLimitsCount).toEqual(body.bookingLimitsCount);
expect(data.onlyShowFirstAvailableSlot).toEqual(body.onlyShowFirstAvailableSlot);
expect(data.bookingLimitsDuration).toEqual(body.bookingLimitsDuration);
expect(data.offsetStart).toEqual(body.offsetStart);
expect(data.bookingWindow).toEqual(body.bookingWindow);
expect(data.bookerLayouts).toEqual(body.bookerLayouts);
expect(data.confirmationPolicy).toEqual(body.confirmationPolicy);
expect(data.requiresBookerEmailVerification).toEqual(body.requiresBookerEmailVerification);
expect(data.hideCalendarNotes).toEqual(body.hideCalendarNotes);
expect(data.hideCalendarEventDetails).toEqual(body.hideCalendarEventDetails);
expect(data.lockTimeZoneToggleOnBookingPage).toEqual(body.lockTimeZoneToggleOnBookingPage);
expect(data.color).toEqual(body.color);
collectiveEventType = responseBody.data;
});
});
it("should create a managed team event-type", async () => {
const body: CreateTeamEventTypeInput_2024_06_14 = {
title: "Coding consultation managed",
slug: "coding-consultation-managed",
description: "Our team will review your codebase.",
lengthInMinutes: 60,
locations: [
{
type: "integration",
integration: "cal-video",
},
],
schedulingType: "MANAGED",
hosts: [
{
userId: teamMember1.id,
mandatory: true,
priority: "high",
},
{
userId: teamMember2.id,
mandatory: false,
priority: "low",
},
],
};
return request(app.getHttpServer())
.post(`/v2/teams/${team.id}/event-types`)
.send(body)
.expect(201)
.then(async (response) => {
const responseBody: ApiSuccessResponse<TeamEventTypeOutput_2024_06_14[]> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data;
expect(data.length).toEqual(3);
const teammate1EventTypes = await eventTypesRepositoryFixture.getAllUserEventTypes(teamMember1.id);
const teammate2EventTypes = await eventTypesRepositoryFixture.getAllUserEventTypes(teamMember2.id);
const teamEventTypes = await eventTypesRepositoryFixture.getAllTeamEventTypes(team.id);
expect(teammate1EventTypes.length).toEqual(1);
expect(teammate2EventTypes.length).toEqual(1);
expect(teamEventTypes.filter((eventType) => eventType.schedulingType === "MANAGED").length).toEqual(
1
);
const responseTeamEvent = responseBody.data.find((event) => event.teamId === team.id);
expect(responseTeamEvent).toBeDefined();
if (!responseTeamEvent) {
throw new Error("Team event not found");
}
const responseTeammate1Event = responseBody.data.find((event) => event.ownerId === teamMember1.id);
expect(responseTeammate1Event).toBeDefined();
expect(responseTeammate1Event?.parentEventTypeId).toEqual(responseTeamEvent?.id);
const responseTeammate2Event = responseBody.data.find((event) => event.ownerId === teamMember2.id);
expect(responseTeammate2Event).toBeDefined();
expect(responseTeammate2Event?.parentEventTypeId).toEqual(responseTeamEvent?.id);
managedEventType = responseTeamEvent;
});
});
it("should not get a non existing event-type", async () => {
return request(app.getHttpServer()).get(`/v2/teams/${team.id}/event-types/999999`).expect(404);
});
it("should get a team event-type", async () => {
return request(app.getHttpServer())
.get(`/v2/teams/${team.id}/event-types/${collectiveEventType.id}`)
.expect(200)
.then((response) => {
const responseBody: ApiSuccessResponse<TeamEventTypeOutput_2024_06_14> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data;
expect(data.title).toEqual(collectiveEventType.title);
expect(data.hosts.length).toEqual(2);
evaluateHost(collectiveEventType.hosts[0], data.hosts[0]);
evaluateHost(collectiveEventType.hosts[1], data.hosts[1]);
collectiveEventType = responseBody.data;
});
});
it("should get team event-types", async () => {
return request(app.getHttpServer())
.get(`/v2/teams/${team.id}/event-types`)
.expect(200)
.then((response) => {
const responseBody: ApiSuccessResponse<TeamEventTypeOutput_2024_06_14[]> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data;
expect(data.length).toEqual(2);
const eventTypeCollective = data.find((eventType) => eventType.schedulingType === "COLLECTIVE");
const eventTypeManaged = data.find((eventType) => eventType.schedulingType === "MANAGED");
expect(eventTypeCollective?.title).toEqual(collectiveEventType.title);
expect(eventTypeCollective?.hosts.length).toEqual(2);
expect(eventTypeManaged?.title).toEqual(managedEventType.title);
expect(eventTypeManaged?.hosts.length).toEqual(2);
evaluateHost(collectiveEventType.hosts[0], eventTypeCollective?.hosts[0]);
evaluateHost(collectiveEventType.hosts[1], eventTypeCollective?.hosts[1]);
});
});
it("should not be able to update non existing event-type", async () => {
const body: UpdateTeamEventTypeInput_2024_06_14 = {
title: "Clean code consultation",
};
return request(app.getHttpServer())
.patch(`/v2/teams/${team.id}/event-types/999999`)
.send(body)
.expect(400);
});
it("should update collective event-type", async () => {
const newHosts: UpdateTeamEventTypeInput_2024_06_14["hosts"] = [
{
userId: teamMember1.id,
},
];
const body: UpdateTeamEventTypeInput_2024_06_14 = {
hosts: newHosts,
};
return request(app.getHttpServer())
.patch(`/v2/teams/${team.id}/event-types/${collectiveEventType.id}`)
.send(body)
.expect(200)
.then((response) => {
const responseBody: ApiSuccessResponse<TeamEventTypeOutput_2024_06_14> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const eventType = responseBody.data;
expect(eventType.title).toEqual(collectiveEventType.title);
expect(eventType.hosts.length).toEqual(1);
evaluateHost(eventType.hosts[0], newHosts[0]);
});
});
it("should update managed event-type", async () => {
const newTitle = "Coding consultation managed updated";
const newHosts: UpdateTeamEventTypeInput_2024_06_14["hosts"] = [
{
userId: teamMember1.id,
mandatory: true,
priority: "medium",
},
];
const body: UpdateTeamEventTypeInput_2024_06_14 = {
title: newTitle,
hosts: newHosts,
};
return request(app.getHttpServer())
.patch(`/v2/teams/${team.id}/event-types/${managedEventType.id}`)
.send(body)
.expect(200)
.then(async (response) => {
const responseBody: ApiSuccessResponse<TeamEventTypeOutput_2024_06_14[]> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data;
expect(data.length).toEqual(2);
const teammate1EventTypes = await eventTypesRepositoryFixture.getAllUserEventTypes(teamMember1.id);
const teammate2EventTypes = await eventTypesRepositoryFixture.getAllUserEventTypes(teamMember2.id);
const teamEventTypes = await eventTypesRepositoryFixture.getAllTeamEventTypes(team.id);
const managedTeamEventTypes = teamEventTypes.filter(
(eventType) => eventType.schedulingType === "MANAGED"
);
expect(teammate1EventTypes.length).toEqual(1);
expect(teammate1EventTypes[0].title).toEqual(newTitle);
expect(teammate2EventTypes.length).toEqual(0);
expect(managedTeamEventTypes.length).toEqual(1);
expect(managedTeamEventTypes[0].assignAllTeamMembers).toEqual(false);
expect(
teamEventTypes.filter((eventType) => eventType.schedulingType === "MANAGED")?.[0]?.title
).toEqual(newTitle);
const responseTeamEvent = responseBody.data.find(
(eventType) => eventType.schedulingType === "MANAGED"
);
expect(responseTeamEvent).toBeDefined();
expect(responseTeamEvent?.title).toEqual(newTitle);
expect(responseTeamEvent?.assignAllTeamMembers).toEqual(false);
const responseTeammate1Event = responseBody.data.find(
(eventType) => eventType.ownerId === teamMember1.id
);
expect(responseTeammate1Event).toBeDefined();
expect(responseTeammate1Event?.title).toEqual(newTitle);
managedEventType = responseBody.data[0];
});
});
it("should assign all members to managed event-type", async () => {
const body: UpdateTeamEventTypeInput_2024_06_14 = {
assignAllTeamMembers: true,
};
return request(app.getHttpServer())
.patch(`/v2/teams/${team.id}/event-types/${managedEventType.id}`)
.send(body)
.expect(200)
.then(async (response) => {
const responseBody: ApiSuccessResponse<TeamEventTypeOutput_2024_06_14[]> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const data = responseBody.data;
// note(Lauris): we expect 4 because we have 2 team members, 1 team admin and 4th is the event object itself.
expect(data.length).toEqual(4);
const teammate1EventTypes = await eventTypesRepositoryFixture.getAllUserEventTypes(teamMember1.id);
const teammate2EventTypes = await eventTypesRepositoryFixture.getAllUserEventTypes(teamMember2.id);
const teamEventTypes = await eventTypesRepositoryFixture.getAllTeamEventTypes(team.id);
const managedTeamEventTypes = teamEventTypes.filter(
(eventType) => eventType.schedulingType === "MANAGED"
);
expect(teammate1EventTypes.length).toEqual(1);
expect(teammate2EventTypes.length).toEqual(1);
expect(managedTeamEventTypes.length).toEqual(1);
expect(managedTeamEventTypes[0].assignAllTeamMembers).toEqual(true);
const responseTeamEvent = responseBody.data.find(
(eventType) => eventType.schedulingType === "MANAGED"
);
expect(responseTeamEvent).toBeDefined();
expect(responseTeamEvent?.teamId).toEqual(team.id);
expect(responseTeamEvent?.assignAllTeamMembers).toEqual(true);
const responseTeammate1Event = responseBody.data.find(
(eventType) => eventType.ownerId === teamMember1.id
);
expect(responseTeammate1Event).toBeDefined();
expect(responseTeammate1Event?.parentEventTypeId).toEqual(responseTeamEvent?.id);
const responseTeammate2Event = responseBody.data.find(
(eventType) => eventType.ownerId === teamMember2.id
);
expect(responseTeammate1Event).toBeDefined();
expect(responseTeammate2Event?.parentEventTypeId).toEqual(responseTeamEvent?.id);
if (responseTeamEvent) {
managedEventType = responseTeamEvent;
}
});
});
it("should delete event-type not part of the team", async () => {
return request(app.getHttpServer()).delete(`/v2/teams/${team.id}/event-types/99999`).expect(404);
});
it("should delete collective event-type", async () => {
return request(app.getHttpServer())
.delete(`/v2/teams/${team.id}/event-types/${collectiveEventType.id}`)
.expect(200);
});
it("should delete managed event-type", async () => {
return request(app.getHttpServer())
.delete(`/v2/teams/${team.id}/event-types/${managedEventType.id}`)
.expect(200);
});
function evaluateHost(expected: Host, received: Host | undefined) {
expect(expected.userId).toEqual(received?.userId);
expect(expected.mandatory).toEqual(received?.mandatory);
expect(expected.priority).toEqual(received?.priority);
}
afterAll(async () => {
await userRepositoryFixture.deleteByEmail(userAdmin.email);
await userRepositoryFixture.deleteByEmail(teamMember1.email);
await userRepositoryFixture.deleteByEmail(teamMember2.email);
await userRepositoryFixture.deleteByEmail(falseTestUser.email);
await teamsRepositoryFixture.delete(team.id);
await teamsRepositoryFixture.delete(falseTestTeam.id);
await app.close();
});
});
});
@@ -0,0 +1,208 @@
import { CreatePhoneCallInput } from "@/ee/event-types/event-types_2024_06_14/inputs/create-phone-call.input";
import { CreatePhoneCallOutput } from "@/ee/event-types/event-types_2024_06_14/outputs/create-phone-call.output";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { PlatformPlan } from "@/modules/auth/decorators/billing/platform-plan.decorator";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Roles } from "@/modules/auth/decorators/roles/roles.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard";
import { OutputTeamEventTypesResponsePipe } from "@/modules/organizations/controllers/pipes/event-types/team-event-types-response.transformer";
import { InputOrganizationsEventTypesService } from "@/modules/organizations/services/event-types/input.service";
import { DatabaseTeamEventType } from "@/modules/organizations/services/event-types/output.service";
import { CreateTeamEventTypeOutput } from "@/modules/teams/event-types/outputs/create-team-event-type.output";
import { DeleteTeamEventTypeOutput } from "@/modules/teams/event-types/outputs/delete-team-event-type.output";
import { GetTeamEventTypeOutput } from "@/modules/teams/event-types/outputs/get-team-event-type.output";
import { GetTeamEventTypesOutput } from "@/modules/teams/event-types/outputs/get-team-event-types.output";
import { UpdateTeamEventTypeOutput } from "@/modules/teams/event-types/outputs/update-team-event-type.output";
import { TeamsEventTypesService } from "@/modules/teams/event-types/services/teams-event-types.service";
import { UserWithProfile } from "@/modules/users/users.repository";
import {
Controller,
UseGuards,
Get,
Post,
Param,
ParseIntPipe,
Body,
Patch,
Delete,
HttpCode,
HttpStatus,
NotFoundException,
Query,
} from "@nestjs/common";
import { ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
import { handleCreatePhoneCall } from "@calcom/platform-libraries";
import {
CreateTeamEventTypeInput_2024_06_14,
GetTeamEventTypesQuery_2024_06_14,
SkipTakePagination,
TeamEventTypeOutput_2024_06_14,
UpdateTeamEventTypeInput_2024_06_14,
} from "@calcom/platform-types";
export type EventTypeHandlerResponse = {
data: DatabaseTeamEventType[] | DatabaseTeamEventType;
status: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
};
@Controller({
path: "/v2/teams/:teamId/event-types",
version: API_VERSIONS_VALUES,
})
@DocsTags("Teams / Event Types")
export class TeamsEventTypesController {
constructor(
private readonly teamsEventTypesService: TeamsEventTypesService,
private readonly inputService: InputOrganizationsEventTypesService,
private readonly outputTeamEventTypesResponsePipe: OutputTeamEventTypesResponsePipe
) {}
@Roles("TEAM_ADMIN")
@PlatformPlan("ESSENTIALS")
@UseGuards(ApiAuthGuard, RolesGuard)
@Post("/")
@ApiOperation({ summary: "Create an event type" })
async createTeamEventType(
@GetUser() user: UserWithProfile,
@Param("teamId", ParseIntPipe) teamId: number,
@Body() bodyEventType: CreateTeamEventTypeInput_2024_06_14
): Promise<CreateTeamEventTypeOutput> {
const transformedBody = await this.inputService.transformAndValidateCreateTeamEventTypeInput(
user.id,
teamId,
bodyEventType
);
const eventType = await this.teamsEventTypesService.createTeamEventType(user, teamId, transformedBody);
return {
status: SUCCESS_STATUS,
data: await this.outputTeamEventTypesResponsePipe.transform(eventType),
};
}
@Roles("TEAM_ADMIN")
@UseGuards(ApiAuthGuard, RolesGuard)
@Get("/:eventTypeId")
@ApiOperation({ summary: "Get an event type" })
async getTeamEventType(
@Param("teamId", ParseIntPipe) teamId: number,
@Param("eventTypeId") eventTypeId: number
): Promise<GetTeamEventTypeOutput> {
const eventType = await this.teamsEventTypesService.getTeamEventType(teamId, eventTypeId);
if (!eventType) {
throw new NotFoundException(`Event type with id ${eventTypeId} not found`);
}
return {
status: SUCCESS_STATUS,
data: (await this.outputTeamEventTypesResponsePipe.transform(
eventType
)) as TeamEventTypeOutput_2024_06_14,
};
}
@Roles("TEAM_ADMIN")
@Post("/:eventTypeId/create-phone-call")
@UseGuards(ApiAuthGuard, RolesGuard)
@ApiOperation({ summary: "Create a phone call" })
async createPhoneCall(
@Param("eventTypeId") eventTypeId: number,
@Param("orgId", ParseIntPipe) orgId: number,
@Body() body: CreatePhoneCallInput,
@GetUser() user: UserWithProfile
): Promise<CreatePhoneCallOutput> {
const data = await handleCreatePhoneCall({
user: {
id: user.id,
timeZone: user.timeZone,
profile: { organization: { id: orgId } },
},
input: { ...body, eventTypeId },
});
return {
status: SUCCESS_STATUS,
data,
};
}
@Get("/")
@ApiOperation({ summary: "Get a team event type" })
async getTeamEventTypes(
@Param("teamId", ParseIntPipe) teamId: number,
@Query() queryParams: GetTeamEventTypesQuery_2024_06_14
): Promise<GetTeamEventTypesOutput> {
const { eventSlug } = queryParams;
if (eventSlug) {
const eventType = await this.teamsEventTypesService.getTeamEventTypeBySlug(teamId, eventSlug);
return {
status: SUCCESS_STATUS,
data: await this.outputTeamEventTypesResponsePipe.transform(eventType ? [eventType] : []),
};
}
const eventTypes = await this.teamsEventTypesService.getTeamEventTypes(teamId);
return {
status: SUCCESS_STATUS,
data: await this.outputTeamEventTypesResponsePipe.transform(eventTypes),
};
}
@Roles("TEAM_ADMIN")
@UseGuards(ApiAuthGuard, RolesGuard)
@Patch("/:eventTypeId")
@ApiOperation({ summary: "Update a team event type" })
async updateTeamEventType(
@Param("teamId", ParseIntPipe) teamId: number,
@Param("eventTypeId", ParseIntPipe) eventTypeId: number,
@GetUser() user: UserWithProfile,
@Body() bodyEventType: UpdateTeamEventTypeInput_2024_06_14
): Promise<UpdateTeamEventTypeOutput> {
const transformedBody = await this.inputService.transformAndValidateUpdateTeamEventTypeInput(
user.id,
eventTypeId,
teamId,
bodyEventType
);
const eventType = await this.teamsEventTypesService.updateTeamEventType(
eventTypeId,
teamId,
transformedBody,
user
);
return {
status: SUCCESS_STATUS,
data: await this.outputTeamEventTypesResponsePipe.transform(eventType),
};
}
@Roles("TEAM_ADMIN")
@UseGuards(ApiAuthGuard, RolesGuard)
@Delete("/:eventTypeId")
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: "Delete a team event type" })
async deleteTeamEventType(
@Param("teamId", ParseIntPipe) teamId: number,
@Param("eventTypeId", ParseIntPipe) eventTypeId: number
): Promise<DeleteTeamEventTypeOutput> {
const eventType = await this.teamsEventTypesService.deleteTeamEventType(teamId, eventTypeId);
return {
status: SUCCESS_STATUS,
data: {
id: eventTypeId,
title: eventType.title,
},
};
}
}

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