Compare commits

...
191 Commits
Author SHA1 Message Date
Morgan af524d9e93 fix: enable event-type booking field url with api v2 (#19577)
Post release / release (push) Canceled after 0s
* fix: enable event-type booking field url with api v2

* fixup! fix: enable event-type booking field url with api v2

* fixup! fixup! fix: enable event-type booking field url with api v2

* fixup! fixup! fixup! fix: enable event-type booking field url with api v2
2025-02-26 19:12:41 +00:00
GitHub Actions 6b7ced262d chore: release v5.0.7 2025-02-26 19:12:07 +00:00
Eunjae Lee 7a797490c8 feat: support attendee name and email filter on /bookings (#19565)
* feat: support attendee name and email filter on /bookings

* remove console log

* change label
2025-02-26 18:48:36 +01:00
Morgan 3c367dd2c8 fix: phone input and week view missing styles atoms (#19581)
* fix: phone input missing styles atoms

* fixup! fix: phone input missing styles atoms
2025-02-26 17:44:14 +00:00
Morgan 00f50a9449 feat: booker atom prevent event type success redirect (#19573) 2025-02-26 18:54:03 +02:00
Hariom Balhara 381e22ae7e test: Salesforce CRM - Add user facing tests and more logs (#19531)
* Added user facing tests

* fix tests

* Fix ts error
2025-02-26 22:21:36 +05:30
Anik Dhabal BabuandTushar Bhatt 3850b519fd fix: time slot doesn't select in email embed (#19523)
Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>
2025-02-26 21:13:17 +05:30
Calcom BotandLingo.dev 78473bab1b feat: update translations via @lingodotdev (#19576)
Co-authored-by: Lingo.dev <support@lingo.dev>
2025-02-26 15:37:26 +00:00
Lauris Skraucis e437dfa000 refactor: platform default event types (#19225)
* feat: add areDefaultEventTypesEnabled to PlatformOAuthClient

* feat: specify areDefaultEventTypesEnabled when creating OAuth client

* feat: specify areDefaultEventTypesEnabled when updating OAuth client

* feat: display areDefaultEventTypesEnabled in OAuth clients list

* refactor: set areDefaultEventTypesEnabled by default to false on API level

* feat: v2 API CREATE managed user toggle default event types

* refactor: centralize OAuth inputs and outputs in platform/types

* fix: correct response types for OAuth hooks

* refactor: web/lib/hooks/settings/platform/oauth-clients/useOAuthClients.ts

* refactor: web/lib/hooks/settings/platform/oauth-clients/useOAuthClients.ts

* refactor: split web OAuth hooks into separate files

* refactor: split web OAuth hooks into separate files

* docs: v2 OAuth client inputs and outputs

* refactor: update and create oauth client inputs
2025-02-26 12:06:08 -03:00
07789ba697 feat: Introduce a 'slot no longer available' message (#18935)
* feat: Don't allow unavailable slot's booking form to be visible - Send back to slots listing

* Improvements

* feat: Add env variables and strategies to prevent booking failures

- Added new environment variables for configuring slot reservation and availability checks
- Implemented strategies to handle concurrent bookings and slot availability
- Updated Booker component and related files to support new reservation and slot checking mechanisms
- Added README with detailed explanation of booking prevention strategies
- Configured dynamic intervals for slot and reservation queries

* docs: Update Booker README with detailed slot reservation and availability explanation

- Clarified slot reservation behavior when multiple users access the same booking page
- Added details about `getSchedule` refetching strategies and timing
- Explained how slot availability is detected and communicated to users

* Support for skip confirmation form flow

* feat: Enhance slot availability and reservation mechanism

- Refactored slot availability checking to support multiple slots
- Added tentative selected timeslots to improve booking UX
- Updated trpc handler to check availability for multiple slots
- Introduced new store methods for managing tentative slot selections
- Improved slot reservation and availability status tracking

* refactor: Improve slot availability quick check mechanism

- Renamed and restructured slot availability check parameters
- Extracted quick availability checks into a separate hook
- Updated type definitions for slot status and availability checks
- Simplified slot availability logic in Booker and related components
- Maintained cached state for quick availability checks

* Support minimu booking check too

* change data-testid

* Rneame

* Fix race condition with uid cookie not set

* fix tests

* Remove unsded variable

---------

Co-authored-by: Hariom Balhara <hariombalhara@gmgmail.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-02-26 16:49:26 +02:00
Peer Richelsen a6c6a46076 chore: small ooo translation fixes (#19569) 2025-02-26 08:42:53 -05:00
Eunjae Lee d44d74d2fc fix: apply routing form filter by default on /insights/routing (#19535)
* fix: mandate routing form filter on /insights/routing

* add e2e test

* update e2e test

* fix e2e test

* add comment
2025-02-26 14:39:49 +01:00
Morgan 52662b3375 fix: old v2 booking cancel endpoint issue (#19564)
* fix: old v2 booking cancel endpoint issue

* fixup! fix: old v2 booking cancel endpoint issue
2025-02-26 13:14:13 +00:00
8612fa71c7 feat: Manage Team ooo or crud (#16456)
* feature for team ooo crud and past records

* added tests for ooo handler, combined list components for mine,team

* nit: removed commented code

* added current-previous tab , not to show TeamOOO tab for nonadmin

* update for type checks

* updated tests after merge

* updated outofoffice handler after merge

* for alignment with outofoffice header column

* update after resolving merge conflicts

* nit/chore: spacing

* update after changes in router migration

* ui improvements rounded corner

* updated props

* Update apps/web/public/static/locales/en/common.json

Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>

* Update apps/web/public/static/locales/en/common.json

Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>

* updated dialog subtitles, review comments

* Update packages/features/settings/outOfOffice/CreateOrEditOutOfOfficeModal.tsx

Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com>

* Update packages/trpc/server/routers/loggedInViewer/outOfOffice.schema.ts

Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com>

* refactored to split ooo handlers, review comments

* updated test.utils

* chore

* chore: unrelated changes may be merge

* optimized query

* update due to latest changes and merge conflicts

* updates to changes in people filter

* chore

* as now taken care in DataTable

* updates after merge

* updates after merge due tp changes in datatable and others

* update import due to file splitting and new name

* update for typecheck

* update for new add button when empty entries

* nit

* replace tests with e2e tests

* chore

* include only manage team ooo

* fix type check

* Update safe-parse.ts

* use invalidate instead of props, leaving main server components as it is

* nit

* update forMember div ht in edit mode

---------

Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>
2025-02-26 11:39:35 +00:00
Benny JooandHariom Balhara caaecf2f94 chore: migrate /user embed pages (#19149)
* add user pages to config.matcher in middleware

* add app router user booking pages

* remove HeadSeo from users-public-view component

* remove pages router user booking pages

* fix type check

* fix embed

* fix test

* chore: remove BookerSEO from users-type-public-view

* fix

* migrate all /user embed pages to app router

* remove /future routes

* fix prefill not working with preload

* move to (booking-page-wrapper) route group

---------

Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2025-02-26 11:50:27 +01:00
Anik Dhabal BabuandPeer Richelsen 8741714402 fix: some ui fixes (#19558)
* fix

* Update SettingsLayoutAppDirClient.tsx

* Update packages/features/eventtypes/components/EventTypeLayout.tsx

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-02-26 10:13:24 +00:00
Eunjae Lee 271d9a5f61 chore: remove not used code related to filters on /bookings (#19450)
* chore: remove filter-related code that is no longer in use

* remove groupBy.ts
2025-02-26 09:42:19 +00:00
Eunjae Lee 3d3acba82a fix: refactor filter UIs on /bookings (#19532)
* Reapply "fix: replace filter implementations on bookings (#19445)" (#19506)

This reverts commit f6af6e34bd.

* force custom date range selector for bookings except for Past tab

* fix e2e test

* add e2e tests

* fix e2e test
2025-02-26 09:47:20 +01:00
Somay ChauhanandHariom Balhara ca1f84c827 fix: disable skip confirm for booker_layout=WEEK_VIEW (#19524)
* fix: disable skip confirm for booker_layout=WEEK_VIEW

* Make code clearer

---------

Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2025-02-26 11:15:55 +05:30
Lauris Skraucis a44bcafcf2 feat: v2 managed organizations (#19341)
* refactor: allow non unique PlatformBilling customerId

* feat: add PlatformBilling managed organizations fields

* feat: ManagedOrganization table

* refactor: bill overdue based on teamId

* refactor: restructure organizations module

* wip: organizations endpoints

* Revert "wip: organizations endpoints"

This reverts commit 0e9e66fc74f31da436f12930c1b6597c650ed621.

* refactor: unique index for managed organizations

* wip: organizations endpoints

* wip: create managed organization

* remove unecessary membership check because we have guard

* feat: create managed org

* feat: get managed org and orgs

* feat: update and delete managed orgs

* wip: api key logic

* feat: allow variable api key length

* feat: refresh managed org api key

* feat: create managed org OAuth clients using api key

* finish merge main

* chore: bump platform libraries

* tests: fix and add more tests to api-auth.strategy.e2e

* refactor: dont request managed org slug and handle metadata as object

* revert: billing service and repository update overdue based on sub and customer ids

* refactor: v2 OAuth client permissions (#19501)

* refactor: v2 permissions as string array

* refactor: frontend work with permissions as string

* tests: test '*' permissions

* fix:managed org creator have profile & test can fetch oauth client

* fix: tests

* fix: OAuthClientCard on frontend

* fix: tests
2025-02-25 18:10:46 -07:00
Anik Dhabal BabuandAlex van Andel e4ab8d87c4 fix: Attempted to call ZFormsInputSchema() from the server (#19540)
* fix: Attempted to call ZFormsInputSchema() from the server

* chore: type optimisation

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-02-26 00:39:46 +00:00
a4519e705d fix: No option to install/disconnect app from app detail page (#17997)
* fix: No option to install/disconnect app from app detail page

* Fix types

* fix: Install button showing up even after it is installed for all targers

* chore: Simplified installOrDisconnectAppButton making it easy to read

---------

Co-authored-by: Hariom <hariombalhara@gmail.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-02-26 00:08:59 +05:30
Tushar BhattandKeith Williams a3113607ff chore: pr-template updates to include demonstrations (#19533)
* updated - pr_template

* minor-change

* Update PULL_REQUEST_TEMPLATE.md

* Update PULL_REQUEST_TEMPLATE.md

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2025-02-25 13:01:39 +00:00
Benny Joo acf270bc61 fix: Encode usernames in booking url to UTF-8 to prevent 500 throws (#19475)
* fix: Encode usernames in booking url to UTF-8 to prevent throws

* add dynamic booking page e2e

* add 1 more test
2025-02-25 06:27:23 -05:00
Benny Joo d1a9af84b2 chore: migrate /api/avatar/[uuid] to App Router (#19514)
* chore: migrate /api/avatar/[uuid]

* fix type

* move location of apiRouteMiddleware and fix the args

* refactor
2025-02-25 11:19:29 +00:00
Benny Joo 6ea879f265 perf: run ssrInit() at root layout (#19460)
* wip

* remove ssrInit unneeded

* refactor

* revert unneeded changes

* update booking-page-wrapper layout
2025-02-25 06:08:23 -05:00
Keith WilliamsandOmar López 307b2946a2 perf: cache app store imports (#19519)
* perf: Cache app store imports

* Added a console log to see when imports happen

* Discard changes to yarn.lock

---------

Co-authored-by: Omar López <zomars@me.com>
2025-02-24 23:02:35 -03:00
GitHub Actions 23d9788dce chore: release v5.0.6
Post release / release (push) Canceled after 0s
2025-02-24 22:08:05 +00:00
caade0850a fix: consider sendToAll settings in routingForms response (#18226)
* update to consider sendToAll

* added tests for team routingForms selectAllMembers cases

* chore

* chore

* chore

* updated test case in case of toggle off

* tweak

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: unknown <adhabal2002@gmail.com>
2025-02-24 17:59:54 +00:00
Eunjae Lee f6af6e34bd Revert "fix: replace filter implementations on bookings (#19445)" (#19506)
This reverts commit 641193bd61.
2025-02-24 17:14:06 +00:00
Benny Joo 5f5cfaf7c7 perf: improve matching paths in middleware (#19491)
* perf: exclude next native paths from going through middleware

* fix build error

* fix

* fix
2025-02-24 16:53:06 +00:00
07a4aa6c7d fix: Fix for 'Scheduling by cal.com' is still showing in workflow emails even when branding is disabled (#18862)
* Branding Disabling on Team Workflows and Organization Workflows if branding is hidden

* update

* update

---------

Co-authored-by: unknown <adhabal2002@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-02-24 16:31:32 +00:00
Eunjae Lee 641193bd61 fix: replace filter implementations on bookings (#19445)
* fix: replace filter implementation on /bookings

* add eventTypeId column

* add eventType filter

* add team filter

* add people filter

* fix type error

* support date range filter

* fix empty view

* fix date range filter

* add comment

* fix type error

* fix type error

* fix type error

* fix type error

* fix type error

* address feedback

* remove reverted functionality
2025-02-24 17:11:40 +01:00
Eunjae Lee 2d372746d3 fix: /bookings get handler (#19369)
* fix: sorting on /bookings

* fix type erorr

* add filters to logging

* fix type error

* filter with attendee emails

* clean up filters

* add test from #19376

* fix e2e tests

* split ORs into smaller queries

* add missing imports
2025-02-24 13:11:29 -03:00
Peer Richelsen 4b2265c35d chore: removed experimental calcom license api call (#19366) 2025-02-24 14:58:25 +00:00
Peer Richelsen 4dc2d3236d Update .env.example (#19364) 2025-02-24 14:55:43 +00:00
+20 7bff15cc47 chore: replace toaster with sonner (#19342)
* fix: replace react-hot-toast with sonner for toast notifications

* feat: add country code (#19264)

* perf: Move PlainChat up the hierarchy to remove rerenders (#19255)

* perf: Move PlainChat up the hierarchy to remove rerenders

* rmeove yarn lock

---------

Co-authored-by: Nizzy <nizabizaher@gmail.com>
Co-authored-by: nizzy <140507264+nizzyabi@users.noreply.github.com>

* hotfix (#19266)

* chore: release v4.9.11

* Handle cancelled status (#19272)

* feat: Use new /routing URL for routing forms (#19235)

* feat: Use new /routing URL for routing forms

* Fixes

* Fix bug

* precent crash

---------

Co-authored-by: Hariom Balhara <hariombalhara@gmgmail.com>

* fix: remove section on /bookings if no data exists (#19261)

* feat: v2 slots new version (#18758)

* refactor: version old slots

* feat: init new slots endpoints

* chore: range format

* fix: duratin

* fix: duratin

* test: slot releaseAt

* refactor: reserve slot response

* refactor variable name

* docs: have new slots controller in docs

* feat: crud for slots reservations

* refactor: use exclude all for response

* docs

* chore: slots input service

* refactor mini

* refactor: remove unused imports

* docs

* handle orgSlug for dynamic events

* refactor: correct name

* docs

* add optional organizationSlug to BySlug search

* refactor: slot output format

* refactor: return seated slot info

* docs

* rename functions

* refactor: slots seated response

* fix: handle same username in org and non org

* refactor: test format

* fix: allow reservationDuration only for authed requests

* chore: check if auth user has permissions to define custom reservation duration

* refactor: split e2e test files

* refactor: invalid request exception codes

* chore: old slots controller uses all old versions

* refactor: remove depreceated fields (#19279)

* refactor: remove depreceated fields

* chore: use v2 endpoint

* chore: update V2 Api type

* chore

* chore: Refactor to remove `getServerSideProps` for /teams route (#19286)

* remove getServerSideProps

* refactor teams route

* chore: release v4.9.12

* fix: Salesforce - if no contact throw Error (#19271)

* Throw error if no contact is passed to createEvent

* chore: update error message

* chore

---------

Co-authored-by: Udit Takkar <udit222001@gmail.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>

* fix: missing await router controller (#19276)

* fix: Default people filter in bookings list for admin (#18035)

* default people filter for admin

* chore

* type check

* added test case

* made test concise to reduce flakiness

* add timeout to wait for second get response before counting

* update timeout

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>

* feat: add CSAT to V2 bookings return (#19278)

* init

* test: v2 bookings returns rating

---------

Co-authored-by: supalarry <laurisskraucis@gmail.com>
Co-authored-by: Lauris Skraucis <lauris.skraucis@gmail.com>

* chore: disable v2 booking seats safe parse error logs (#19292)

* revert: Reapply "fix: Multiple rr-hosts combine to create erroneous availabil… (#19263)

* Reapply "fix: Multiple rr-hosts combine to create erroneous availability (#18772)"

This reverts commit 5dbc6d9ca6.

* Only thing left is a diff to show which slots are removed

* Add logging around time slot results

* Setup logging through axiom

* .... forgot

* fix: type errors

* Only log when there are differences

* Updated from old which had a failing test to new logic

* chore: release v4.9.13

* fix: flaky test (#19294)

* fix: flaky test

* fix another test

* update

---------

Co-authored-by: Eunjae Lee <hey@eunjae.dev>
Co-authored-by: unknown <adhabal2002@gmail.com>

* chore: calendars controller v2 docs (#19291)

Co-authored-by: Bailey Pumfleet <bailey@pumfleet.co.uk>

* Merge branch 'main' into replace-toaster-with-sonner

* add ireland country code (#19117)

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

* perf: separate client vs server code from insights layout (#19285)

* add UpgradeTipWrapper

* refactor insights/layout.tsx

---------

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

* feat: Use Folders to organize SMS links on Dub (#19248)

* feat: Use Folders to organize SMS links on Dub

* Update yarn.lock

---------

Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
Co-authored-by: Bailey Pumfleet <bailey@pumfleet.co.uk>

* fix: removing-all-members-toggle-for-fh (#19277)

* fix : removing all members toggle for fh

* ux enhancements

* adding placeholder

* chore: release v5.0.0

* fix flake (#19306)

* chore: migrate `/apps/routing-forms/[...pages]` to App Router (#18956)

* wip

* fix

* fix

* refactor

* rename to routingServerSidePropsConfig

* refactor

* refactor

* add routing-link to useIsBookingPage hook

* remove Head component

* fix

* redirect user to apps/routing-forms/forms if user goes to apps/routing-forms

* refactor

* remove log

* remove client component not needed

* clean up code

* remove unneeded metadata

* clean up further

* clean up further 2

* fix type check

* routing-link does not need shell

* Fix title for Routing Form public link and also remove any

* Remove ; in HTML

* Remove unnecessary page reload

---------

Co-authored-by: Hariom Balhara <hariombalhara@gmgmail.com>

* chore: migrate api for team upgrade to App Router (#19100)

* remove old pages router api

* add new app router api

* fix

* fix redirect

* refactor

* fix: cut off and alignment bug (#19317)

* fix: assignment label cut-off

* fix: add all team members label is vertically aligned

* fix: nested scrolls on /bookings (#19284)

* fix: Can't change availability for managed event type (#19006)

* fix: flaky test organization.spec

* fix

* fix: bulk-update-in-scheduleId-in-detailed-view (#19295)

* fix: bulk-update-in-scheduleId-in-detailed-view

* minor-change

---------

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

* feat: prevent automatic query parameters when opening booking page (#18132)

- Resolve the user hindrance where the event's booking page should not have search parameters such as date and month in the initial page load
- Contains changes for the fix of issue #18094 as well as it is needed

Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>

* feat: atoms adjustments with ui v3 styles (#19320)

* refactor: Clean out old code, no longer needed (#19323)

* refactor: Clean out old code, no longer needed

* Removed a sneaky one keen to stay behind

* chore: release v5.0.1

* feat: Create `UserCreationService` and use in API V1 create user endpoint (#19150)

* Create `createUser` method in `userCreationService`

* Refactor `UserRepository` create method to accept prisma input and remove business logic

* API use `UserCreationService`

* Move slugify to service

* Use hashPassword instead

* Type fixes in `UserCreationService`

* Add `userCreationService` tests

* API accept data object

* Type fixes

* Add user _post test

* Add test for locked user

* Add locked param to log

* Add user repository tests

* Do not return locked status

* Explicitly pass `locked` prop

* Fix tests when locked isn't returned

* Fix tests

* Pass locked prop

* Edit test name

* Use logger

* Fix passing hashed password

* fix (#19298)

* fix: timezone input text is now visible in dark mode (#19325)

* feat: make first tab active by default (#19315)

* feat: make first tab active by default

* perf: optimize event types tabs rendering with useMemo

---------

Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>

* perf: Use one PageWrapper instance for all settings pages (#18752)

* add a layoutfile to use-page-wrapper route group

* refactor and move bookings status page to route group

* improve logic in pagesAndRewritePaths

* fix

* add use client directive

* move /403 and /500

* move /auth/error

* move /connect-and-join

* move /enterprise

* move /maintenance

* move /more

* move /upgrade

* chore: remove WithLayout from 8 low-risk single pages (#18745)

* move /403 and /500

* move /auth/error

* move /connect-and-join

* move /enterprise

* move /maintenance

* move /more

* move /upgrade

* move /availability pages

* move /event-types pages

* move /insights pages

* move /apps to use-page-wrapper group

* move /getting-started to use-page-wrapper group

* move /signup to use-page-wrapper group

* move /workflows to use-page-wrapper group

* move /video pages to use-page-wrapper group

* pass dehydratedState in layout

* pass dehydratedState in layout

* move settings/(settings-layout) to use-page-wrapper

* move settings/(admin-layout) to use-page-wrapper

* move remaining settings pages to (use-page-wrapper)

* fix test

* remove unused code

* remove unused files

* fix type check

* remove test tag

* remove page

* RSC should not default export client components

* fix: Can't use unsaved booking question as variable in event name (#18604)

Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>

* chore: remove WithLayout from not-found.tsx (#19331)

* fix: redirect logic in /settings/admin/apps (#19332)

* chore: v3 fixed filters, new profile view (#19312)

* fixed filters with badge

* aligned recurrence in bookings

* removed new badge

* new profile view

* fixed try for free button

* fixed form input

* fix: Issues with date changes in column view (#19258)

* fix: coulmn view date change

* Update store.ts

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>

* chore: fixed tooltip position for routing form (#19267)

* fixed tooltip position for routing form

* fixed offset

* fix: Fairness when routing (#18550)

* Partial push of new filters

* Let's always return the passed host array when a filter doesn't need to be applied

* fix: isFixed typing in same round robin host check

* Add main bulk of rewritten logic for routed fairness support

* Remove console.log

* Add getAttributeWithEnabledWeights to AttributeRepository

* Add OOO entry repository

* Use getOrderedListOfLuckyUsers in lead threshold filtering

* Shortfall already includes weight

* test against minShortfall

* first attempt to fix fallbacks

* Added testcase updates

* Partially fix filterHosts test

* Some test updates

* Removed email field from normalization

* fix no available users found error

* fix unit test

* remove fallback from same host reschedule return

* fixes and improvements for findQualifiedHosts

* include fallback logic in handleNewBooking

* use fallback in handleNewBooking

* fix for contact owner in handleNewBooking

* WIP - comment

* pass routingFormResponseId

* fix type error

* pass routingFormResponse

* fixes in treshold logic

* remove reason

* merge qualified and fallback availabilities

* fix type error

* add and fix tests

* clean up test file

* fix filterHostsBySameRoundRobinHost tests

* fix findQualifiedHosts.test.ts

* fix getRoutedUsers.test.ts

* fix tests

* fix isRerouting check

* fix start time for two weeks check

* fix fallback hosts

* fix test

* fallback hosts should also include qualified hosts

* fix type error

* fix typos

* add contact owner to fallbacks

* fix typo

* fix qualifiedRRUsers

* set fixed users when no hosts

* add tets + code clean up

* add test for reschedule with same host

* fix typo

* add more tests for findQualifiedHosts

* remove skip from test

* add comment

* remove unused code

* fix fallback users in loadAndValidateUsers

* improve naming for fallback

* rename missed fallback variable

* fix reschedule with same rr host in handleNewBooking

* fixes for fallback slots

* add more tests + small fixes for contact owner

* fix tests and type errors

* add logs for fallback

* add type:json to logger

* Fix small merge issue

* fix end time if two weeks are cut off

* add more tests for contact owner availability check

* add new logic for two weeks fallback

* fix reschedule same RR host test

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>

* fix: EditLocationDialog footer positioning and structure (#19335)

* fix: EditLocationDialog footer positioning and structure

* fix: make RescheduleDialog footer layout and button structure right

* fix: input dialogue glitch now works great

* made tests happy

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>

* Merge branch 'main' into replace-toaster-with-sonner

* chore: remove DefaultToast from toast.stories.mdx

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: Benny Joo <sldisek783@gmail.com>
Co-authored-by: Nizzy <nizabizaher@gmail.com>
Co-authored-by: nizzy <140507264+nizzyabi@users.noreply.github.com>
Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>
Co-authored-by: GitHub Actions <github-actions@github.com>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
Co-authored-by: Hariom Balhara <hariombalhara@gmgmail.com>
Co-authored-by: Eunjae Lee <hey@eunjae.dev>
Co-authored-by: Lauris Skraucis <lauris.skraucis@gmail.com>
Co-authored-by: Udit Takkar <udit222001@gmail.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Vijay <vijayraghav22@gmail.com>
Co-authored-by: supalarry <laurisskraucis@gmail.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: unknown <adhabal2002@gmail.com>
Co-authored-by: Bailey Pumfleet <bailey@pumfleet.co.uk>
Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: Steven Tey <stevensteel97@gmail.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>
Co-authored-by: amrit <iamamrit27@gmail.com>
Co-authored-by: Sanchit Tewari <46245135+sanchitttt@users.noreply.github.com>
Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com>
2025-02-24 11:48:38 -03:00
luzpaz 97ef32f7ca fix: typos in several package/ directories (#19495)
* fix: typos in packages/embeds
Found via codespell

* fix: typos in packages/lib
Found via codespell

* fix: typos in packages/trpc
Found via codespell
2025-02-24 14:44:08 +00:00
16a94fe712 chore: bump alby packages (#18406)
* chore: bump alby packages

* fix: update alby sdk version

* chore: update yarn.lock

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>
Co-authored-by: amrit <iamamrit27@gmail.com>
2025-02-24 11:25:20 -03:00
Cao HoangandAnik Dhabal Babu 8f29811d5a fix: Some errors breaking storybook build (#18767)
* fix: filters ui breaking in routing insights page

* fix: story book build errors

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-02-24 14:24:33 +00:00
Benny Joo a47cd5b106 chore: cleanup - Remove WithLayout HoC itself (#19490)
* remove future folder

* remove unused file

* remove unused files
2025-02-24 08:38:47 -05:00
Eunjae Lee 64aa19fcea revert: default people filter at bookings (#19486) 2025-02-24 14:31:00 +01:00
7c71b179c8 feat: extract bottom navigation logic into a custom hook (#19468)
* feat: extract bottom navigation logic into a custom hook

* tweak

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: unknown <adhabal2002@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-02-24 13:27:24 +00:00
luzpaz d485e5f621 fix: typos in packages/app-store (#19470)
Found via `codespell -q 3 -S "*.svg,./apps/web/public/static/locales,./packages/app-store/stripepayment/lib/currencyOptions.ts,./packages/lib/freeEmailDomainCheck/freeEmailDomains.ts" -L afterall,atleast,datea,fo,incase,ist,nam,notin,optionel,perview,reccuring`
2025-02-24 10:54:28 +00:00
Vijay aa8d0f78d6 error msg when end date not selected (#19485) 2025-02-24 10:26:32 +00:00
Sy SagarandAnik Dhabal Babu 564497ec2a feat(lexicalEditor): custom enter-key plugin (#15952)
* fix(team-description): break lines rendering

* chore(EventTypeDescription): useBreakLine hook for handling html line breaks

* feat(lexicalEditor): custom enter-key plugin

* test(customEditorPlugin): enter key usage

* Update customEnterKeyPlugin.tsx

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-02-24 14:12:12 +05:30
Anwar SadathandAnik Dhabal Babu 2089ad40ea fix: Wrong avatars shown in webhooks page (#19386)
* fix: Wrong avatars shown in webhooks page

* Fix teams showing wrong avatar

* Fix type error

* Remove unused function arguments

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-02-24 08:02:57 +00:00
42e94cd5b7 fix: Misaligned Select with input box (#19400)
* Aligned Select field with input

* Minor fix in alignment

---------

Co-authored-by: amrit <iamamrit27@gmail.com>
Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-02-24 07:54:48 +00:00
Peer Richelsen 4546bd8653 Update EnterpriseLicense.tsx (#19363) 2025-02-24 12:10:14 +05:30
Anik Dhabal Babu 2a89a5e249 fix: Username input field not in line (#19480) 2025-02-23 18:32:52 +00:00
Benny Joo aba7c6df7f perf: move all booking pages into (booking-page-wrapper) route group (#19321)
* update useIsBookingPage

* move team pages into use-page-wrapper route group

* update imports

* fix type check

* update

* update

* remove isBookingPage configure from booking client components

* move all booking pages to use-page-wrapper route group

* add checkIfBookingPage util

* update layout

* update AppProviders

* improve comments

* update

* update pagesAndRewritePaths logic

* refactor
2025-02-23 10:13:11 +01:00
Peer Richelsen 97348e2052 fixed FAB (#19469) 2025-02-23 03:34:58 -05:00
Steven Tey 30149dd100 Upgrade dub version (#19472) 2025-02-22 22:43:32 +00:00
Peer Richelsen d91ccd37e0 Revert "fixed FAB size (#19466)" (#19467)
This reverts commit 0bd90d1673.
2025-02-22 11:52:58 +00:00
Peer Richelsen 0bd90d1673 fixed FAB size (#19466) 2025-02-22 10:08:16 +00:00
Calcom BotandLingo.dev 6899b853ee feat: update translations via @lingodotdev (#19462)
Co-authored-by: Lingo.dev <support@lingo.dev>
2025-02-21 21:50:02 +00:00
Benny Joo b07d81d0b9 perf: do not use dynamic imports for settings client pages (#19461) 2025-02-21 13:27:27 -07:00
Vijay 22104f8d91 enable_pip_ui in dailyvideo (#19423) 2025-02-21 17:47:00 +00:00
Alex van Andel 26d2decea4 Revert "feat: display alert when leaving/reloading booking page (#18932)"
This reverts commit b0921fe90a.
2025-02-21 17:09:07 +00:00
Benny Joo b6d8dc0bd6 wip (#19446) 2025-02-21 16:51:24 +00:00
GitHub Actions 7c0cdcfc6d chore: release v5.0.5
Post release / release (push) Canceled after 0s
2025-02-21 16:12:41 +00:00
Anik Dhabal Babu ad23613599 fix: Issues in custom event name (#19405)
* fix: Issues in custom event name

* Update event.ts
2025-02-21 15:25:48 +00:00
luzpaz 71598a4389 fix: typos in packages/ui (#19434)
Found via `codespell -q 3 -S "*.svg,./apps/web/public/static/locales,./packages/app-store/stripepayment/lib/currencyOptions.ts,./packages/lib/freeEmailDomainCheck/freeEmailDomains.ts" -L afterall,atleast,datea,fo,incase,ist,nam,notin,optionel,perview,reccuring`
2025-02-21 15:06:49 +00:00
Hariom Balhara 2ce1828841 chore: More salesforce logs (#19409)
* More logs

* fix ts issue
2025-02-21 20:14:28 +05:30
Udit Takkar b287f7e047 docs: add help section for creating phone only event type (#19440)
* docs: add help section for creating phone only event type

* chore: add not
2025-02-21 15:25:28 +01:00
Benny Joo c2be796a5b chore: remove deprecated code, Meta & MetaProvider (#19407)
* chore: remove deprecated code Meta, MetaProvider

* fix type checks
2025-02-21 09:01:44 -05:00
Somay ChauhanandUdit Takkar 829bb63eb9 fix: skip confirm step followup (#19076)
* Fix: Resolved double-click issue on timeSlot in Booker Atom

* fix: show toast on booking error

* fix: type error

* Prevent the automatic change of bookerState when all fields are filled.

* fix: when a user clicks on a new timeslot, any previously displayed "Confirm" button should be hidden

* Update useSkipConfirmStep.ts

* fix: remove 2 states for slots

* Update useSlotsForDate.ts

* fix types

* use common types

* fix: show VerifyCodeDialog and RedirectToInstantMeetingModal when skiping confirm step

* fix for instant bookings

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-02-21 19:07:54 +05:30
Alex van Andel 07accf700e refactor: Enabling typescript 5.3.3 in @calcom/trpc (#19394)
* Refactors related to enabling typescript 5.3.3 in @calcom/trpc

* Also skip respective tests (obviously logic is broken)

* This causes problems for some reason, revert

* Bring back QueryCell as it's used by atoms
2025-02-21 13:22:31 +00:00
Rajiv Sahal 46f73e79c1 fix: booking fields being overridden whenever saving with atom (#19339)
* fix booking fields not saving properly

* fixup
2025-02-21 12:42:11 +01:00
Udit Takkar b0921fe90a feat: display alert when leaving/reloading booking page (#18932)
* feat: display alert when leaving/reloading booking page

* feat: add recurring booking as well

* refactor: use use callback

* chore: add comment
2025-02-21 10:20:05 +00:00
Anik Dhabal Babu 3c956dd8e8 fix (#19399) 2025-02-21 08:56:23 +00:00
luzpaz 197a7ba6e9 fix: typos in packages/features (#19220)
Found via `codespell -q 3 -S "*.svg,./apps/web/public/static/locales,./packages/app-store/stripepayment/lib/currencyOptions.ts,./packages/lib/freeEmailDomainCheck/freeEmailDomains.ts" -L afterall,atleast,datea,fo,incase,ist,nam,notin,optionel,perview,reccuring`

Closes #19219
2025-02-21 05:14:57 -03:00
Lauris Skraucis e6daed762b feat: v2 routing forms responses endpoints (#19319)
* wip: routing forms responses

* refactor structure

* Revert "refactor structure"

This reverts commit b641c06592cd9314008e81c4584039bd42393ac7.

* routing forms

* remove unused file
2025-02-21 13:38:00 +05:30
Eunjae Lee 0b3aa4fd34 fix: preserve columnVisibility from initialState (#19412) 2025-02-21 08:56:51 +01:00
Pavan NaikandTushar Bhatt 4a6704c934 fix occurences issues in booking page (#19304)
Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>
2025-02-21 07:55:32 +00:00
Hariom Balhara fbcfc35621 fix crash due to an invalid state of connected field that was deleted (#19421) 2025-02-21 11:32:51 +05:30
GitHub Actions 0d2ec20f66 chore: release v5.0.4
Post release / release (push) Canceled after 0s
2025-02-20 22:50:23 +00:00
Benny JooandKeith Williams 01fc501cb9 chore: Block POST requests to all page routes except a whitelist (#19346)
* chore: block POST requests to next.js routes except a whitelist

* update config.matcher

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2025-02-20 17:19:35 -03:00
Nayan Bagale 1be002c33c fix: Issues with scheduling timezone change without end time (#19103)
* fix: Issues with scheduling timezone change without end time

* test: remove DatePicker component tests

* feat: implement DatePicker component with tests and update button data-testid
2025-02-20 19:19:55 +00:00
Benny Joo 8a4b03833d chore: remove org/team booking routes from middleware (#19349)
* chore: remove user routes from middleware

* chore: remove org and team routes from middleware
2025-02-20 15:30:13 -03:00
Calcom BotandLingo.dev 8714dda047 feat: update translations via @lingodotdev (#19417)
Co-authored-by: Lingo.dev <support@lingo.dev>
2025-02-20 18:18:14 +00:00
5b89123307 fix: fix youtube link and referral url (#19410)
* feat: Add 'Monobot CX' web application into cal.com app-store

* rollback yarn.lock

* fix: youtube link

* fix: change redirect url

* fix: config change redirect url

---------

Co-authored-by: Volodymyr Gusakovskyi <v.gusakovskyi@asferro.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-02-20 17:48:47 +00:00
Benny Joo 3221379584 chore: remove user routes from middleware (#19345) 2025-02-20 14:39:40 -03:00
Amit SharmaandTushar Bhatt 578f5dc16b feat: implement mintlify AI search into CMD+K (#18749)
Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>
2025-02-20 16:07:13 +00:00
amritandTushar Bhatt 3f042a1077 fix: reduce abnormal spacing in calendar invite (#19290)
* fix: reduce abnormal spacing in calendar invite

* add test for CalEventParser's getRichDescription

---------

Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>
2025-02-20 21:27:33 +05:30
Anik Dhabal Babu a44e7b2371 fix: multiselect is broken (#19351) 2025-02-20 13:22:34 +00:00
Hariom Balhara b06a94ab57 More dry run fixes (#18865) 2025-02-20 10:21:28 +00:00
Rajiv Sahal ec55454e43 separate phone input for web and platform (#19396) 2025-02-20 10:23:59 +01:00
Hariom Balhara 9ec0217858 chore: Add logs more (#19397) 2025-02-20 10:17:05 +01:00
amrit 66d69f5a06 fix: impersonation button alignment (#19383) 2025-02-20 06:45:45 +00:00
GitHub Actions b7b58c2dc7 chore: release v5.0.3
Post release / release (push) Canceled after 0s
2025-02-19 22:38:11 +00:00
Vachmara de1e19ee6d fix: Intercom app - book an event inside the messenger (#19391) 2025-02-19 21:21:22 +00:00
mintlify[bot] a366cb7c89 Documentation edits made through Mintlify web editor (#19084)
Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
2025-02-19 14:33:22 +00:00
yuriisilkov1986andVolodymyr Gusakovskyi dac336894c feat: Add 'Monobot CX' web application into cal.com app-store (#18505)
* feat: Add 'Monobot CX' web application into cal.com app-store

* rollback yarn.lock

---------

Co-authored-by: Volodymyr Gusakovskyi <v.gusakovskyi@asferro.com>
2025-02-19 13:40:07 +00:00
Harshit Singh 373c17a46d fix: Improved EventsLimit page for mobile viewports (#19270)
* Fixed mobile responsiveness UI  bugs

* Minor fix
2025-02-19 18:50:34 +05:30
Peer Richelsen 4c00c1ac2b added millis ai (#19357) 2025-02-19 18:20:47 +05:30
Özer 050a030ff0 fix(ui): prevent text descender cutoff in user dropdown (#19309) 2025-02-19 12:44:21 +00:00
Benny Joo dfb2232a59 chore: deprecate requiresLicense = true (#19374) 2025-02-19 13:33:03 +01:00
Amit SharmaandAnik Dhabal Babu 984ccf7c80 feat: Duration select dropdown multiple durations email embed (#17432)
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-02-19 12:29:52 +00:00
Hariom Balhara e87168322c fix: Dont crash entire listing if one form has faulty JSON fields (#19368)
* Dont hit members matching endpoint for regular team forms

* fix tests

* Dont crash and instead show the form in readonly mode
2025-02-19 11:05:29 +00:00
Anwar Sadath bf9e9b4ae1 fix: Show loading indicator when delete account API is in progress (#19361) 2025-02-19 10:20:20 +00:00
Peer Richelsen 6d4b05cf1d Update README.md 2025-02-19 10:48:15 +01:00
Peer Richelsen bd1af4027f Update README.md 2025-02-19 10:47:45 +01:00
Peer Richelsen 3872175393 Update LICENSE 2025-02-19 10:27:35 +01:00
Peer Richelsen 5ca063d4e8 Update custom-css.mdx 2025-02-19 10:24:27 +01:00
Peer Richelsen 112aa8201f Update introduction.mdx 2025-02-19 10:22:21 +01:00
Hariom Balhara 17fcc2c213 fix: Test preview - Routing forms crash for regular teams(that are not sub-teams) (#19353) 2025-02-19 08:20:26 +00:00
amritandPeer Richelsen d3f1dc1b32 fix: tanstack getRight error, focus in user impersonation, missing space after input fields, border in my-profile email (#19350)
* fix: shadow after email and before the primary label

* fix: autofill input shadow in impersonation view

* fix: improve spacing and layout in EditUserForm

* fix: error due to getRight

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-02-19 13:23:11 +05:30
Hariom BalharaandhbjORbj 25f3368fa1 fix: Plain Chat loading in embed (#19348)
* PlainChat has to be on dashboard and not on booking pages

* improve useIsBookingPage

---------

Co-authored-by: hbjORbj <sldisek783@gmail.com>
2025-02-19 06:40:32 +00:00
9a271f397b fix: empty hosts array in filterHostsByLeadThreshold (#19343)
* return early if hosts is empty

* feedback

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

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-02-18 18:19:44 +00:00
GitHub Actions 6847781a7f chore: release v5.0.2
Post release / release (push) Canceled after 0s
2025-02-18 16:07:40 +00:00
amritandPeer Richelsen 2d9a3bd741 fix: EditLocationDialog footer positioning and structure (#19335)
* fix: EditLocationDialog footer positioning and structure

* fix: make RescheduleDialog footer layout and button structure right

* fix: input dialogue glitch now works great

* made tests happy

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-02-18 15:23:40 +00:00
649faf4ff6 fix: Fairness when routing (#18550)
* Partial push of new filters

* Let's always return the passed host array when a filter doesn't need to be applied

* fix: isFixed typing in same round robin host check

* Add main bulk of rewritten logic for routed fairness support

* Remove console.log

* Add getAttributeWithEnabledWeights to AttributeRepository

* Add OOO entry repository

* Use getOrderedListOfLuckyUsers in lead threshold filtering

* Shortfall already includes weight

* test against minShortfall

* first attempt to fix fallbacks

* Added testcase updates

* Partially fix filterHosts test

* Some test updates

* Removed email field from normalization

* fix no available users found error

* fix unit test

* remove fallback from same host reschedule return

* fixes and improvements for findQualifiedHosts

* include fallback logic in handleNewBooking

* use fallback in handleNewBooking

* fix for contact owner in handleNewBooking

* WIP - comment

* pass routingFormResponseId

* fix type error

* pass routingFormResponse

* fixes in treshold logic

* remove reason

* merge qualified and fallback availabilities

* fix type error

* add and fix tests

* clean up test file

* fix filterHostsBySameRoundRobinHost tests

* fix findQualifiedHosts.test.ts

* fix getRoutedUsers.test.ts

* fix tests

* fix isRerouting check

* fix start time for two weeks check

* fix fallback hosts

* fix test

* fallback hosts should also include qualified hosts

* fix type error

* fix typos

* add contact owner to fallbacks

* fix typo

* fix qualifiedRRUsers

* set fixed users when no hosts

* add tets + code clean up

* add test for reschedule with same host

* fix typo

* add more tests for findQualifiedHosts

* remove skip from test

* add comment

* remove unused code

* fix fallback users in loadAndValidateUsers

* improve naming for fallback

* rename missed fallback variable

* fix reschedule with same rr host in handleNewBooking

* fixes for fallback slots

* add more tests + small fixes for contact owner

* fix tests and type errors

* add logs for fallback

* add type:json to logger

* Fix small merge issue

* fix end time if two weeks are cut off

* add more tests for contact owner availability check

* add new logic for two weeks fallback

* fix reschedule same RR host test

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
2025-02-18 14:59:48 +00:00
Peer Richelsen 03346f04ed chore: fixed tooltip position for routing form (#19267)
* fixed tooltip position for routing form

* fixed offset
2025-02-18 14:11:09 +00:00
Anik Dhabal BabuandUdit Takkar 99260974f4 fix: Issues with date changes in column view (#19258)
* fix: coulmn view date change

* Update store.ts

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-02-18 18:46:46 +05:30
Peer Richelsen 4a493c0a0e chore: v3 fixed filters, new profile view (#19312)
* fixed filters with badge

* aligned recurrence in bookings

* removed new badge

* new profile view

* fixed try for free button

* fixed form input
2025-02-18 12:23:30 +00:00
Benny Joo 47435c36ff fix: redirect logic in /settings/admin/apps (#19332) 2025-02-18 11:24:13 +00:00
Benny Joo 599744b31c chore: remove WithLayout from not-found.tsx (#19331) 2025-02-18 11:07:16 +00:00
Amit SharmaandTushar Bhatt d2c4c45137 fix: Can't use unsaved booking question as variable in event name (#18604)
Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>
2025-02-18 16:11:40 +05:30
Benny Joo 43ba47a122 perf: Use one PageWrapper instance for all settings pages (#18752)
* add a layoutfile to use-page-wrapper route group

* refactor and move bookings status page to route group

* improve logic in pagesAndRewritePaths

* fix

* add use client directive

* move /403 and /500

* move /auth/error

* move /connect-and-join

* move /enterprise

* move /maintenance

* move /more

* move /upgrade

* chore: remove WithLayout from 8 low-risk single pages (#18745)

* move /403 and /500

* move /auth/error

* move /connect-and-join

* move /enterprise

* move /maintenance

* move /more

* move /upgrade

* move /availability pages

* move /event-types pages

* move /insights pages

* move /apps to use-page-wrapper group

* move /getting-started to use-page-wrapper group

* move /signup to use-page-wrapper group

* move /workflows to use-page-wrapper group

* move /video pages to use-page-wrapper group

* pass dehydratedState in layout

* pass dehydratedState in layout

* move settings/(settings-layout) to use-page-wrapper

* move settings/(admin-layout) to use-page-wrapper

* move remaining settings pages to (use-page-wrapper)

* fix test

* remove unused code

* remove unused files

* fix type check

* remove test tag

* remove page

* RSC should not default export client components
2025-02-18 04:43:25 -05:00
amritandTushar Bhatt 0048b2d92c feat: make first tab active by default (#19315)
* feat: make first tab active by default

* perf: optimize event types tabs rendering with useMemo

---------

Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>
2025-02-18 14:42:03 +05:30
amrit 9dc0570d38 fix: timezone input text is now visible in dark mode (#19325) 2025-02-18 05:46:10 +00:00
Anik Dhabal Babu 1fbfca958a fix (#19298) 2025-02-18 11:08:10 +05:30
Joe Au-Yeung 7a6c93795a feat: Create UserCreationService and use in API V1 create user endpoint (#19150)
* Create `createUser` method in `userCreationService`

* Refactor `UserRepository` create method to accept prisma input and remove business logic

* API use `UserCreationService`

* Move slugify to service

* Use hashPassword instead

* Type fixes in `UserCreationService`

* Add `userCreationService` tests

* API accept data object

* Type fixes

* Add user _post test

* Add test for locked user

* Add locked param to log

* Add user repository tests

* Do not return locked status

* Explicitly pass `locked` prop

* Fix tests when locked isn't returned

* Fix tests

* Pass locked prop

* Edit test name

* Use logger

* Fix passing hashed password
2025-02-17 22:30:39 -05:00
GitHub Actions 4481b232cc chore: release v5.0.1
Post release / release (push) Canceled after 0s
2025-02-17 20:02:39 +00:00
Alex van Andel 84b265cd54 refactor: Clean out old code, no longer needed (#19323)
* refactor: Clean out old code, no longer needed

* Removed a sneaky one keen to stay behind
2025-02-17 19:39:20 +00:00
Rajiv Sahal eb86064995 feat: atoms adjustments with ui v3 styles (#19320) 2025-02-17 16:58:47 +02:00
Sanchit TewariandTushar Bhatt 39fdf5a74e feat: prevent automatic query parameters when opening booking page (#18132)
- Resolve the user hindrance where the event's booking page should not have search parameters such as date and month in the initial page load
- Contains changes for the fix of issue #18094 as well as it is needed

Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>
2025-02-17 14:41:00 +00:00
Tushar BhattandAnik Dhabal Babu f28c605b50 fix: bulk-update-in-scheduleId-in-detailed-view (#19295)
* fix: bulk-update-in-scheduleId-in-detailed-view

* minor-change

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-02-17 14:39:27 +00:00
Anik Dhabal Babu 63d26c4fba fix: Can't change availability for managed event type (#19006)
* fix: flaky test organization.spec

* fix
2025-02-17 13:59:39 +00:00
Eunjae Lee 14bba343a4 fix: nested scrolls on /bookings (#19284) 2025-02-17 10:25:42 +01:00
amrit e441f3308f fix: cut off and alignment bug (#19317)
* fix: assignment label cut-off

* fix: add all team members label is vertically aligned
2025-02-17 08:21:26 +00:00
Benny Joo b4aad453cd chore: migrate api for team upgrade to App Router (#19100)
* remove old pages router api

* add new app router api

* fix

* fix redirect

* refactor
2025-02-17 12:07:13 +05:30
Benny JooandHariom Balhara dc7a1c4680 chore: migrate /apps/routing-forms/[...pages] to App Router (#18956)
* wip

* fix

* fix

* refactor

* rename to routingServerSidePropsConfig

* refactor

* refactor

* add routing-link to useIsBookingPage hook

* remove Head component

* fix

* redirect user to apps/routing-forms/forms if user goes to apps/routing-forms

* refactor

* remove log

* remove client component not needed

* clean up code

* remove unneeded metadata

* clean up further

* clean up further 2

* fix type check

* routing-link does not need shell

* Fix title for Routing Form public link and also remove any

* Remove ; in HTML

* Remove unnecessary page reload

---------

Co-authored-by: Hariom Balhara <hariombalhara@gmgmail.com>
2025-02-17 11:15:54 +05:30
Anik Dhabal Babu fd651133c2 fix flake (#19306) 2025-02-16 07:27:34 -03:00
GitHub Actions f0d2a1a051 chore: release v5.0.0
Post release / release (push) Canceled after 0s
2025-02-15 10:26:34 +00:00
Tushar Bhatt 62c7627775 fix: removing-all-members-toggle-for-fh (#19277)
* fix : removing all members toggle for fh

* ux enhancements

* adding placeholder
2025-02-15 10:14:56 +00:00
be53a20429 feat: Use Folders to organize SMS links on Dub (#19248)
* feat: Use Folders to organize SMS links on Dub

* Update yarn.lock

---------

Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
Co-authored-by: Bailey Pumfleet <bailey@pumfleet.co.uk>
2025-02-15 10:06:28 +00:00
Benny JooandAnik Dhabal Babu 5c6f52f1d4 perf: separate client vs server code from insights layout (#19285)
* add UpgradeTipWrapper

* refactor insights/layout.tsx

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-02-15 06:43:37 -03:00
Carina WollendorferandCarinaWolli 0e9e3e5012 add ireland country code (#19117)
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2025-02-15 06:28:44 -03:00
5d709cf63c feat: v3 of UI components (#19136)
* ui playground

* add types to ui

* push avatar ignore ts and eslint errors

* feat: V3 UI avatar  (#18997)

* avatar playground

* add overflow-hidden back for loading indicator

* update lock

* feat: v3/badge  (#18999)

* badge intro

* fix text on small badge

* add dark mode warning

* feat: v3/button (#19014)

* TOC

* wip buttons

* shadows

* secondary

* semantic colours

* minimal buttons

* update disabled states

* checkbox

* dropdown v3

* load icons

* fix design sections

* fix icon gap

* fix

* remove client component from rsc

* use peer as avatar

* gif

* fix button gap - dropdown iocn

* support start icon in dropdowns

* add alert demo + v3 component + darken semantic text

* base inputs and text field

* wip input

* input field addon/suffix

* toast page

* wip select

* match designs for input and select rounded

* fix

* fix select isloading transform

* fix multi icons transition rotation

* fix group heading

* range slider demo + range slider

* range slider popover design

* v3 dialog

* fix slider thumb size

* wrap in suspense for useSearchParam difference in next14+

* base of tabs + horizontal tabs

* fix select sizing to match input 36px

* fix dark mode hover on button

* target domState class for light/dark so we work on portal elements

* fix default bg on popover

* lightmode toasts + eleveation token

* empty screen

* intro to split button concept

* mass colour updates

* intro to themes

* remove i18n from label with name

* bouncy buttons

* feat: small select

* nav item dumb component

* full demo

* settings demo

* fix tabs

* fix mt

* fix dropdown feedback from loom

* alert fixes mentioned in loom

* push font-cal

* move to fumadocs

* fix avatar

* colors table

* add typeography

* icon + spacing guide

* add border radius and shadow tables

* fix colours and border radius

* remove prose undline via fumas fork

* fix icon buttons sizes

* button group component

* fix horizontal tabs

* tab fixes

* switches

* pagination component

* show toasts components raw

* sync with airtable

* add use client

* 10px on input again

* 10px in select also

* fix input height

* fix files merge

* fix loading state for icon buttons

* fix button fab

* Enable addon to now overflow to next line in DS

* use cal font for dialog text

* add avatar square variant

* fix select padding and menu size

* fix type errors

* fix type errors

* add switch small size and fix type errors

* fix ref types on input

* update web styles

* remove addonFilled to fix type errors

* push dialog fixes

* fix checkbox display

* remove prose from alert examples

* remove prose from all our component examples

* badge rounded-lg on lg size

* update colors

* force w/h on icon buttons instead of inheriting

* remove border-focus

* remove border-focus from tailwind config

* update tokens to match new colours

* add new border subtle tokens and add to toasts

* fix lg button padding

* fix and drastically improve rtl rests

* multi select use badges

* use badge design for select pills

* fix avatar alignment

* fix tests and remove redudant ones

* fix tests and remove redudant ones

* update atoms globals css

* extract tokens.css

* extract app.css

* force flex for atoms

* add @calcom/ui/css

* revert ui playground styles abstraction

* fix input focus states

* fix focus states for buttons

* feat: v3/app work (#19233)

* globals.css for app + event types listing search

* few app wide NITS

* fix select foucs within styling

* fix formbuilder switch styles

* fix disabled state of nested inputs

* workflow fixes

* webhook form fixes

* i18n on tabs info

* booking filters + tab

* fix filters spacing

* make first item so we get correct border radius if not default

* round radio group in create event types + make button small

* profile page

* update editor br

* button nits in existing places in the app

* fix timezone select and multilist in guest form

* fix text area on public booking page

* size small event types create

* margin on routing filter

* filters improvments

* routing insights fixes

* fix date filter range

* ooo fixes

* fix teams/members bulk actions

* create team UI

* i18n in useTabs instead of in tab component now

* Add event type setup border to availability

* fix bulk actions on org members table

* onboarding fixes

* fix input types with ref stripe comparision

* i18n fixes for platform

* update globals of atoms

* fix form builder firstname/lastname switch + correct footer useage

* fix select

* Revert "add @calcom/ui/css"

This reverts commit 0dd8f9012907a278cfede4a98f289cb0744c9244.

* revert tokens css

* Revert "extract app.css"

This reverts commit 10b998604816ad3310c24b36a02a638dabc5be24.

* linear nits

* workflow dropdown

* fix page theme heading sizes to match cards

* fix stepper for team creation

* adjust margin to FilterSearchField

* fix ooo icon

* fix booker and dark mode due to darkgray 50

* more dark mode fixes

* add size prop

---------

Co-authored-by: Eunjae Lee <hey@eunjae.dev>
Co-authored-by: Morgan Vernay <morgan@cal.com>

* remove ui-playground

* fix grow missing from merge

* add search icon data-test-id back to search

* fix FormAction style

* fix datatestid for apps and tabs

* change selector for team invitation e2e

* fix use data-testid from item instaed of using names

* rename upper case O

* fix unit tests data-testid

* fix unit tests data-testid

* more data-testid changes

* add data-testid to apps tab

* data-testid to installed appPage

* fix embed tests

* fix filter-popover-trigger

* use text-error and use dataId for locator

* more e2e improvment

* pass in single testId as button is now duplicate

* show field-error instead

* add test to eventtype tabs

* Add css vars to embed too\

* add scrollbar and change dialog overlay colour

* fix type

* use attribute instead of class for tab detection

* await promise

* use new tokens for sprite generation

* add correct testing Ids to e2e instead of button:text

* use testIds for creation of orgs

* Webhook receiver wait for 10 seconds

---------

Co-authored-by: Eunjae Lee <hey@eunjae.dev>
Co-authored-by: Morgan Vernay <morgan@cal.com>
Co-authored-by: Hariom <hariombalhara@gmail.com>
Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
2025-02-14 16:31:21 -05:00
MorganandBailey Pumfleet 0f67faeef3 chore: calendars controller v2 docs (#19291)
Co-authored-by: Bailey Pumfleet <bailey@pumfleet.co.uk>
2025-02-14 17:54:23 +00:00
1ff4f557f6 fix: flaky test (#19294)
Post release / release (push) Canceled after 0s
* fix: flaky test

* fix another test

* update

---------

Co-authored-by: Eunjae Lee <hey@eunjae.dev>
Co-authored-by: unknown <adhabal2002@gmail.com>
2025-02-14 16:25:54 +00:00
GitHub Actions 7e2c0bd29e chore: release v4.9.13 2025-02-14 16:25:10 +00:00
Alex van Andel 5b59cf9d9c revert: Reapply "fix: Multiple rr-hosts combine to create erroneous availabil… (#19263)
* Reapply "fix: Multiple rr-hosts combine to create erroneous availability (#18772)"

This reverts commit 5dbc6d9ca6.

* Only thing left is a diff to show which slots are removed

* Add logging around time slot results

* Setup logging through axiom

* .... forgot

* fix: type errors

* Only log when there are differences

* Updated from old which had a failing test to new logic
2025-02-14 12:34:56 -03:00
Lauris Skraucis d5420eda00 chore: disable v2 booking seats safe parse error logs (#19292) 2025-02-14 10:59:10 +00:00
c17ac67b3f feat: add CSAT to V2 bookings return (#19278)
* init

* test: v2 bookings returns rating

---------

Co-authored-by: supalarry <laurisskraucis@gmail.com>
Co-authored-by: Lauris Skraucis <lauris.skraucis@gmail.com>
2025-02-14 09:47:54 +00:00
VijayandPeer Richelsen b2763a6274 fix: Default people filter in bookings list for admin (#18035)
* default people filter for admin

* chore

* type check

* added test case

* made test concise to reduce flakiness

* add timeout to wait for second get response before counting

* update timeout

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-02-14 10:08:57 +01:00
Morgan 08b6f60407 fix: missing await router controller (#19276) 2025-02-13 21:38:43 +00:00
466b3e4c08 fix: Salesforce - if no contact throw Error (#19271)
* Throw error if no contact is passed to createEvent

* chore: update error message

* chore

---------

Co-authored-by: Udit Takkar <udit222001@gmail.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-02-13 16:01:46 -05:00
GitHub Actions 401209810a chore: release v4.9.12
Post release / release (push) Canceled after 0s
2025-02-13 17:53:44 +00:00
Benny Joo 9f34a840d0 chore: Refactor to remove getServerSideProps for /teams route (#19286)
* remove getServerSideProps

* refactor teams route
2025-02-13 17:46:56 +00:00
Udit Takkar 37f1535e1a refactor: remove depreceated fields (#19279)
* refactor: remove depreceated fields

* chore: use v2 endpoint

* chore: update V2 Api type

* chore
2025-02-13 17:34:33 +02:00
Lauris Skraucis 5dc81e8677 feat: v2 slots new version (#18758)
* refactor: version old slots

* feat: init new slots endpoints

* chore: range format

* fix: duratin

* fix: duratin

* test: slot releaseAt

* refactor: reserve slot response

* refactor variable name

* docs: have new slots controller in docs

* feat: crud for slots reservations

* refactor: use exclude all for response

* docs

* chore: slots input service

* refactor mini

* refactor: remove unused imports

* docs

* handle orgSlug for dynamic events

* refactor: correct name

* docs

* add optional organizationSlug to BySlug search

* refactor: slot output format

* refactor: return seated slot info

* docs

* rename functions

* refactor: slots seated response

* fix: handle same username in org and non org

* refactor: test format

* fix: allow reservationDuration only for authed requests

* chore: check if auth user has permissions to define custom reservation duration

* refactor: split e2e test files

* refactor: invalid request exception codes

* chore: old slots controller uses all old versions
2025-02-13 14:17:00 +00:00
Eunjae Lee 5a166ee430 fix: remove section on /bookings if no data exists (#19261) 2025-02-13 11:40:17 +01:00
Hariom BalharaandHariom Balhara f6f964d495 feat: Use new /routing URL for routing forms (#19235)
* feat: Use new /routing URL for routing forms

* Fixes

* Fix bug

* precent crash

---------

Co-authored-by: Hariom Balhara <hariombalhara@gmgmail.com>
2025-02-13 15:13:13 +05:30
Joe Au-Yeung 6364e85293 Handle cancelled status (#19272) 2025-02-13 12:59:41 +05:30
GitHub Actions 46add2bebc chore: release v4.9.11
Post release / release (push) Canceled after 0s
2025-02-12 19:22:01 +00:00
Syed Ali Shahbaz 8ada940dc7 hotfix (#19266) 2025-02-12 19:16:52 +00:00
d027f8004a perf: Move PlainChat up the hierarchy to remove rerenders (#19255)
* perf: Move PlainChat up the hierarchy to remove rerenders

* rmeove yarn lock

---------

Co-authored-by: Nizzy <nizabizaher@gmail.com>
Co-authored-by: nizzy <140507264+nizzyabi@users.noreply.github.com>
2025-02-12 19:13:54 +00:00
Udit Takkar cc2f16411b feat: add country code (#19264) 2025-02-12 20:09:37 +01:00
nizzy 15b58c1c13 fix: added youtube videos to tips.tsx sidebar (#19245)
* added youtube videos to tips.tsx sidebar

* replace video links with dubco go.cal.com links for tracking
2025-02-12 21:04:38 +05:30
Eunjae Lee 2d12ea7372 fix: path to impersonation page on side bar (#19260) 2025-02-12 13:43:30 +00:00
Eunjae Lee 06bf9cfbfe fix: indicate hidden columns on filter dropdown (#19259) 2025-02-12 13:33:10 +00:00
Alex van Andel 5dbc6d9ca6 Revert "fix: Multiple rr-hosts combine to create erroneous availability (#18772)"
This reverts commit f5dc22f145.
2025-02-12 13:15:04 +00:00
Morgan 486e3a386e chore: salesforce for Router / Booker atoms and api v2 (#19217)
* wip

* small refactor

* small refactor

* fixup! Merge branch 'main' into enable-salesforce-router-apiv2-atom

* crm props

* fixup! crm props

* bump platform libraries

* bump platform libraries
2025-02-12 15:04:38 +02:00
Tushar Bhatt 3a29327761 fix: overlapping-dropdown-bookings-page (#19216) 2025-02-12 10:45:47 +00:00
Benny Joo 4f226cd653 chore: remove unneeded props from AuthContainer and make its usages cleaner (#19191)
* refactor AuthContainer by removing app-dir related props

* fix
2025-02-12 05:19:16 -05:00
Benny Joo 207804bd97 perf: remove WithLayout HOC from private booking page and booking embed (#19189) 2025-02-12 11:15:08 +01:00
Benny Joo 7969789d60 wip (#19190) 2025-02-12 05:06:53 -05:00
Lauris Skraucis 67fb0e6719 fix: v2 slots not returning attendees and bookingUid info (#18858)
* fix: v2 slots not returning attendees and bookingUid info

* rename file

* finish merge main
2025-02-12 15:06:52 +05:30
Anik Dhabal Babuandsean-brydon 7f390b147a fix: CTA is hidden on mobile (#19241)
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
2025-02-12 09:26:08 +00:00
Benny Joo 1dc869971e fix: small ui bug in 404 pages (#19254) 2025-02-12 08:30:00 +00:00
Joe Au-YeungandUdit Takkar 3fe83bb45c fix: Salesforce bugs (#19250)
* incompleteBooking only search for leads if contact is not found

* Fix logic

* Abstract to functions

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-02-12 08:24:57 +00:00
Benny Joo 4fbeff31e7 fix: decode params used in query object in buildLegacyCtx (#19253)
* fix: decode params used in query object in buildLegacyCtx

* add tests

* fix
2025-02-12 07:58:46 +00:00
GitHub Actions e800341485 chore: release v4.9.10
Post release / release (push) Canceled after 0s
2025-02-11 19:48:09 +00:00
Alex van Andel f5dc22f145 fix: Multiple rr-hosts combine to create erroneous availability (#18772)
* wip: Open draft PR with passing test (should fail)

* Fix aggregatedAvailability by not merging rr host availability

* Added test for validating fixed host behaviour

* Add test for combined rr and fixed hosts

* Check date-ranges arent returned multiple times when offered by multiple rr hosts

* Also sort date ranges

* Adding failing test that should result in 5 slots, but returns 7 as it returns the same slots twice.

* Slots returns duplicate slots for overlapping date ranges

* As mergeOverlappingDateRanges enabled the unified start time, we need to reproduce this

* Do not 'prettify' slots to the same degree if they fall on different days

* Added test to prove an end date before start also works

* Use a string instead of number as key

* chore: Deprecate organizerTimeZone, effectively unused

* Adjust all dateRanges similarly

* Bring back eventTimeZone

* Remove adjustDateRanges in favour of slot generation changes

* Convert to tz after all logic is finished.

* clearer code flow

* Remove console.log + add failing test due to inverse order

* Address issue with inversion when date ranges are given out of order
2025-02-11 19:35:56 +00:00
Keith WilliamsandJoe Au-Yeung 4fd31db6ee perf: Use a limit for searching website in Salesforce (#19244)
* perf: Avoid leading wildcard for Salesforce

* use limit of 1 since we need 1 record

* use LOWER to check exact website match

* Revert the usage of LOWER since we need wider searches

* Add limits to queries

* Update packages/app-store/salesforce/lib/CrmService.ts

* Remove unneeded LIMIT statements

* Update packages/app-store/salesforce/lib/CrmService.ts

* Apply suggestions from code review

* Update packages/app-store/salesforce/lib/CrmService.ts

---------

Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com>
2025-02-11 19:17:23 +00:00
Keith Williams f58d3cf837 revert: "fix: bookings for guests added by organizer get cancelled wh… (#19243)
This reverts commit e29b42a02b.
2025-02-11 14:53:03 +00:00
Keith Williams fc79ea898a chore: Update CODEOWNERS to include more booking files (#19240) 2025-02-11 15:08:28 +01:00
Eunjae Lee 5a602f10e6 fix: select "Your account" for members by default on insights (#19236) 2025-02-11 12:39:40 +00:00
Kartik SainiandTushar Bhatt e29b42a02b fix: bookings for guests added by organizer get cancelled when rescheduled (#17820)
* fix: bookings for guests added by organizer get cancelled when rescheduled

* chore

---------

Co-authored-by: Tushar Bhatt <95581504+TusharBhatt1@users.noreply.github.com>
2025-02-11 17:56:09 +05:30
Benny Joo cdb57eaa59 fix: get user loggedin if accouont is found + add better error handling for new user creation (#19229) 2025-02-11 11:41:18 +00:00
Peer Richelsen 662ba8dfc6 chore: added impersonation to sidebar for admins (#19228) 2025-02-11 11:39:09 +00:00
Hariom BalharaandHariom Balhara 552d88ad6d Fallback if embedLibUrl is empty string (#19223)
Co-authored-by: Hariom Balhara <hariombalhara@gmgmail.com>
2025-02-11 14:56:31 +05:30
Lauris Skraucis 08bcc77e2c feat: v2 GET bookings updated at filters and sort (#19133)
* fix: make Booking.updatedAt update automatically

* feat: return updatedAt by bookings endpoints

* feat: GET bookings beforeUpdatedAt, afterUpdatedAt, sortUpdated params

* docs: api

* chore: bump platform-libraries

* refactor: sortUpdated -> sortUpdatedAt query param

* chore: delete wrong migration
2025-02-11 08:39:50 +00:00
anushka-0099 c211f181fc fix: the wprd on confirm booking button in japanese (#19230) 2025-02-11 04:16:05 +00:00
Rajiv SahalandMorgan Vernay cc6016aef3 chore: atoms and docs update (#19137)
* hide docs for old google connect endpoint

* update docs for atoms

* fix css styles for week view

* update v2 reference

* add dutch translations in cal provider

* fix: add nl i18n in BaseCalProvider

---------

Co-authored-by: Morgan Vernay <morgan@cal.com>
2025-02-10 20:05:28 +00:00
Pavan NaikandPavan 77d0fa9ff8 fix: the set as default apps issue with links #19176 (#19198)
* fix the set as default apps issue with links

* Allow (. _ -) in the Mirotalk link

---------

Co-authored-by: Pavan <pavannaik20@gmail.com>
2025-02-10 20:29:22 +01:00
Eunjae LeeandBenny Joo 720136fcf9 fix: replace filter implementations on /insights (#19033)
* fix: replace filter implementations on /insights

* add authorization for teamIds

* replace all the implementations

* provide eventTypeId

* remove log

* fix teamId for isAll

* fix Download button

* remove legacy implementations

* clean up

* nullish check

* remove unusable filters

* revert style

* fix type error

* fix e2e test

* fix type error

* fix type error

* fix e2e

* extract util method

* fix type error

* fix type error

* fix type error

---------

Co-authored-by: Benny Joo <sldisek783@gmail.com>
2025-02-10 20:28:48 +01:00
Benny Joo 9bf3732717 fix: RSC boundary error from auth/oauth2/authorize (#19226) 2025-02-10 19:18:25 +00:00
1113 changed files with 44815 additions and 17109 deletions
+16
View File
@@ -388,6 +388,12 @@ BLACKLISTED_GUEST_EMAILS=
NEXT_PUBLIC_VAPID_PUBLIC_KEY=
VAPID_PRIVATE_KEY=
# Mintlify chat api
# Power AI chat in for docs
NEXT_PUBLIC_MINTLIFY_CHAT_API_KEY=
NEXT_PUBLIC_CHAT_API_URL=
NEXT_PUBLIC_DOCS_URL=
# Custom privacy policy / terms URLs (for self-hosters: change to your privacy policy / terms URLs)
NEXT_PUBLIC_WEBSITE_PRIVACY_POLICY_URL=
NEXT_PUBLIC_WEBSITE_TERMS_URL=
@@ -406,3 +412,13 @@ 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=
## Env variables related to avoiding booking failures
# Request for checking reservation would be attempted to send every these seconds if the request is stale at that time
NEXT_PUBLIC_QUERY_RESERVATION_INTERVAL_SECONDS=
# Request for checking reservation of same slot would be sent only after this time has passed. It must be lower than PUBLIC_QUERY_RESERVATION_INTERVAL_SECONDS
NEXT_PUBLIC_QUERY_RESERVATION_STALE_TIME_SECONDS=
# Query available slots interval - Should be kept high in minutes as it could cause significant load on the system
NEXT_PUBLIC_QUERY_AVAILABLE_SLOTS_INTERVAL_SECONDS=
# Used to invalidate available slots when navigating to booking form
NEXT_PUBLIC_INVALIDATE_AVAILABLE_SLOTS_ON_BOOKING_FORM=0
+4 -1
View File
@@ -12,8 +12,11 @@
/packages/app-store/larkcalendar/**/* @calcom/Foundation
/packages/app-store/office365calendar/**/* @calcom/Foundation
/packages/app-store/zohocalendar/**/* @calcom/Foundation
/packages/core/getAggregatedAvailability/index.ts @calcom/Foundation
/packages/core/getAggregateWorkingHours.ts @calcom/Foundation
/packages/core/getUserAvailability.ts @calcom/Foundation
/packages/features/bookings/lib/handleNewBooking/**/* @calcom/Foundation
/packages/features/bookings/lib/**/* @calcom/Foundation
/packages/lib/server/getLuckyUser.ts @calcom/Foundation
/packages/lib/slots.ts @calcom/Foundation
/packages/platform/**/* @calcom/Platform
/packages/prisma/**/* @calcom/Foundation
+13 -3
View File
@@ -5,9 +5,19 @@
- Fixes #XXXX (GitHub issue number)
- Fixes CAL-XXXX (Linear issue number - should be visible at the bottom of the GitHub issue description)
<!-- Please provide a loom video for visual changes to speed up reviews
Loom Video: https://www.loom.com/
-->
## Visual Demo (For contributors especially)
A visual demonstration is strongly recommended, for both the original and new change **(video / image - any one)**.
#### Video Demo (if applicable):
- Show screen recordings of the issue or feature.
- Demonstrate how to reproduce the issue, the behavior before and after the change.
#### Image Demo (if applicable):
- Add side-by-side screenshots of the original and updated change.
- Highlight any significant change(s).
## Mandatory Tasks (DO NOT REMOVE)
+1
View File
@@ -96,3 +96,4 @@ apps/auth
!.yarn/releases
!.yarn/sdks
!.yarn/versions
i18n.cache
+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"
+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"
+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
+6
View File
@@ -0,0 +1,6 @@
undecided:
- "@calcom/app-store-cli"
- "@calcom/platform-constants"
- "@calcom/platform-enums"
- "@calcom/platform-types"
- "@calcom/platform-utils"
+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
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"
+3 -2
View File
@@ -2,6 +2,7 @@ API_KEY_PREFIX=cal_
DATABASE_URL="postgresql://postgres:@localhost:5450/calendso"
NEXT_PUBLIC_WEBAPP_URL=http://localhost:3000
# Get it in console.cal.com
# Get CALCOM_LICENSE_KEY here: https://go.cal.com/get-license
CALCOM_LICENSE_KEY=""
NEXT_PUBLIC_API_V2_ROOT_URL=http://localhost:5555
NEXT_PUBLIC_API_V2_ROOT_URL=http://localhost:5555
-10
View File
@@ -190,16 +190,6 @@ We make sure of this by not using next in dev, but next build && next start, if
See <https://github.com/vercel/next.js/blob/canary/packages/next/server/dev/hot-reloader.ts#L79>. Here in dev mode OPTIONS method is hardcoded to return only GET and OPTIONS as allowed method. Running in Production mode would cause this file to be not used. This is hot-reloading logic only.
To remove this limitation, we need to ensure that on local endpoints are requested by swagger at /api/v1 and not /v1
## Hosted api through cal.com
> _❗ WARNING: This is still experimental and not fully implemented yet❗_
Go to console.cal.com
Add a deployment or go to an existing one.
Activate API or Admin addon
Provide your `DATABASE_URL`
Now you can call api.cal.com?key=CALCOM_LICENSE_KEY, which will connect to your own databaseUrl.
## How to deploy
We recommend deploying API in vercel.
+4 -2
View File
@@ -2,7 +2,7 @@ import type { NextApiRequest } from "next";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import { UserCreationService } from "@calcom/lib/server/service/userCreationService";
import { CreationSource } from "@calcom/prisma/enums";
import { schemaUserCreateBodyParams } from "~/lib/validations/user";
@@ -93,7 +93,9 @@ async function postHandler(req: NextApiRequest) {
// If user is not ADMIN, return unauthorized.
if (!isSystemWideAdmin) throw new HttpError({ statusCode: 401, message: "You are not authorized" });
const data = await schemaUserCreateBodyParams.parseAsync(req.body);
const user = await prisma.user.create({ data: { ...data, creationSource: CreationSource.API_V1 } });
const user = await UserCreationService.createUser({
data: { ...data, creationSource: CreationSource.API_V1 },
});
req.statusCode = 201;
return { user };
}
+134
View File
@@ -0,0 +1,134 @@
import prismock from "../../../../../../tests/libs/__mocks__/prisma";
import type { Request, Response } from "express";
import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http";
import { describe, test, expect, vi } from "vitest";
import handler from "../../../pages/api/users/_post";
type CustomNextApiRequest = NextApiRequest & Request;
type CustomNextApiResponse = NextApiResponse & Response;
vi.mock("@calcom/lib/server/i18n", () => {
return {
getTranslation: (key: string) => {
return () => key;
},
};
});
vi.stubEnv("CALCOM_LICENSE_KEY", undefined);
describe("POST /api/users", () => {
test("should throw 401 if not system-wide admin", async () => {
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "POST",
body: {
email: "test@example.com",
username: "test",
},
});
req.isSystemWideAdmin = false;
await handler(req, res);
expect(res.statusCode).toBe(401);
});
test("should throw a 400 if no email is provided", async () => {
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "POST",
body: {
username: "test",
},
});
req.isSystemWideAdmin = true;
await handler(req, res);
expect(res.statusCode).toBe(400);
});
test("should throw a 400 if no username is provided", async () => {
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "POST",
body: {
email: "test@example.com",
},
});
req.isSystemWideAdmin = true;
await handler(req, res);
expect(res.statusCode).toBe(400);
});
test("should create user successfully", async () => {
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "POST",
body: {
email: "test@example.com",
username: "test",
},
prisma: prismock,
});
req.isSystemWideAdmin = true;
await handler(req, res);
expect(res.statusCode).toBe(200);
const userQuery = await prismock.user.findFirst({
where: {
email: "test@example.com",
},
});
expect(userQuery).toEqual(
expect.objectContaining({
email: "test@example.com",
username: "test",
locked: false,
organizationId: null,
})
);
});
test("should auto lock user if email is in watchlist", async () => {
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "POST",
body: {
email: "test@example.com",
username: "test",
},
prisma: prismock,
});
req.isSystemWideAdmin = true;
await prismock.watchlist.create({
data: {
type: "EMAIL",
value: "test@example.com",
severity: "CRITICAL",
createdById: 1,
},
});
await handler(req, res);
expect(res.statusCode).toBe(200);
const userQuery = await prismock.user.findFirst({
where: {
email: "test@example.com",
},
});
expect(userQuery).toEqual(
expect.objectContaining({
email: "test@example.com",
username: "test",
locked: true,
organizationId: null,
})
);
});
});
+3 -1
View File
@@ -30,7 +30,7 @@
"@axiomhq/winston": "^1.2.0",
"@calcom/platform-constants": "*",
"@calcom/platform-enums": "*",
"@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.94",
"@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.116",
"@calcom/platform-libraries-0.0.2": "npm:@calcom/platform-libraries@0.0.2",
"@calcom/platform-types": "*",
"@calcom/platform-utils": "*",
@@ -61,6 +61,7 @@
"helmet": "^7.1.0",
"ioredis": "^5.3.2",
"jsforce": "^1.11.0",
"lodash": "^4.17.21",
"luxon": "^3.4.4",
"nest-winston": "^1.9.4",
"next-auth": "^4.22.1",
@@ -90,6 +91,7 @@
"@types/supertest": "^2.0.12",
"jest": "^29.7.0",
"jest-date-mock": "^1.0.10",
"node-mocks-http": "^1.16.2",
"prettier": "^2.8.6",
"source-map-support": "^0.5.21",
"supertest": "^6.3.3",
+2 -2
View File
@@ -8,13 +8,13 @@ used in production, if you (and any entity that you represent) have agreed to,
and are in compliance with, the Cal.com Subscription Terms available
at https://cal.com/terms, or other agreements governing
the use of the Software, as mutually agreed by you and Cal.com, Inc ("Cal.com"),
and otherwise have a valid Cal.com Enterprise Edition subscription ("Commercial Subscription")
and otherwise have a valid Cal.com Commercial License ("Commercial License")
for the correct number of hosts as defined in the "Commercial Terms ("Hosts"). Subject to the foregoing sentence,
you are free to modify this Software and publish patches to the Software. You agree
that Cal.com and/or its licensors (as applicable) retain all right, title and interest in
and to all such modifications and/or patches, and all such modifications and/or
patches may only be used, copied, modified, displayed, distributed, or otherwise
exploited with a valid Commercial Subscription for the correct number of hosts.
exploited with a valid Commercial License for the correct number of hosts.
Notwithstanding the foregoing, you may copy and modify the Software for development
and testing purposes, without requiring a subscription. You agree that Cal.com and/or
its licensors (as applicable) retain all right, title and interest in and to all such
+5 -5
View File
@@ -4,15 +4,15 @@
<img src="https://user-images.githubusercontent.com/8019099/133430653-24422d2a-3c8d-4052-9ad6-0580597151ee.png" alt="Logo">
</a>
<a href="https://console.cal.com/">Get a License Key</a>
<a href="https://go.cal.com/get-license">Get a License Key</a>
</div>
# Enterprise Edition of API
# Commercial License of API
Welcome to the Enterprise Edition ("/ee") of the Cal.com API.
Welcome to the Commercial License of the Cal.com API.
Our philosophy is simple, all "Singleplayer APIs" are open-source under AGPLv3. All "Multiplayer APIs" are under a commercial license.
The [/ee](https://github.com/calcom/cal.com/tree/main/apps/api/v2/ee) subfolder is the place for all the **Enterprise Edition** features from our [hosted](https://cal.com/pricing) plan and enterprise-grade features for [Enterprise](https://cal.com/enterprise) such as SSO, SAML, OIDC, SCIM, SIEM and much more or [Platform](https://cal.com/platform) plan to build a marketplace.
The [/ee](https://github.com/calcom/cal.com/tree/main/apps/api/v2/ee) subfolder is the place for all the **Commercial License** features from our [hosted](https://cal.com/pricing) plan.
> _❗ WARNING: This repository is copyrighted (unlike our [main repo](https://github.com/calcom/cal.com)). You are not allowed to use this code to host your own version of app.cal.com without obtaining a proper [license](https://console.cal.com/) first❗_
> _❗ WARNING: This repository is copyrighted (unlike our [main repo](https://github.com/calcom/cal.com)). You are not allowed to use this code to host your own version of app.cal.com without obtaining a proper [license](https://go.cal.com/get-license) first❗_
@@ -1,5 +1,5 @@
import { BookingsController_2024_04_15 } from "@/ee/bookings/2024-04-15/controllers/bookings.controller";
import { ApiKeyRepository } from "@/modules/api-key/api-key-repository";
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
import { BillingModule } from "@/modules/billing/billing.module";
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.service";
@@ -11,7 +11,7 @@ import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule, RedisModule, TokensModule, BillingModule],
providers: [TokensRepository, OAuthFlowService, OAuthClientRepository, ApiKeyRepository],
providers: [TokensRepository, OAuthFlowService, OAuthClientRepository, ApiKeysRepository],
controllers: [BookingsController_2024_04_15],
})
export class BookingsModule_2024_04_15 {}
@@ -6,7 +6,7 @@ import { GetBookingsOutput_2024_04_15 } from "@/ee/bookings/2024-04-15/outputs/g
import { MarkNoShowOutput_2024_04_15 } from "@/ee/bookings/2024-04-15/outputs/mark-no-show.output";
import { hashAPIKey, isApiKey, stripApiKey } from "@/lib/api-key";
import { VERSION_2024_04_15, VERSION_2024_06_11, VERSION_2024_06_14 } from "@/lib/api-versions";
import { ApiKeyRepository } from "@/modules/api-key/api-key-repository";
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
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";
@@ -29,6 +29,7 @@ import {
Query,
NotFoundException,
UseGuards,
BadRequestException,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { ApiQuery, ApiExcludeController as DocsExcludeController } from "@nestjs/swagger";
@@ -98,7 +99,7 @@ export class BookingsController_2024_04_15 {
private readonly oAuthClientRepository: OAuthClientRepository,
private readonly billingService: BillingService,
private readonly config: ConfigService,
private readonly apiKeyRepository: ApiKeyRepository
private readonly apiKeyRepository: ApiKeysRepository
) {}
@Get("/")
@@ -189,18 +190,24 @@ export class BookingsController_2024_04_15 {
throw new InternalServerErrorException("Could not create booking.");
}
@Post("/:bookingId/cancel")
@Post("/:bookingUid/cancel")
async cancelBooking(
@Req() req: BookingRequest,
@Param("bookingId") bookingId: string,
@Param("bookingUid") bookingUid: string,
@Body() _: CancelBookingInput_2024_04_15,
@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) {
const isUidNumber = !isNaN(Number(bookingUid));
if (isUidNumber) {
throw new BadRequestException("Please provide booking uid instead of booking id.");
}
if (bookingUid) {
try {
req.body.id = parseInt(bookingId);
req.body.uid = bookingUid;
const res = await handleCancelBooking(
await this.createNextApiBookingRequest(req, oAuthClientId, undefined, isEmbed)
);
@@ -169,4 +169,19 @@ export class CreateBookingInput_2024_04_15 {
label?: string | undefined;
}
>;
@IsString()
@IsOptional()
@ApiPropertyOptional()
teamMemberEmail?: string;
@IsString()
@IsOptional()
@ApiPropertyOptional()
crmAppSlug?: string;
@IsString()
@IsOptional()
@ApiPropertyOptional()
crmOwnerRecordType?: string;
}
@@ -4,7 +4,7 @@ import { BookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/bo
import { InputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/input.service";
import { OutputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output.service";
import { EventTypesRepository_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.repository";
import { ApiKeyRepository } from "@/modules/api-key/api-key-repository";
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
import { BillingModule } from "@/modules/billing/billing.module";
import { BookingSeatModule } from "@/modules/booking-seat/booking-seat.module";
import { BookingSeatRepository } from "@/modules/booking-seat/booking-seat.repository";
@@ -29,7 +29,7 @@ import { Module } from "@nestjs/common";
BookingsRepository_2024_08_13,
EventTypesRepository_2024_06_14,
BookingSeatRepository,
ApiKeyRepository,
ApiKeysRepository,
],
controllers: [BookingsController_2024_08_13],
exports: [InputBookingsService_2024_08_13, OutputBookingsService_2024_08_13, BookingsService_2024_08_13],
@@ -309,6 +309,23 @@ describe("Bookings Endpoints 2024-08-13", () => {
placeholder: "matrix",
disableOnPrefill: false,
},
{
name: "video-url",
type: "url",
label: "video url",
sources: [
{
id: "user",
type: "user",
label: "User",
fieldRequired: true,
},
],
editable: "user",
required: false,
placeholder: "add video url",
disableOnPrefill: false,
},
],
},
user.id
@@ -455,7 +472,6 @@ describe("Bookings Endpoints 2024-08-13", () => {
// eslint-disable-next-line
// @ts-ignore
const data: GetSeatedBookingOutput_2024_08_13 = responseBody.data;
console.log("asap data", JSON.stringify(data, null, 2));
expect(data.attendees[0].name).toEqual(`${splitName.firstName} ${splitName.lastName}`);
expect(data.attendees[0].bookingFieldsResponses.name).toEqual(splitName);
} else {
@@ -500,6 +516,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
location: "https://meet.google.com/abc-def-ghi",
bookingFieldsResponses: {
"favorite-movie": "lord of the rings",
"video-url": "http://video-url.com",
},
};
return request(app.getHttpServer())
@@ -516,6 +533,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
if (responseDataIsBooking(responseBody.data)) {
const data: BookingOutput_2024_08_13 = responseBody.data;
expect(data.bookingFieldsResponses["favorite-movie"]).toEqual("lord of the rings");
expect(data.bookingFieldsResponses["video-url"]).toEqual("http://video-url.com");
} else {
throw new Error(
"Invalid response data - expected booking but received array of possibily recurring bookings"
@@ -167,6 +167,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
timeZone: "Europe/Rome",
},
},
rating: 10,
});
app = moduleRef.createNestApplication();
@@ -396,6 +397,12 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(createdAtDate.getTime()).toBeGreaterThanOrEqual(beforeCreate.getTime());
expect(createdAtDate.getTime()).toBeLessThanOrEqual(afterCreate.getTime());
// Check updatedAt date is between the time of the request and after the request
expect(data.updatedAt).toBeDefined();
const updatedAtDate = data.updatedAt ? new Date(data.updatedAt) : null;
expect(updatedAtDate?.getTime()).toBeGreaterThanOrEqual(beforeCreate.getTime());
expect(updatedAtDate?.getTime()).toBeLessThanOrEqual(afterCreate.getTime());
expect(data.metadata).toEqual(body.metadata);
createdBooking = data;
} else {
@@ -546,6 +553,30 @@ describe("Bookings Endpoints 2024-08-13", () => {
});
});
it("should should get a booking with rating", async () => {
return request(app.getHttpServer())
.get(`/v2/bookings/${bookingInThePast.uid}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(200)
.then(async (response) => {
const responseBody: GetBookingOutput_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).toEqual(bookingInThePast.id);
expect(data.uid).toEqual(bookingInThePast.uid);
expect(data.rating).toEqual(bookingInThePast.rating);
} else {
throw new Error(
"Invalid response data - expected booking but received array of possibily recurring bookings"
);
}
});
});
it("should should get 1 recurrence of a recurring booking", async () => {
const recurrenceUid = createdRecurringBooking[0].uid;
return request(app.getHttpServer())
@@ -869,7 +900,63 @@ describe("Bookings Endpoints 2024-08-13", () => {
it("should should get bookings by before specified end time", async () => {
return request(app.getHttpServer())
.get(`/v2/bookings?afterStart=${createdRecurringBooking[0].start}`)
.get(`/v2/bookings?beforeEnd=${createdRecurringBooking[0].end}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(200)
.then(async (response) => {
const responseBody: GetBookingsOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
const data: (
| BookingOutput_2024_08_13
| RecurringBookingOutput_2024_08_13
| GetSeatedBookingOutput_2024_08_13
)[] = responseBody.data;
expect(data.length).toEqual(3);
});
});
it("should should get bookings after specified update time", async () => {
return request(app.getHttpServer())
.get(`/v2/bookings?afterUpdatedAt=${createdRecurringBooking[1].updatedAt}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(200)
.then(async (response) => {
const responseBody: GetBookingsOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
const data: (
| BookingOutput_2024_08_13
| RecurringBookingOutput_2024_08_13
| GetSeatedBookingOutput_2024_08_13
)[] = responseBody.data;
expect(data.length).toEqual(2);
});
});
it("should should get bookings before specified update time", async () => {
return request(app.getHttpServer())
.get(`/v2/bookings?beforeUpdatedAt=${createdRecurringBooking[0].updatedAt}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(200)
.then(async (response) => {
const responseBody: GetBookingsOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
const data: (
| BookingOutput_2024_08_13
| RecurringBookingOutput_2024_08_13
| GetSeatedBookingOutput_2024_08_13
)[] = responseBody.data;
expect(data.length).toEqual(3);
});
});
it("should should get bookings in update range", async () => {
return request(app.getHttpServer())
.get(
`/v2/bookings?afterUpdatedAt=${createdRecurringBooking[0].updatedAt}&beforeUpdatedAt=${createdRecurringBooking[2].updatedAt}`
)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(200)
.then(async (response) => {
@@ -1004,6 +1091,46 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(data[1].start).toEqual(createdBooking.start);
});
});
it("should should sort bookings by updated in descending order", async () => {
return request(app.getHttpServer())
.get(`/v2/bookings?eventTypeId=${eventTypeId}&sortUpdatedAt=desc`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(200)
.then(async (response) => {
const responseBody: GetBookingsOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
const data: (
| BookingOutput_2024_08_13
| RecurringBookingOutput_2024_08_13
| GetSeatedBookingOutput_2024_08_13
)[] = responseBody.data;
expect(data.length).toEqual(2);
expect(data[0].updatedAt).toEqual(createdBooking.updatedAt);
expect(data[1].updatedAt).toEqual(bookingInThePast.updatedAt?.toISOString());
});
});
it("should should sort bookings by updated in ascending order", async () => {
return request(app.getHttpServer())
.get(`/v2/bookings?eventTypeId=${eventTypeId}&sortUpdatedAt=asc`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(200)
.then(async (response) => {
const responseBody: GetBookingsOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
const data: (
| BookingOutput_2024_08_13
| RecurringBookingOutput_2024_08_13
| GetSeatedBookingOutput_2024_08_13
)[] = responseBody.data;
expect(data.length).toEqual(2);
expect(data[0].updatedAt).toEqual(bookingInThePast.updatedAt?.toISOString());
expect(data[1].updatedAt).toEqual(createdBooking.updatedAt);
});
});
});
describe("reschedule bookings", () => {
@@ -5,7 +5,7 @@ import {
} from "@/ee/bookings/2024-08-13/services/output.service";
import { EventTypesRepository_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.repository";
import { hashAPIKey, isApiKey, stripApiKey } from "@/lib/api-key";
import { ApiKeyRepository } from "@/modules/api-key/api-key-repository";
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
import { BookingSeatRepository } from "@/modules/booking-seat/booking-seat.repository";
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.service";
@@ -74,7 +74,7 @@ export class InputBookingsService_2024_08_13 {
private readonly eventTypesRepository: EventTypesRepository_2024_06_14,
private readonly bookingsRepository: BookingsRepository_2024_08_13,
private readonly config: ConfigService,
private readonly apiKeyRepository: ApiKeyRepository,
private readonly apiKeyRepository: ApiKeysRepository,
private readonly bookingSeatRepository: BookingSeatRepository
) {}
@@ -463,11 +463,18 @@ export class InputBookingsService_2024_08_13 {
teamIds: queryParams.teamsIds || (queryParams.teamId ? [queryParams.teamId] : undefined),
eventTypeIds:
queryParams.eventTypeIds || (queryParams.eventTypeId ? [queryParams.eventTypeId] : undefined),
afterUpdatedDate: queryParams.afterUpdatedAt,
beforeUpdatedDate: queryParams.beforeUpdatedAt,
};
}
transformGetBookingsSort(queryParams: GetBookingsInput_2024_08_13) {
if (!queryParams.sortStart && !queryParams.sortEnd && !queryParams.sortCreated) {
if (
!queryParams.sortStart &&
!queryParams.sortEnd &&
!queryParams.sortCreated &&
!queryParams.sortUpdatedAt
) {
return undefined;
}
@@ -475,6 +482,7 @@ export class InputBookingsService_2024_08_13 {
sortStart: queryParams.sortStart,
sortEnd: queryParams.sortEnd,
sortCreated: queryParams.sortCreated,
sortUpdated: queryParams.sortUpdatedAt,
};
}
@@ -132,6 +132,8 @@ export class OutputBookingsService_2024_08_13 {
meetingUrl: location,
absentHost: !!databaseBooking.noShowHost,
createdAt: databaseBooking.createdAt,
updatedAt: databaseBooking.updatedAt,
rating: databaseBooking.rating,
};
const bookingTransformed = plainToClass(BookingOutput_2024_08_13, booking, { strategy: "excludeAll" });
@@ -225,6 +227,8 @@ export class OutputBookingsService_2024_08_13 {
absentHost: !!databaseBooking.noShowHost,
bookingFieldsResponses: databaseBooking.responses,
createdAt: databaseBooking.createdAt,
updatedAt: databaseBooking.updatedAt,
rating: databaseBooking.rating,
};
const bookingTransformed = plainToClass(RecurringBookingOutput_2024_08_13, booking, {
@@ -271,6 +275,8 @@ export class OutputBookingsService_2024_08_13 {
meetingUrl: location,
absentHost: !!databaseBooking.noShowHost,
createdAt: databaseBooking.createdAt,
updatedAt: databaseBooking.updatedAt,
rating: databaseBooking.rating,
};
const parsed = plainToClass(GetSeatedBookingOutput_2024_08_13, booking, { strategy: "excludeAll" });
@@ -280,7 +286,8 @@ export class OutputBookingsService_2024_08_13 {
const { responses } = safeParse(
seatedBookingDataSchema,
attendee.bookingSeat?.data,
defaultSeatedBookingData
defaultSeatedBookingData,
false
);
const attendeeData = {
@@ -297,7 +304,8 @@ export class OutputBookingsService_2024_08_13 {
attendeeParsed.metadata = safeParse(
seatedBookingMetadataSchema,
attendee.bookingSeat?.metadata,
defaultSeatedBookingMetadata
defaultSeatedBookingMetadata,
false
);
// note(Lauris): as of now email is not returned for privacy
delete attendeeParsed.bookingFieldsResponses.email;
@@ -376,6 +384,8 @@ export class OutputBookingsService_2024_08_13 {
recurringBookingUid: databaseBooking.recurringEventId,
absentHost: !!databaseBooking.noShowHost,
createdAt: databaseBooking.createdAt,
updatedAt: databaseBooking.updatedAt,
rating: databaseBooking.rating,
};
const parsed = plainToClass(GetRecurringSeatedBookingOutput_2024_08_13, booking, {
@@ -387,7 +397,8 @@ export class OutputBookingsService_2024_08_13 {
const { responses } = safeParse(
seatedBookingDataSchema,
attendee.bookingSeat?.data,
defaultSeatedBookingData
defaultSeatedBookingData,
false
);
const attendeeData = {
@@ -404,7 +415,8 @@ export class OutputBookingsService_2024_08_13 {
attendeeParsed.metadata = safeParse(
seatedBookingMetadataSchema,
attendee.bookingSeat?.metadata,
defaultSeatedBookingMetadata
defaultSeatedBookingMetadata,
false
);
// note(Lauris): as of now email is not returned for privacy
delete attendeeParsed.bookingFieldsResponses.email;
@@ -34,7 +34,7 @@ import {
Post,
Body,
} from "@nestjs/common";
import { ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { ApiOperation, ApiParam, ApiTags as DocsTags } from "@nestjs/swagger";
import { User } from "@prisma/client";
import { plainToClass } from "class-transformer";
import { Request } from "express";
@@ -123,10 +123,15 @@ export class CalendarsController {
};
}
@ApiParam({
enum: [OFFICE_365_CALENDAR, GOOGLE_CALENDAR],
type: String,
name: "calendar",
})
@UseGuards(ApiAuthGuard)
@Get("/:calendar/connect")
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: "Get connect URL" })
@ApiOperation({ summary: "Get oAuth connect URL" })
async redirect(
@Req() req: Request,
@Headers("Authorization") authorization: string,
@@ -146,10 +151,15 @@ export class CalendarsController {
}
}
@ApiParam({
enum: [OFFICE_365_CALENDAR, GOOGLE_CALENDAR],
type: String,
name: "calendar",
})
@Get("/:calendar/save")
@HttpCode(HttpStatus.OK)
@Redirect(undefined, 301)
@ApiOperation({ summary: "Save a calendar" })
@ApiOperation({ summary: "Save an oAuth calendar credentials" })
async save(
@Query("state") state: string,
@Query("code") code: string,
@@ -177,6 +187,11 @@ export class CalendarsController {
}
}
@ApiParam({
enum: [APPLE_CALENDAR],
type: String,
name: "calendar",
})
@UseGuards(ApiAuthGuard)
@Post("/:calendar/credentials")
@ApiOperation({ summary: "Sync credentials" })
@@ -198,6 +213,11 @@ export class CalendarsController {
}
}
@ApiParam({
enum: [APPLE_CALENDAR, GOOGLE_CALENDAR, OFFICE_365_CALENDAR],
type: String,
name: "calendar",
})
@Get("/:calendar/check")
@HttpCode(HttpStatus.OK)
@UseGuards(ApiAuthGuard, PermissionsGuard)
@@ -219,6 +239,11 @@ export class CalendarsController {
}
}
@ApiParam({
enum: [APPLE_CALENDAR, GOOGLE_CALENDAR, OFFICE_365_CALENDAR],
type: String,
name: "calendar",
})
@UseGuards(ApiAuthGuard)
@Post("/:calendar/disconnect")
@HttpCode(HttpStatus.OK)
@@ -377,6 +377,15 @@ describe("Event types Endpoints", () => {
disableOnPrefill: true,
hidden: false,
},
{
type: "url",
label: "Video Url",
slug: "video-url",
required: true,
placeholder: "add video url",
disableOnPrefill: true,
hidden: false,
},
],
scheduleId: firstSchedule.id,
bookingLimitsCount: {
@@ -478,6 +487,16 @@ describe("Event types Endpoints", () => {
hidden: false,
isDefault: false,
},
{
type: "url",
label: "Video Url",
slug: "video-url",
required: true,
placeholder: "add video url",
disableOnPrefill: true,
hidden: false,
isDefault: false,
},
{ ...defaultResponseBookingFieldTitle },
{ ...defaultResponseBookingFieldNotes },
{ ...defaultResponseBookingFieldGuests },
@@ -7,11 +7,7 @@ import { InputEventTransformed_2024_06_14 } from "@calcom/platform-types";
@Injectable()
export class EventTypesRepository_2024_06_14 {
constructor(
private readonly dbRead: PrismaReadService,
private readonly dbWrite: PrismaWriteService,
private usersService: UsersService
) {}
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
async createUserEventType(
userId: number,
@@ -47,6 +43,13 @@ export class EventTypesRepository_2024_06_14 {
});
}
async getEventTypeWithHosts(eventTypeId: number) {
return this.dbRead.prisma.eventType.findUnique({
where: { id: eventTypeId },
include: { hosts: true },
});
}
async getUserEventType(userId: number, eventTypeId: number) {
return this.dbRead.prisma.eventType.findFirst({
where: {
@@ -1,6 +1,6 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsEnum, IsString, ValidateNested } from "class-validator";
import { IsEnum, IsString, ValidateNested, IsOptional } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
@@ -10,8 +10,9 @@ class Data {
callId!: string;
@IsString()
@IsOptional()
@ApiProperty()
agentId!: string;
agentId?: string;
}
export class CreatePhoneCallOutput {
+3 -2
View File
@@ -26,7 +26,8 @@ import {
Headers,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { ApiExcludeController } from "@nestjs/swagger";
import { ApiOperation } from "@nestjs/swagger";
import { Request } from "express";
import { APPS_READ, GOOGLE_CALENDAR_TYPE, SUCCESS_STATUS } from "@calcom/platform-constants";
@@ -41,7 +42,7 @@ const CALENDAR_SCOPES = [
path: "/v2/gcal",
version: API_VERSIONS_VALUES,
})
@DocsTags("Platform / Google Calendar")
@ApiExcludeController(true)
export class GcalController {
private readonly logger = new Logger("Platform Gcal Provider");
@@ -8,7 +8,8 @@ import { MeModule } from "@/ee/me/me.module";
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 { SlotsModule_2024_04_15 } from "@/modules/slots/slots-2024-04-15/slots.module";
import { SlotsModule_2024_09_04 } from "@/modules/slots/slots-2024-09-04/slots.module";
import { TeamsEventTypesModule } from "@/modules/teams/event-types/teams-event-types.module";
import { TeamsMembershipsModule } from "@/modules/teams/memberships/teams-memberships.module";
import { TeamsModule } from "@/modules/teams/teams/teams.module";
@@ -29,7 +30,8 @@ import { Module } from "@nestjs/common";
BookingsModule_2024_04_15,
BookingsModule_2024_08_13,
TeamsMembershipsModule,
SlotsModule,
SlotsModule_2024_04_15,
SlotsModule_2024_09_04,
TeamsModule,
],
})
+3
View File
@@ -6,6 +6,7 @@ import {
VERSION_2024_06_11,
VERSION_2024_06_14,
VERSION_2024_08_13,
VERSION_2024_09_04,
} from "@calcom/platform-constants";
export const API_VERSIONS_VALUES: VersionValue = API_VERSIONS as unknown as VersionValue;
@@ -13,8 +14,10 @@ export const VERSION_2024_06_14_VALUE: VersionValue = VERSION_2024_06_14 as unkn
export const VERSION_2024_06_11_VALUE: VersionValue = VERSION_2024_06_11 as unknown as VersionValue;
export const VERSION_2024_04_15_VALUE: VersionValue = VERSION_2024_04_15 as unknown as VersionValue;
export const VERSION_2024_08_13_VALUE: VersionValue = VERSION_2024_08_13 as unknown as VersionValue;
export const VERSION_2024_09_04_VALUE: VersionValue = VERSION_2024_09_04 as unknown as VersionValue;
export { VERSION_2024_04_15 };
export { VERSION_2024_06_11 };
export { VERSION_2024_06_14 };
export { VERSION_2024_08_13 };
export { VERSION_2024_09_04 };
+10 -8
View File
@@ -3,20 +3,22 @@ import { ZodSchema } from "zod";
const logger = new Logger("safeParse");
export function safeParse<T>(schema: ZodSchema<T>, value: unknown, defaultValue: T): T {
export function safeParse<T>(schema: ZodSchema<T>, value: unknown, defaultValue: T, logError = true): T {
const result = schema.safeParse(value);
if (result.success) {
return result.data;
} else {
const errorStack = new Error().stack;
logger.error(
`Zod parsing failed.\n` +
`1. Schema: ${schema.description || "UnnamedSchema"}\n` +
`2. Input: ${JSON.stringify(value, null, 2)}\n` +
`3. Zod Error: ${result.error}\n` +
`4. Call Stack: ${errorStack}`
);
if (logError) {
logger.error(
`Zod parsing failed.\n` +
`1. Schema: ${schema.description || "UnnamedSchema"}\n` +
`2. Input: ${JSON.stringify(value, null, 2)}\n` +
`3. Zod Error: ${result.error}\n` +
`4. Call Stack: ${errorStack}`
);
}
return defaultValue;
}
@@ -1,10 +0,0 @@
import { ApiKeyRepository } from "@/modules/api-key/api-key-repository";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule],
providers: [ApiKeyRepository],
exports: [ApiKeyRepository],
})
export class ApiKeyModule {}
@@ -3,7 +3,7 @@ import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
@Injectable()
export class ApiKeyRepository {
export class ApiKeysRepository {
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
async getApiKeyFromHash(hashedKey: string) {
@@ -13,4 +13,20 @@ export class ApiKeyRepository {
},
});
}
async getTeamApiKeys(teamId: number) {
return this.dbRead.prisma.apiKey.findMany({
where: {
teamId,
},
});
}
async deleteById(id: string) {
return this.dbWrite.prisma.apiKey.delete({
where: {
id,
},
});
}
}
@@ -0,0 +1,13 @@
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
import { ApiKeysController } from "@/modules/api-keys/controllers/api-keys.controller";
import { ApiKeysService } from "@/modules/api-keys/services/api-keys.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule],
providers: [ApiKeysRepository, ApiKeysService],
controllers: [ApiKeysController],
exports: [ApiKeysRepository, ApiKeysService],
})
export class ApiKeysModule {}
@@ -0,0 +1,48 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { RefreshApiKeyInput } from "@/modules/api-keys/inputs/refresh-api-key.input";
import { RefreshApiKeyOutput } from "@/modules/api-keys/outputs/refresh-api-key.output";
import { ApiKeysService } from "@/modules/api-keys/services/api-keys.service";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { ApiAuthGuardRequest } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { Body, Controller, HttpCode, HttpStatus, Post, Req, UseGuards } from "@nestjs/common";
import { ApiTags, ApiHeader, ApiOperation } from "@nestjs/swagger";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
@Controller({
path: "/v2/api-keys",
version: API_VERSIONS_VALUES,
})
@UseGuards(ApiAuthGuard)
@ApiTags("Api Keys")
export class ApiKeysController {
constructor(private readonly apiKeysService: ApiKeysService) {}
@ApiOperation({
summary: "Refresh API Key",
description: `Generate a new API key and delete the current one. Provide API key to refresh as a Bearer token in the Authorization header (e.g. "Authorization: Bearer <apiKey>").`,
})
@ApiHeader({
name: "Authorization",
description: "Bearer <apiKey>",
required: true,
schema: { type: "string" },
})
@Post("/refresh")
@HttpCode(HttpStatus.OK)
async refresh(
@Body() body: RefreshApiKeyInput,
@GetUser("id") userId: number,
@Req() request: ApiAuthGuardRequest
): Promise<RefreshApiKeyOutput> {
const currentApiKey = await this.apiKeysService.getRequestApiKey(request);
const newApiKey = await this.apiKeysService.refreshApiKey(userId, currentApiKey, body);
return {
status: SUCCESS_STATUS,
data: {
apiKey: newApiKey,
},
};
}
}
@@ -0,0 +1,20 @@
import { RefreshApiKeyInput } from "@/modules/api-keys/inputs/refresh-api-key.input";
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsInt, IsOptional, IsString } from "class-validator";
export class CreateApiKeyInput extends RefreshApiKeyInput {
@IsOptional()
@IsInt()
@ApiPropertyOptional({
description: "For which team or organization is the api key.",
})
readonly teamId?: number;
@IsOptional()
@IsString()
@ApiPropertyOptional({
description: "Store additional note about this api key.",
example: "This is an api key for development purposes.",
})
readonly note?: string;
}
@@ -0,0 +1,20 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsBoolean, IsInt, IsOptional, Min } from "class-validator";
export class RefreshApiKeyInput {
@IsOptional()
@IsInt()
@Min(1)
@ApiPropertyOptional({
description: "For how many days is managed organization api key valid. Defaults to 30 days.",
example: 60,
default: 30,
minimum: 1,
})
readonly apiKeyDaysValid?: number;
@IsOptional()
@IsBoolean()
@ApiPropertyOptional({ description: "If true, organization api key never expires.", example: true })
readonly apiKeyNeverExpires?: boolean;
}
@@ -0,0 +1,10 @@
import { ApiProperty as DocsProperty } from "@nestjs/swagger";
import { Expose } from "class-transformer";
import { IsString } from "class-validator";
export class ApiKeyOutput {
@IsString()
@Expose()
@DocsProperty()
readonly apiKey!: string;
}
@@ -0,0 +1,18 @@
import { ApiKeyOutput } from "@/modules/api-keys/outputs/api-key.output";
import { ApiProperty } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import { IsEnum, ValidateNested } from "class-validator";
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
export class RefreshApiKeyOutput {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({ type: ApiKeyOutput })
@Expose()
@ValidateNested()
@Type(() => ApiKeyOutput)
data!: ApiKeyOutput;
}
@@ -0,0 +1,80 @@
import { hashAPIKey, stripApiKey } from "@/lib/api-key";
import { AuthMethods } from "@/lib/enums/auth-methods";
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
import { CreateApiKeyInput } from "@/modules/api-keys/inputs/create-api-key.input";
import { RefreshApiKeyInput } from "@/modules/api-keys/inputs/refresh-api-key.input";
import { ApiAuthGuardRequest } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { BadRequestException, Injectable, UnauthorizedException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { DateTime } from "luxon";
import { createApiKeyHandler } from "@calcom/platform-libraries";
@Injectable()
export class ApiKeysService {
constructor(
private readonly apiKeysRepository: ApiKeysRepository,
private readonly config: ConfigService
) {}
async getRequestApiKey(request: ApiAuthGuardRequest) {
if (request.authMethod !== AuthMethods.API_KEY) {
throw new UnauthorizedException(
"ApiKeysService - This endpoint can only be accessed using an API key by providing 'Authorization: Bearer <apiKey>' header"
);
}
const apiKey = request.get("Authorization")?.replace("Bearer ", "");
if (!apiKey) {
throw new UnauthorizedException("ApiKeysService - No API key provided");
}
return apiKey;
}
async createApiKey(authUserId: number, createApiKeyInput: CreateApiKeyInput) {
if (createApiKeyInput.apiKeyDaysValid && createApiKeyInput.apiKeyNeverExpires) {
throw new BadRequestException(
"ApiKeysService -Cannot set both apiKeyDaysValid and apiKeyNeverExpires. It has to be either or none of them."
);
}
const defaultApiKeyDaysValid = 30;
const apiKeyExpiresAfterDays = createApiKeyInput.apiKeyDaysValid
? createApiKeyInput.apiKeyDaysValid
: defaultApiKeyDaysValid;
const apiKeyExpiresAt = DateTime.utc().plus({ days: apiKeyExpiresAfterDays }).toJSDate();
const apiKey = await createApiKeyHandler({
ctx: {
user: {
id: authUserId,
},
},
input: {
note: createApiKeyInput.note,
neverExpires: !!createApiKeyInput.apiKeyNeverExpires,
expiresAt: apiKeyExpiresAt,
teamId: createApiKeyInput.teamId,
},
});
return apiKey;
}
async refreshApiKey(authUserId: number, apiKey: string, refreshApiKeyInput: RefreshApiKeyInput) {
const strippedApiKey = stripApiKey(apiKey, this.config.get<string>("api.keyPrefix"));
const apiKeyHash = hashAPIKey(strippedApiKey);
const apiKeyInDb = await this.apiKeysRepository.getApiKeyFromHash(apiKeyHash);
if (!apiKeyInDb) {
throw new UnauthorizedException("ApiKeysService - provided api key is not valid.");
}
const newApiKey = await this.createApiKey(authUserId, {
...refreshApiKeyInput,
note: apiKeyInDb.note || undefined,
teamId: apiKeyInDb.teamId || undefined,
});
await this.apiKeysRepository.deleteById(apiKeyInDb.id);
return newApiKey;
}
}
@@ -2,9 +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 { 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 { 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, ForbiddenException } from "@nestjs/common";
@@ -122,9 +122,10 @@ export class EventTypesAtomService {
async updateEventType(eventTypeId: number, body: TUpdateEventTypeInputSchema, user: UserWithProfile) {
await this.eventTypeService.checkCanUpdateEventType(user.id, eventTypeId, body.scheduleId);
const eventTypeUser = await this.eventTypeService.getUserToUpdateEvent(user);
const bookingFields = [...(body.bookingFields || [])];
const bookingFields = body.bookingFields ? [...body.bookingFields] : undefined;
if (
bookingFields?.length &&
!bookingFields.find((field) => field.type === "email") &&
!bookingFields.find((field) => field.type === "phone")
) {
+2 -2
View File
@@ -1,4 +1,4 @@
import { ApiKeyModule } from "@/modules/api-key/api-key.module";
import { ApiKeysModule } from "@/modules/api-keys/api-keys.module";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { NextAuthGuard } from "@/modules/auth/guards/next-auth/next-auth.guard";
import { ApiAuthStrategy } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
@@ -17,7 +17,7 @@ import { PassportModule } from "@nestjs/passport";
imports: [
PassportModule,
RedisModule,
ApiKeyModule,
ApiKeysModule,
UsersModule,
MembershipsModule,
TokensModule,
@@ -0,0 +1,30 @@
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { ExecutionContext } from "@nestjs/common";
import { createParamDecorator } from "@nestjs/common";
export const GetOptionalUser = createParamDecorator<
keyof ApiAuthGuardUser | (keyof ApiAuthGuardUser)[],
ExecutionContext
>((data, ctx) => {
const request = ctx.switchToHttp().getRequest();
const user = request.user as ApiAuthGuardUser;
if (!user) {
return null;
}
if (Array.isArray(data)) {
return data.reduce((prev, curr) => {
return {
...prev,
[curr]: user[curr],
};
}, {});
}
if (data) {
return user[data];
}
return user;
});
@@ -0,0 +1,12 @@
import { createParamDecorator, ExecutionContext, UnauthorizedException } from "@nestjs/common";
export const GetOrgId = createParamDecorator((_: unknown, ctx: ExecutionContext): number => {
const request = ctx.switchToHttp().getRequest();
const organizationId = request.organizationId;
if (!organizationId) {
throw new UnauthorizedException("GetOrgId decorator: Organization ID not found");
}
return organizationId;
});
@@ -1,5 +1,5 @@
import { PlatformPlanGuard } from "@/modules/auth/guards/billing/platform-plan.guard";
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { RedisService } from "@/modules/redis/redis.service";
import { createMock } from "@golevelup/ts-jest";
import { ExecutionContext } from "@nestjs/common";
@@ -1,7 +1,7 @@
import { PlatformPlan } from "@/modules/auth/decorators/billing/platform-plan.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 { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { RedisService } from "@/modules/redis/redis.service";
import { Injectable, CanActivate, ExecutionContext } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
@@ -1,4 +1,4 @@
import { OrganizationsMembershipRepository } from "@/modules/organizations/repositories/organizations-membership.repository";
import { OrganizationsMembershipRepository } from "@/modules/organizations/memberships/organizations-membership.repository";
import {
Injectable,
CanActivate,
@@ -0,0 +1,14 @@
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { NO_AUTH_PROVIDED_MESSAGE } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
export class OptionalApiAuthGuard extends ApiAuthGuard {
handleRequest(error: Error, user: any) {
// note(Lauris): optional means that auth is not required but if it is invalid then still throw error.
const noAuthProvided = error && error.message === NO_AUTH_PROVIDED_MESSAGE;
if (user || noAuthProvided || !error) {
return user || null;
} else {
throw error;
}
}
}
@@ -1,6 +1,6 @@
import { MembershipRoles } from "@/modules/auth/decorators/roles/membership-roles.decorator";
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
import { OrganizationsService } from "@/modules/organizations/services/organizations.service";
import { OrganizationsService } from "@/modules/organizations/index/organizations.service";
import { UsersService } from "@/modules/users/services/users.service";
import { UserWithProfile } from "@/modules/users/users.repository";
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
@@ -20,10 +20,10 @@ export class OrganizationRolesGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const user: UserWithProfile = request.user;
const organizationId = user ? this.usersService.getUserMainOrgId(user) : null;
const organizationId = this.getOrganizationId(context);
if (!user || !organizationId) {
throw new ForbiddenException("No organization associated with the user.");
throw new ForbiddenException("OrganizationRolesGuard - No organization associated with the user.");
}
await this.isPlatform(organizationId);
@@ -40,13 +40,25 @@ export class OrganizationRolesGuard implements CanActivate {
async isPlatform(organizationId: number) {
const isPlatform = await this.organizationsService.isPlatform(organizationId);
if (!isPlatform) {
throw new ForbiddenException("Organization is not a platform (SHP).");
throw new ForbiddenException("OrganizationRolesGuard - Organization is not a platform (SHP).");
}
}
getOrganizationId(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const user: UserWithProfile = request.user;
const authMethodOrganizationId = request.organizationId;
if (authMethodOrganizationId) return authMethodOrganizationId;
const userOrganizationId = user ? this.usersService.getUserMainOrgId(user) : null;
return userOrganizationId;
}
isMembershipAccepted(accepted: boolean) {
if (!accepted) {
throw new ForbiddenException(`User has not accepted membership in the organization.`);
throw new ForbiddenException(
`OrganizationRolesGuard - User has not accepted membership in the organization.`
);
}
}
@@ -57,7 +69,9 @@ export class OrganizationRolesGuard implements CanActivate {
const hasRequiredRole = allowedRoles.includes(membershipRole);
if (!hasRequiredRole) {
throw new ForbiddenException(`User must have one of the roles: ${allowedRoles.join(", ")}.`);
throw new ForbiddenException(
`OrganizationRolesGuard - User must have one of the roles: ${allowedRoles.join(", ")}.`
);
}
}
}
@@ -1,4 +1,4 @@
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { RedisService } from "@/modules/redis/redis.service";
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
import { Request } from "express";
@@ -0,0 +1,43 @@
import { ManagedOrganizationsRepository } from "@/modules/organizations/organizations/managed-organizations.repository";
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
NotFoundException,
} from "@nestjs/common";
import { Request } from "express";
import { Team } from "@calcom/prisma/client";
@Injectable()
export class IsManagedOrgInManagerOrg implements CanActivate {
constructor(private managedOrganizationsRepository: ManagedOrganizationsRepository) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request & { managedOrganization: Team }>();
const managedOrgId: string = request.params.managedOrganizationId;
const managerOrgId: string = request.params.orgId;
if (!managerOrgId) {
throw new ForbiddenException("No manager org id found in request params.");
}
if (!managedOrgId) {
throw new ForbiddenException("No managed org id found in request params.");
}
const managedOrganization = await this.managedOrganizationsRepository.getByManagerManagedIds(
Number(managerOrgId),
Number(managedOrgId)
);
if (!managedOrganization) {
throw new NotFoundException(
`Managed organization with id=${managedOrgId} within manager organization with id=${managerOrgId} not found.`
);
}
return true;
}
}
@@ -1,4 +1,4 @@
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { RedisService } from "@/modules/redis/redis.service";
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
import { Request } from "express";
@@ -1,5 +1,5 @@
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { OrganizationsWebhooksRepository } from "@/modules/organizations/repositories/organizations-webhooks.repository";
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { OrganizationsWebhooksRepository } from "@/modules/organizations/webhooks/organizations-webhooks.repository";
import { RedisService } from "@/modules/redis/redis.service";
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
import { Request } from "express";
@@ -0,0 +1,40 @@
import { RoutingFormsRepository } from "@/modules/routing-forms/routing-forms.repository";
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
NotFoundException,
} from "@nestjs/common";
import { Request } from "express";
import { Team } from "@calcom/prisma/client";
@Injectable()
export class IsRoutingFormInTeam implements CanActivate {
constructor(private routingFormsRepository: RoutingFormsRepository) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request & { team: Team }>();
const teamId: string = request.params.teamId;
const routingFormId: string = request.params.routingFormId;
if (!routingFormId) {
throw new ForbiddenException("No routing form id found in request params.");
}
if (!teamId) {
throw new ForbiddenException("No team id found in request params.");
}
const routingForm = await this.routingFormsRepository.getTeamRoutingForm(Number(teamId), routingFormId);
if (!routingForm) {
throw new NotFoundException(
`Team with id=(${teamId}) routing form with id=(${routingFormId}) not found.`
);
}
return true;
}
}
@@ -1,4 +1,4 @@
import { OrganizationsTeamsRepository } from "@/modules/organizations/repositories/organizations-teams.repository";
import { OrganizationsTeamsRepository } from "@/modules/organizations/teams/index/organizations-teams.repository";
import {
Injectable,
CanActivate,
@@ -1,4 +1,4 @@
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
import { Request } from "express";
@@ -1,4 +1,4 @@
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
import { Request } from "express";
@@ -1,5 +1,6 @@
import appConfig from "@/config/app";
import { ApiKeyRepository } from "@/modules/api-key/api-key-repository";
import { AuthMethods } from "@/lib/enums/auth-methods";
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
import { DeploymentsRepository } from "@/modules/deployments/deployments.repository";
import { DeploymentsService } from "@/modules/deployments/deployments.service";
import { JwtService } from "@/modules/jwt/jwt.service";
@@ -9,6 +10,7 @@ import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { ProfilesModule } from "@/modules/profiles/profiles.module";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { UsersService } from "@/modules/users/services/users.service";
import { UsersRepository } from "@/modules/users/users.repository";
import { ExecutionContext, HttpException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
@@ -16,6 +18,7 @@ import { ConfigModule } from "@nestjs/config";
import { JwtService as NestJwtService } from "@nestjs/jwt";
import { Test, TestingModule } from "@nestjs/testing";
import { PlatformOAuthClient, Team, User } from "@prisma/client";
import { createRequest } from "node-mocks-http";
import { ApiKeysRepositoryFixture } from "test/fixtures/repository/api-keys.repository.fixture";
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
@@ -27,6 +30,7 @@ import { randomString } from "test/utils/randomString";
import { X_CAL_CLIENT_ID, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
import { ApiAuthGuardRequest } from "./api-auth.strategy";
import { ApiAuthStrategy } from "./api-auth.strategy";
describe("ApiAuthStrategy", () => {
@@ -35,7 +39,9 @@ describe("ApiAuthStrategy", () => {
let tokensRepositoryFixture: TokensRepositoryFixture;
let teamRepositoryFixture: TeamRepositoryFixture;
let organization: Team;
let organizationTwo: Team;
let oAuthClient: PlatformOAuthClient;
let oAuthClientTwo: PlatformOAuthClient;
let apiKeysRepositoryFixture: ApiKeysRepositoryFixture;
let oAuthClientRepositoryFixture: OAuthClientRepositoryFixture;
let profilesRepositoryFixture: ProfileRepositoryFixture;
@@ -65,7 +71,8 @@ describe("ApiAuthStrategy", () => {
ConfigService,
OAuthFlowService,
UsersRepository,
ApiKeyRepository,
UsersService,
ApiKeysRepository,
DeploymentsService,
OAuthClientRepository,
PrismaReadService,
@@ -84,7 +91,11 @@ describe("ApiAuthStrategy", () => {
teamRepositoryFixture = new TeamRepositoryFixture(module);
oAuthClientRepositoryFixture = new OAuthClientRepositoryFixture(module);
profilesRepositoryFixture = new ProfileRepositoryFixture(module);
organization = await teamRepositoryFixture.create({ name: `api-auth-organization-${randomString()}` });
organization = await teamRepositoryFixture.create({ name: `api-auth-organization-1-${randomString()}` });
organizationTwo = await teamRepositoryFixture.create({
name: `api-auth-organization-2-${randomString()}`,
});
validApiKeyUser = await userRepositoryFixture.create({
email: validApiKeyEmail,
});
@@ -103,6 +114,13 @@ describe("ApiAuthStrategy", () => {
organization: { connect: { id: organization.id } },
});
await profilesRepositoryFixture.create({
uid: "asd-asd",
username: validOAuthEmail,
user: { connect: { id: validOAuthUser.id } },
organization: { connect: { id: organizationTwo.id } },
});
const data = {
logo: "logo-url",
name: "name",
@@ -110,6 +128,7 @@ describe("ApiAuthStrategy", () => {
permissions: 32,
};
oAuthClient = await oAuthClientRepositoryFixture.create(organization.id, data, "secret");
oAuthClientTwo = await oAuthClientRepositoryFixture.create(organizationTwo.id, data, "secret");
});
describe("authenticate with strategy", () => {
@@ -119,25 +138,68 @@ describe("ApiAuthStrategy", () => {
oAuthClient.id
);
const user = await strategy.accessTokenStrategy(accessToken);
const mockRequest = createRequest() as ApiAuthGuardRequest;
mockRequest.authMethod = AuthMethods.ACCESS_TOKEN;
mockRequest.organizationId = null;
const user = await strategy.accessTokenStrategy(accessToken, mockRequest);
expect(user).toBeDefined();
expect(user?.id).toEqual(validAccessTokenUser.id);
});
it("should return user associated with valid api key", async () => {
it("should return user associated with valid api key and correctly set organizationId for org1", async () => {
const now = new Date();
now.setDate(now.getDate() + 1);
const { keyString } = await apiKeysRepositoryFixture.createApiKey(validApiKeyUser.id, now);
const { keyString } = await apiKeysRepositoryFixture.createApiKey(
validApiKeyUser.id,
now,
organization.id
);
const user = await strategy.apiKeyStrategy(keyString);
const mockRequest = createRequest() as ApiAuthGuardRequest;
mockRequest.authMethod = AuthMethods.API_KEY;
mockRequest.organizationId = null;
const user = await strategy.apiKeyStrategy(keyString, mockRequest);
expect(user).toBeDefined();
expect(user?.id).toEqual(validApiKeyUser.id);
expect(mockRequest.organizationId).toEqual(organization.id);
});
it("should return user associated with valid api key and correctly set organizationId for org2", async () => {
const now = new Date();
now.setDate(now.getDate() + 1);
const { keyString } = await apiKeysRepositoryFixture.createApiKey(
validApiKeyUser.id,
now,
organizationTwo.id
);
const mockRequest = createRequest() as ApiAuthGuardRequest;
mockRequest.authMethod = AuthMethods.API_KEY;
mockRequest.organizationId = null;
const user = await strategy.apiKeyStrategy(keyString, mockRequest);
expect(user).toBeDefined();
expect(user?.id).toEqual(validApiKeyUser.id);
expect(mockRequest.organizationId).toEqual(organizationTwo.id);
});
it("should return user associated with valid OAuth client", async () => {
const user = await strategy.oAuthClientStrategy(oAuthClient.id, oAuthClient.secret);
const mockRequest = createRequest() as ApiAuthGuardRequest;
mockRequest.authMethod = AuthMethods.OAUTH_CLIENT;
mockRequest.organizationId = null;
const user = await strategy.oAuthClientStrategy(oAuthClient.id, oAuthClient.secret, mockRequest);
expect(user).toBeDefined();
expect(user.id).toEqual(validOAuthUser.id);
expect(mockRequest.organizationId).toEqual(organization.id);
});
it("should return user associated with valid OAuth client for org2", async () => {
const mockRequest = createRequest() as ApiAuthGuardRequest;
mockRequest.authMethod = AuthMethods.OAUTH_CLIENT;
mockRequest.organizationId = null;
const user = await strategy.oAuthClientStrategy(oAuthClientTwo.id, oAuthClientTwo.secret, mockRequest);
expect(user).toBeDefined();
expect(user.id).toEqual(validOAuthUser.id);
expect(mockRequest.organizationId).toEqual(organizationTwo.id);
});
it("should throw 401 if api key is invalid", async () => {
@@ -2,12 +2,13 @@ import { hashAPIKey, isApiKey, stripApiKey } from "@/lib/api-key";
import { AuthMethods } from "@/lib/enums/auth-methods";
import { isOriginAllowed } from "@/lib/is-origin-allowed/is-origin-allowed";
import { BaseStrategy } from "@/lib/passport/strategies/types";
import { ApiKeyRepository } from "@/modules/api-key/api-key-repository";
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
import { DeploymentsService } from "@/modules/deployments/deployments.service";
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.service";
import { ProfilesRepository } from "@/modules/profiles/profiles.repository";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { UsersService } from "@/modules/users/services/users.service";
import { UserWithProfile, UsersRepository } from "@/modules/users/users.repository";
import { Injectable, InternalServerErrorException, UnauthorizedException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
@@ -18,7 +19,13 @@ 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 };
export type ApiAuthGuardRequest = Request & {
authMethod: AuthMethods;
organizationId: number | null;
user: ApiAuthGuardUser;
};
export const NO_AUTH_PROVIDED_MESSAGE =
"No authentication method provided. Either pass an API key as 'Bearer' header or OAuth client credentials as 'x-cal-secret-key' and 'x-cal-client-id' headers";
@Injectable()
export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth") {
constructor(
@@ -27,14 +34,15 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
private readonly oauthFlowService: OAuthFlowService,
private readonly tokensRepository: TokensRepository,
private readonly userRepository: UsersRepository,
private readonly apiKeyRepository: ApiKeyRepository,
private readonly apiKeyRepository: ApiKeysRepository,
private readonly oauthRepository: OAuthClientRepository,
private readonly profilesRepository: ProfilesRepository
private readonly profilesRepository: ProfilesRepository,
private readonly usersService: UsersService
) {
super();
}
async authenticate(request: Request & { authMethod: AuthMethods }) {
async authenticate(request: ApiAuthGuardRequest) {
try {
const { params } = request;
const oAuthClientSecret = request.get(X_CAL_SECRET_KEY);
@@ -43,7 +51,7 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
if (oAuthClientId && oAuthClientSecret) {
request.authMethod = AuthMethods["OAUTH_CLIENT"];
return await this.authenticateOAuthClient(oAuthClientId, oAuthClientSecret);
return await this.authenticateOAuthClient(oAuthClientId, oAuthClientSecret, request);
}
if (bearerToken) {
@@ -51,7 +59,7 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
request.authMethod = isApiKey(bearerToken, this.config.get<string>("api.apiKeyPrefix") ?? "cal_")
? AuthMethods["API_KEY"]
: AuthMethods["ACCESS_TOKEN"];
return await this.authenticateBearerToken(bearerToken, requestOrigin);
return await this.authenticateBearerToken(bearerToken, request, requestOrigin);
}
const nextAuthSecret = this.config.get("next.authSecret", { infer: true });
@@ -59,12 +67,10 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
if (nextAuthToken) {
request.authMethod = AuthMethods["NEXT_AUTH"];
return await this.authenticateNextAuth(nextAuthToken);
return await this.authenticateNextAuth(nextAuthToken, request);
}
throw new UnauthorizedException(
"No authentication method provided. Either pass an API key as 'Bearer' header or OAuth client credentials as 'x-cal-secret-key' and 'x-cal-client-id' headers"
);
throw new UnauthorizedException(NO_AUTH_PROVIDED_MESSAGE);
} catch (err) {
if (err instanceof Error) {
return this.error(err);
@@ -75,8 +81,8 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
}
}
async authenticateNextAuth(token: { email?: string | null }) {
const user = await this.nextAuthStrategy(token);
async authenticateNextAuth(token: { email?: string | null }, request: ApiAuthGuardRequest) {
const user = await this.nextAuthStrategy(token, request);
return this.success(this.getSuccessUser(user));
}
@@ -87,12 +93,16 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
};
}
async authenticateOAuthClient(oAuthClientId: string, oAuthClientSecret: string) {
const user = await this.oAuthClientStrategy(oAuthClientId, oAuthClientSecret);
async authenticateOAuthClient(
oAuthClientId: string,
oAuthClientSecret: string,
request: ApiAuthGuardRequest
) {
const user = await this.oAuthClientStrategy(oAuthClientId, oAuthClientSecret, request);
return this.success(this.getSuccessUser(user));
}
async oAuthClientStrategy(oAuthClientId: string, oAuthClientSecret: string) {
async oAuthClientStrategy(oAuthClientId: string, oAuthClientSecret: string, request: ApiAuthGuardRequest) {
const client = await this.oauthRepository.getOAuthClient(oAuthClientId);
if (!client) {
@@ -115,14 +125,20 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
throw new UnauthorizedException("No user associated with the provided OAuth client");
}
request.organizationId = client.organizationId;
return user;
}
async authenticateBearerToken(authString: string, requestOrigin: string | undefined) {
async authenticateBearerToken(
authString: string,
request: ApiAuthGuardRequest,
requestOrigin: string | undefined
) {
try {
const user = isApiKey(authString, this.config.get<string>("api.apiKeyPrefix") ?? "cal_")
? await this.apiKeyStrategy(authString)
: await this.accessTokenStrategy(authString, requestOrigin);
? await this.apiKeyStrategy(authString, request)
: await this.accessTokenStrategy(authString, request, requestOrigin);
if (!user) {
return this.error(new UnauthorizedException("No user associated with the provided token"));
@@ -139,7 +155,7 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
}
}
async apiKeyStrategy(apiKey: string) {
async apiKeyStrategy(apiKey: string, request: ApiAuthGuardRequest) {
const isLicenseValid = await this.deploymentsService.checkLicense();
if (!isLicenseValid) {
throw new UnauthorizedException("Invalid or missing CALCOM_LICENSE_KEY environment variable");
@@ -163,10 +179,12 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
}
const user: UserWithProfile | null = await this.userRepository.findByIdWithProfile(apiKeyOwnerId);
request.organizationId = keyData.teamId;
return user;
}
async accessTokenStrategy(accessToken: string, origin?: string) {
async accessTokenStrategy(accessToken: string, request: ApiAuthGuardRequest, origin?: string) {
const accessTokenValid = await this.oauthFlowService.validateAccessToken(accessToken);
if (!accessTokenValid) {
throw new UnauthorizedException(INVALID_ACCESS_TOKEN);
@@ -190,10 +208,17 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
}
const user: UserWithProfile | null = await this.userRepository.findByIdWithProfile(ownerId);
if (!user) {
throw new UnauthorizedException("User associated with the authentication api key not found.");
}
const organizationId = this.usersService.getUserMainOrgId(user) as number;
request.organizationId = organizationId;
return user;
}
async nextAuthStrategy(token: { email?: string | null }) {
async nextAuthStrategy(token: { email?: string | null }, request: ApiAuthGuardRequest) {
if (!token.email) {
throw new UnauthorizedException("Email not found in the authentication token.");
}
@@ -202,6 +227,8 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
if (!user) {
throw new UnauthorizedException("User associated with the authentication token email not found.");
}
const organizationId = this.usersService.getUserMainOrgId(user) as number;
request.organizationId = organizationId;
return user;
}
@@ -3,6 +3,7 @@ import { BillingRepository } from "@/modules/billing/billing.repository";
import { BillingController } from "@/modules/billing/controllers/billing.controller";
import { BillingConfigService } from "@/modules/billing/services/billing.config.service";
import { BillingService } from "@/modules/billing/services/billing.service";
import { ManagedOrganizationsBillingService } from "@/modules/billing/services/managed-organizations.billing.service";
import { MembershipsModule } from "@/modules/memberships/memberships.module";
import { OrganizationsModule } from "@/modules/organizations/organizations.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
@@ -26,8 +27,14 @@ import { Module } from "@nestjs/common";
}),
UsersModule,
],
providers: [BillingConfigService, BillingService, BillingRepository, BillingProcessor],
exports: [BillingService, BillingRepository],
providers: [
BillingConfigService,
BillingService,
BillingRepository,
BillingProcessor,
ManagedOrganizationsBillingService,
],
exports: [BillingService, BillingRepository, ManagedOrganizationsBillingService],
controllers: [BillingController],
})
export class BillingModule {}
@@ -1,5 +1,5 @@
import { BillingRepository } from "@/modules/billing/billing.repository";
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { StripeService } from "@/modules/stripe/stripe.service";
import { Process, Processor } from "@nestjs/bull";
import { Logger } from "@nestjs/common";
@@ -38,7 +38,7 @@ export class BillingRepository {
async updateBillingOverdue(subId: string, cusId: string, overdue: boolean) {
try {
return this.dbWrite.prisma.platformBilling.update({
return this.dbWrite.prisma.platformBilling.updateMany({
where: {
subscriptionId: subId,
customerId: cusId,
@@ -141,7 +141,6 @@ describe("Platform Billing Controller (e2e)", () => {
},
} as unknown as Stripe)
);
return request(app.getHttpServer())
.post("/v2/billing/webhook")
.expect(200)
@@ -3,7 +3,7 @@ import { BILLING_QUEUE, INCREMENT_JOB, IncrementJobDataType } from "@/modules/bi
import { BillingRepository } from "@/modules/billing/billing.repository";
import { BillingConfigService } from "@/modules/billing/services/billing.config.service";
import { PlatformPlan } from "@/modules/billing/types";
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { StripeService } from "@/modules/stripe/stripe.service";
import { InjectQueue } from "@nestjs/bull";
import {
@@ -0,0 +1,34 @@
import { PlatformPlan } from "@/modules/billing/types";
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable, NotFoundException } from "@nestjs/common";
@Injectable()
export class ManagedOrganizationsBillingService {
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
async createManagedOrganizationBilling(managerOrgId: number, managedOrgId: number) {
const managerOrgBilling = await this.dbRead.prisma.platformBilling.findUnique({
where: { id: managerOrgId },
});
if (!managerOrgBilling) {
throw new NotFoundException("Manager organization billing not found.");
}
if (managerOrgBilling.plan !== PlatformPlan.SCALE) {
throw new NotFoundException("Manager organization billing plan is not SCALE.");
}
return this.dbWrite.prisma.platformBilling.create({
data: {
id: managedOrgId,
customerId: managerOrgBilling.customerId,
subscriptionId: managerOrgBilling.subscriptionId,
plan: managerOrgBilling.plan,
billingCycleStart: managerOrgBilling.billingCycleStart,
billingCycleEnd: managerOrgBilling.billingCycleEnd,
overdue: managerOrgBilling.overdue,
managerBillingId: managerOrgBilling.id,
},
});
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { BillingModule } from "@/modules/billing/billing.module";
import { ConferencingModule } from "@/modules/conferencing/conferencing.module";
import { DestinationCalendarsModule } from "@/modules/destination-calendars/destination-calendars.module";
import { OAuthClientModule } from "@/modules/oauth-clients/oauth-client.module";
import { OrganizationsTeamsBookingsModule } from "@/modules/organizations/controllers/teams/bookings/organizations-teams-bookings.module";
import { OrganizationsTeamsBookingsModule } from "@/modules/organizations/teams/bookings/organizations-teams-bookings.module";
import { RouterModule } from "@/modules/router/router.module";
import { StripeModule } from "@/modules/stripe/stripe.module";
import { TimezoneModule } from "@/modules/timezones/timezones.module";
@@ -1,10 +1,11 @@
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
import { MembershipsService } from "@/modules/memberships/services/memberships.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule],
providers: [MembershipsRepository],
exports: [MembershipsRepository],
providers: [MembershipsRepository, MembershipsService],
exports: [MembershipsRepository, MembershipsService],
})
export class MembershipsModule {}
@@ -0,0 +1,24 @@
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
import { Injectable } from "@nestjs/common";
import { intersectionBy } from "lodash";
@Injectable()
export class MembershipsService {
constructor(private readonly membershipsRepository: MembershipsRepository) {}
async haveMembershipsInCommon(firstUserId: number, secondUserId: number) {
const memberships = await this.membershipsInCommon(firstUserId, secondUserId);
return memberships.length > 0;
}
async membershipsInCommon(firstUserId: number, secondUserId: number) {
const firstUserMemberships = await this.membershipsRepository.findUserMemberships(firstUserId);
const secondUserMemberships = await this.membershipsRepository.findUserMemberships(secondUserId);
return intersectionBy(
firstUserMemberships.filter((m) => m.accepted),
secondUserMemberships.filter((m) => m.accepted),
"teamId"
);
}
}
@@ -74,6 +74,7 @@ describe("OAuth Client Users Endpoints", () => {
let app: INestApplication;
let oAuthClient: PlatformOAuthClient;
let oAuthClientEventTypesDisabled: PlatformOAuthClient;
let organization: Team;
let userRepositoryFixture: UserRepositoryFixture;
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
@@ -84,6 +85,7 @@ describe("OAuth Client Users Endpoints", () => {
let membershipsRepositoryFixture: MembershipRepositoryFixture;
let postResponseData: CreateManagedUserOutput["data"];
let postResponseData2: CreateManagedUserOutput["data"];
const platformAdminEmail = `oauth-client-users-admin-${randomString()}@api.com`;
let platformAdmin: User;
@@ -91,6 +93,9 @@ describe("OAuth Client Users Endpoints", () => {
const userEmail = `oauth-client-users-user-${randomString()}@api.com`;
const userTimeZone = "Europe/Rome";
const userEmail2 = `oauth-client-users-user2-${randomString()}@api.com`;
const userTimeZone2 = "America/New_York";
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
providers: [PrismaExceptionFilter, HttpExceptionFilter],
@@ -116,6 +121,7 @@ describe("OAuth Client Users Endpoints", () => {
isOrganization: true,
});
oAuthClient = await createOAuthClient(organization.id);
oAuthClientEventTypesDisabled = await createOAuthClient(organization.id, false);
await profilesRepositoryFixture.create({
uid: "asd1qwwqeqw-asddsadasd",
@@ -136,12 +142,13 @@ describe("OAuth Client Users Endpoints", () => {
await app.init();
});
async function createOAuthClient(organizationId: number) {
async function createOAuthClient(organizationId: number, areDefaultEventTypesEnabled?: boolean) {
const data = {
logo: "logo-url",
name: "name",
redirectUris: [CLIENT_REDIRECT_URI],
permissions: 32,
areDefaultEventTypesEnabled,
};
const secret = "secret";
@@ -185,7 +192,7 @@ describe("OAuth Client Users Endpoints", () => {
.expect(400);
});
it(`/POST`, async () => {
it(`/POST with default event types`, async () => {
const requestBody: CreateManagedUserInput = {
email: userEmail,
timeZone: userTimeZone,
@@ -218,14 +225,55 @@ describe("OAuth Client Users Endpoints", () => {
expect(responseBody.data.accessToken).toBeDefined();
expect(responseBody.data.refreshToken).toBeDefined();
await userConnectedToOAuth(responseBody.data.user.email);
await userConnectedToOAuth(oAuthClient.id, 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) {
const oAuthUsers = await oauthClientRepositoryFixture.getUsers(oAuthClient.id);
it(`/POST without default event types`, async () => {
const requestBody: CreateManagedUserInput = {
email: userEmail2,
timeZone: userTimeZone2,
weekStart: "Monday",
timeFormat: 24,
locale: Locales.FR,
name: "Alice Smith",
avatarUrl: "https://cal.com/api/avatar/2b735186-b01b-46d3-87da-019b8f61776b.png",
};
const response = await request(app.getHttpServer())
.post(`/api/v2/oauth-clients/${oAuthClientEventTypesDisabled.id}/users`)
.set("x-cal-secret-key", oAuthClientEventTypesDisabled.secret)
.send(requestBody)
.expect(201);
const responseBody: CreateManagedUserOutput = response.body;
postResponseData2 = responseBody.data;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
expect(responseBody.data.user.email).toEqual(
getOAuthUserEmail(oAuthClientEventTypesDisabled.id, requestBody.email)
);
expect(responseBody.data.user.timeZone).toEqual(requestBody.timeZone);
expect(responseBody.data.user.name).toEqual(requestBody.name);
expect(responseBody.data.user.weekStart).toEqual(requestBody.weekStart);
expect(responseBody.data.user.timeFormat).toEqual(requestBody.timeFormat);
expect(responseBody.data.user.locale).toEqual(requestBody.locale);
expect(responseBody.data.user.avatarUrl).toEqual(requestBody.avatarUrl);
expect(responseBody.data.accessToken).toBeDefined();
expect(responseBody.data.refreshToken).toBeDefined();
await userConnectedToOAuth(oAuthClientEventTypesDisabled.id, responseBody.data.user.email);
await userDoesNotHaveDefaultEventTypes(responseBody.data.user.id);
await userHasDefaultSchedule(responseBody.data.user.id, responseBody.data.user.defaultScheduleId);
await userHasOnlyOneSchedule(responseBody.data.user.id);
});
async function userConnectedToOAuth(oAuthClientId: string, userEmail: string) {
const oAuthUsers = await oauthClientRepositoryFixture.getUsers(oAuthClientId);
const newOAuthUser = oAuthUsers?.find((user) => user.email === userEmail);
expect(oAuthUsers?.length).toEqual(1);
@@ -251,6 +299,11 @@ describe("OAuth Client Users Endpoints", () => {
).toBeTruthy();
}
async function userDoesNotHaveDefaultEventTypes(userId: number) {
const defaultEventTypes = await eventTypesRepositoryFixture.getAllUserEventTypes(userId);
expect(defaultEventTypes?.length).toEqual(0);
}
async function userHasDefaultSchedule(userId: number, scheduleId: number | null) {
expect(scheduleId).toBeDefined();
expect(scheduleId).not.toBeNull();
@@ -358,12 +411,18 @@ describe("OAuth Client Users Endpoints", () => {
afterAll(async () => {
await oauthClientRepositoryFixture.delete(oAuthClient.id);
await oauthClientRepositoryFixture.delete(oAuthClientEventTypesDisabled.id);
await teamRepositoryFixture.delete(organization.id);
try {
await userRepositoryFixture.delete(postResponseData.user.id);
} catch (e) {
// User might have been deleted by the test
}
try {
await userRepositoryFixture.delete(postResponseData2.user.id);
} catch (e) {
// User might have been deleted by the test
}
try {
await userRepositoryFixture.delete(platformAdmin.id);
} catch (e) {
@@ -85,14 +85,11 @@ export class OAuthClientUsersController {
`Creating user with data: ${JSON.stringify(body, null, 2)} for OAuth Client with ID ${oAuthClientId}`
);
const client = await this.oauthRepository.getOAuthClient(oAuthClientId);
if (!client) {
throw new NotFoundException(`OAuth Client with ID ${oAuthClientId} not found`);
}
const isPlatformManaged = true;
const { user, tokens } = await this.oAuthClientUsersService.createOauthClientUser(
oAuthClientId,
body,
isPlatformManaged,
client?.organizationId
);
const { user, tokens } = await this.oAuthClientUsersService.createOAuthClientUser(client, body);
return {
status: SUCCESS_STATUS,
@@ -3,8 +3,7 @@ import { AppModule } from "@/app.module";
import { HttpExceptionFilter } from "@/filters/http-exception.filter";
import { PrismaExceptionFilter } from "@/filters/prisma-exception.filter";
import { AuthModule } from "@/modules/auth/auth.module";
import { NextAuthStrategy } from "@/modules/auth/strategies/next-auth/next-auth.strategy";
import { UpdateOAuthClientInput } from "@/modules/oauth-clients/inputs/update-oauth-client.input";
import { ApiAuthStrategy } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { OAuthClientModule } from "@/modules/oauth-clients/oauth-client.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { UsersModule } from "@/modules/users/users.module";
@@ -15,14 +14,27 @@ import { Membership, PlatformOAuthClient, Team, User } from "@prisma/client";
import * as request from "supertest";
import { PlatformBillingRepositoryFixture } from "test/fixtures/repository/billing.repository.fixture";
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
import { NextAuthMockStrategy } from "test/mocks/next-auth-mock.strategy";
import { ApiAuthMockStrategy } from "test/mocks/api-auth-mock.strategy";
import { randomString } from "test/utils/randomString";
import { withNextAuth } from "test/utils/withNextAuth";
import { withApiAuth } from "test/utils/withApiAuth";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import type { CreateOAuthClientInput } from "@calcom/platform-types";
import {
APPS_READ,
APPS_WRITE,
BOOKING_READ,
BOOKING_WRITE,
EVENT_TYPE_READ,
EVENT_TYPE_WRITE,
PROFILE_READ,
PROFILE_WRITE,
SCHEDULE_READ,
SCHEDULE_WRITE,
SUCCESS_STATUS,
} from "@calcom/platform-constants";
import type { CreateOAuthClientInput, UpdateOAuthClientInput } from "@calcom/platform-types";
import { ApiSuccessResponse } from "@calcom/platform-types";
describe("OAuth Clients Endpoints", () => {
@@ -72,15 +84,15 @@ describe("OAuth Clients Endpoints", () => {
const userEmail = `oauth-clients-user-${randomString()}@api.com`;
beforeAll(async () => {
const moduleRef = await withNextAuth(
const moduleRef = await withApiAuth(
userEmail,
Test.createTestingModule({
providers: [PrismaExceptionFilter, HttpExceptionFilter],
imports: [AppModule, OAuthClientModule, UsersModule, AuthModule, PrismaModule],
})
).compile();
const strategy = moduleRef.get(NextAuthStrategy);
expect(strategy).toBeInstanceOf(NextAuthMockStrategy);
const strategy = moduleRef.get(ApiAuthStrategy);
expect(strategy).toBeInstanceOf(ApiAuthMockStrategy);
usersFixtures = new UserRepositoryFixture(moduleRef);
membershipFixtures = new MembershipRepositoryFixture(moduleRef);
teamFixtures = new TeamRepositoryFixture(moduleRef);
@@ -123,6 +135,7 @@ describe("OAuth Clients Endpoints", () => {
let membershipFixtures: MembershipRepositoryFixture;
let teamFixtures: TeamRepositoryFixture;
let platformBillingRepositoryFixture: PlatformBillingRepositoryFixture;
let oAuthClientsRepositoryFixture: OAuthClientRepositoryFixture;
let user: User;
let org: Team;
@@ -130,19 +143,20 @@ describe("OAuth Clients Endpoints", () => {
const userEmail = `oauth-clients-user-${randomString()}@api.com`;
beforeAll(async () => {
const moduleRef = await withNextAuth(
const moduleRef = await withApiAuth(
userEmail,
Test.createTestingModule({
providers: [PrismaExceptionFilter, HttpExceptionFilter],
imports: [AppModule, OAuthClientModule, UsersModule, AuthModule, PrismaModule],
})
).compile();
const strategy = moduleRef.get(NextAuthStrategy);
expect(strategy).toBeInstanceOf(NextAuthMockStrategy);
const strategy = moduleRef.get(ApiAuthStrategy);
expect(strategy).toBeInstanceOf(ApiAuthMockStrategy);
usersFixtures = new UserRepositoryFixture(moduleRef);
membershipFixtures = new MembershipRepositoryFixture(moduleRef);
teamFixtures = new TeamRepositoryFixture(moduleRef);
platformBillingRepositoryFixture = new PlatformBillingRepositoryFixture(moduleRef);
oAuthClientsRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
user = await usersFixtures.create({
email: userEmail,
@@ -218,17 +232,17 @@ describe("OAuth Clients Endpoints", () => {
membership = await membershipFixtures.addUserToOrg(user, org, "ADMIN", true);
});
it(`/POST`, () => {
it(`/POST`, async () => {
const body: CreateOAuthClientInput = {
name: oAuthClientName,
redirectUris: ["http://test-oauth-client.com"],
permissions: 32,
permissions: ["BOOKING_READ", "PROFILE_WRITE"],
};
return request(app.getHttpServer())
.post("/api/v2/oauth-clients")
.send(body)
.expect(201)
.then((response) => {
.then(async (response) => {
const responseBody: ApiSuccessResponse<{ clientId: string; clientSecret: string }> =
response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
@@ -239,6 +253,9 @@ describe("OAuth Clients Endpoints", () => {
clientId: responseBody.data.clientId,
clientSecret: responseBody.data.clientSecret,
};
const dbOAuthClient = await oAuthClientsRepositoryFixture.get(client.clientId);
expect(dbOAuthClient).toBeDefined();
expect(dbOAuthClient?.permissions).toEqual(BOOKING_READ + PROFILE_WRITE);
});
});
it(`/GET`, () => {
@@ -291,7 +308,18 @@ describe("OAuth Clients Endpoints", () => {
let membership: Membership;
let client: { clientId: string; clientSecret: string };
const oAuthClientName = `oauth-clients-owner-${randomString()}`;
const oAuthClientPermissions = 32;
const oAuthClientPermissions: CreateOAuthClientInput["permissions"] = [
"EVENT_TYPE_READ",
"EVENT_TYPE_WRITE",
"BOOKING_READ",
"BOOKING_WRITE",
"SCHEDULE_READ",
"SCHEDULE_WRITE",
"APPS_READ",
"APPS_WRITE",
"PROFILE_READ",
"PROFILE_WRITE",
];
beforeAll(async () => {
membership = await membershipFixtures.addUserToOrg(user, org, "OWNER", true);
@@ -301,13 +329,13 @@ describe("OAuth Clients Endpoints", () => {
const body: CreateOAuthClientInput = {
name: oAuthClientName,
redirectUris: ["http://test-oauth-client.com"],
permissions: 32,
permissions: ["*"],
};
return request(app.getHttpServer())
.post("/api/v2/oauth-clients")
.send(body)
.expect(201)
.then((response) => {
.then(async (response) => {
const responseBody: ApiSuccessResponse<{ clientId: string; clientSecret: string }> =
response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
@@ -318,6 +346,20 @@ describe("OAuth Clients Endpoints", () => {
clientId: responseBody.data.clientId,
clientSecret: responseBody.data.clientSecret,
};
const dbOAuthClient = await oAuthClientsRepositoryFixture.get(client.clientId);
expect(dbOAuthClient).toBeDefined();
expect(dbOAuthClient?.permissions).toEqual(
EVENT_TYPE_READ +
EVENT_TYPE_WRITE +
BOOKING_READ +
BOOKING_WRITE +
SCHEDULE_READ +
SCHEDULE_WRITE +
APPS_READ +
APPS_WRITE +
PROFILE_READ +
PROFILE_WRITE
);
});
});
@@ -1,8 +1,7 @@
import { getEnv } from "@/env";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { GetOrgId } from "@/modules/auth/decorators/get-org-id/get-org-id.decorator";
import { MembershipRoles } from "@/modules/auth/decorators/roles/membership-roles.decorator";
import { NextAuthGuard } from "@/modules/auth/guards/next-auth/next-auth.guard";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { OrganizationRolesGuard } from "@/modules/auth/guards/organization-roles/organization-roles.guard";
import { GetManagedUsersOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/get-managed-users.output";
import { ManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/managed-user.output";
@@ -10,11 +9,9 @@ import { CreateOAuthClientResponseDto } from "@/modules/oauth-clients/controller
import { GetOAuthClientResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/GetOAuthClientResponse.dto";
import { GetOAuthClientsResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/GetOAuthClientsResponse.dto";
import { OAuthClientGuard } from "@/modules/oauth-clients/guards/oauth-client-guard";
import { UpdateOAuthClientInput } from "@/modules/oauth-clients/inputs/update-oauth-client.input";
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { UsersService } from "@/modules/users/services/users.service";
import { UserWithProfile } from "@/modules/users/users.repository";
import { OAuthClientsService } from "@/modules/oauth-clients/services/oauth-clients/oauth-clients.service";
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { UsersRepository } from "@/modules/users/users.repository";
import {
Body,
@@ -33,16 +30,14 @@ import {
BadRequestException,
} from "@nestjs/common";
import {
ApiTags as DocsTags,
ApiExcludeController as DocsExcludeController,
ApiOperation as DocsOperation,
ApiCreatedResponse as DocsCreatedResponse,
ApiTags,
} from "@nestjs/swagger";
import { User, MembershipRole } from "@prisma/client";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { CreateOAuthClientInput } from "@calcom/platform-types";
import { Pagination } from "@calcom/platform-types";
import { CreateOAuthClientInput, UpdateOAuthClientInput, Pagination } from "@calcom/platform-types";
const AUTH_DOCUMENTATION = `⚠️ First, this endpoint requires \`Cookie: next-auth.session-token=eyJhbGciOiJ\` header. Log into Cal web app using owner of organization that was created after visiting \`/settings/organizations/new\`, refresh swagger docs, and the cookie will be added to requests automatically to pass the NextAuthGuard.
Second, make sure that the logged in user has organizationId set to pass the OrganizationRolesGuard guard.`;
@@ -51,15 +46,16 @@ Second, make sure that the logged in user has organizationId set to pass the Org
path: "/v2/oauth-clients",
version: API_VERSIONS_VALUES,
})
@UseGuards(NextAuthGuard, OrganizationRolesGuard)
@ApiTags("OAuth Clients")
@UseGuards(ApiAuthGuard, OrganizationRolesGuard)
export class OAuthClientsController {
private readonly logger = new Logger("OAuthClientController");
constructor(
private readonly oauthClientRepository: OAuthClientRepository,
private readonly oAuthClientsService: OAuthClientsService,
private readonly userRepository: UsersRepository,
private readonly teamsRepository: OrganizationsRepository,
private usersService: UsersService
private readonly teamsRepository: OrganizationsRepository
) {}
@Post("/")
@@ -71,10 +67,9 @@ export class OAuthClientsController {
type: CreateOAuthClientResponseDto,
})
async createOAuthClient(
@GetUser() user: UserWithProfile,
@GetOrgId() organizationId: number,
@Body() body: CreateOAuthClientInput
): Promise<CreateOAuthClientResponseDto> {
const organizationId = this.usersService.getUserMainOrgId(user) as number;
this.logger.log(
`For organisation ${organizationId} creating OAuth Client with data: ${JSON.stringify(body)}`
);
@@ -84,14 +79,11 @@ export class OAuthClientsController {
throw new BadRequestException("Team is not subscribed, cannot create an OAuth Client.");
}
const { id, secret } = await this.oauthClientRepository.createOAuthClient(organizationId, body);
const oAuthClientCredentials = await this.oAuthClientsService.createOAuthClient(organizationId, body);
return {
status: SUCCESS_STATUS,
data: {
clientId: id,
clientSecret: secret,
},
data: oAuthClientCredentials,
};
}
@@ -99,10 +91,8 @@ export class OAuthClientsController {
@HttpCode(HttpStatus.OK)
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER])
@DocsOperation({ description: AUTH_DOCUMENTATION })
async getOAuthClients(@GetUser() user: UserWithProfile): Promise<GetOAuthClientsResponseDto> {
const organizationId = this.usersService.getUserMainOrgId(user) as number;
const clients = await this.oauthClientRepository.getOrganizationOAuthClients(organizationId);
async getOAuthClients(@GetOrgId() organizationId: number): Promise<GetOAuthClientsResponseDto> {
const clients = await this.oAuthClientsService.getOAuthClients(organizationId);
return { status: SUCCESS_STATUS, data: clients };
}
@@ -112,11 +102,7 @@ export class OAuthClientsController {
@DocsOperation({ description: AUTH_DOCUMENTATION })
@UseGuards(OAuthClientGuard)
async getOAuthClientById(@Param("clientId") clientId: string): Promise<GetOAuthClientResponseDto> {
const client = await this.oauthClientRepository.getOAuthClient(clientId);
if (!client) {
throw new NotFoundException(`OAuth client with ID ${clientId} not found`);
}
const client = await this.oAuthClientsService.getOAuthClientById(clientId);
return { status: SUCCESS_STATUS, data: client };
}
@@ -149,8 +135,7 @@ export class OAuthClientsController {
@Body() body: UpdateOAuthClientInput
): Promise<GetOAuthClientResponseDto> {
this.logger.log(`For client ${clientId} updating OAuth Client with data: ${JSON.stringify(body)}`);
const client = await this.oauthClientRepository.updateOAuthClient(clientId, body);
const client = await this.oAuthClientsService.updateOAuthClient(clientId, body);
return { status: SUCCESS_STATUS, data: client };
}
@@ -161,7 +146,7 @@ export class OAuthClientsController {
@UseGuards(OAuthClientGuard)
async deleteOAuthClient(@Param("clientId") clientId: string): Promise<GetOAuthClientResponseDto> {
this.logger.log(`Deleting OAuth Client with ID: ${clientId}`);
const client = await this.oauthClientRepository.deleteOAuthClient(clientId);
const client = await this.oAuthClientsService.deleteOAuthClient(clientId);
return { status: SUCCESS_STATUS, data: client };
}
@@ -1,22 +1,9 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsIn, ValidateNested, IsNotEmptyObject, IsString } from "class-validator";
import { IsIn, ValidateNested, IsNotEmptyObject } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS, REDIRECT_STATUS } from "@calcom/platform-constants";
class DataDto {
@ApiProperty({
example: "clsx38nbl0001vkhlwin9fmt0",
})
@IsString()
clientId!: string;
@ApiProperty({
example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoib2F1dGgtY2xpZW50Iiwi",
})
@IsString()
clientSecret!: string;
}
import { CreateOAuthClientOutput } from "@calcom/platform-types";
export class CreateOAuthClientResponseDto {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@@ -31,8 +18,8 @@ export class CreateOAuthClientResponseDto {
})
@IsNotEmptyObject()
@ValidateNested()
@Type(() => DataDto)
data!: DataDto;
@Type(() => CreateOAuthClientOutput)
data!: CreateOAuthClientOutput;
}
export class CreateOauthClientRedirect {
@@ -1,53 +1,9 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import {
IsArray,
ValidateNested,
IsEnum,
IsString,
IsNumber,
IsOptional,
IsDate,
IsNotEmptyObject,
} from "class-validator";
import { ValidateNested, IsEnum, IsNotEmptyObject } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class PlatformOAuthClientDto {
@ApiProperty({ example: "clsx38nbl0001vkhlwin9fmt0" })
@IsString()
id!: string;
@ApiProperty({ example: "MyClient" })
@IsString()
name!: string;
@ApiProperty({ example: "secretValue" })
@IsString()
secret!: string;
@ApiProperty({ example: 3 })
@IsNumber()
permissions!: number;
@ApiPropertyOptional({ example: "https://example.com/logo.png" })
@IsOptional()
@IsString()
logo!: string | null;
@ApiProperty({ example: ["https://example.com/callback"] })
@IsArray()
@IsString({ each: true })
redirectUris!: string[];
@ApiProperty({ example: 1 })
@IsNumber()
organizationId!: number;
@ApiProperty({ example: "2024-03-23T08:33:21.851Z", type: Date })
@IsDate()
createdAt!: Date;
}
import { PlatformOAuthClientDto } from "@calcom/platform-types";
export class GetOAuthClientResponseDto {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@@ -1,9 +1,9 @@
import { PlatformOAuthClientDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/GetOAuthClientResponse.dto";
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsArray, ValidateNested, IsEnum } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
import { PlatformOAuthClientDto } from "@calcom/platform-types";
export class GetOAuthClientsResponseDto {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@@ -1,6 +1,7 @@
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { ApiAuthGuardRequest, 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 { UserWithProfile } from "@/modules/users/users.repository";
import {
Injectable,
CanActivate,
@@ -15,25 +16,35 @@ 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: ApiAuthGuardUser }>();
const request = context.switchToHttp().getRequest<ApiAuthGuardRequest>();
const organizationId = this.getOrganizationId(context);
const user: ApiAuthGuardUser = request.user;
const organizationId = user ? this.usersService.getUserMainOrgId(user) : null;
const oAuthClientId = request.params.clientId;
if (!oAuthClientId) {
throw new ForbiddenException("No OAuth client associated with the request.");
throw new ForbiddenException("OAuthClientGuard - No OAuth client associated with the request.");
}
if (!user || !organizationId) {
throw new ForbiddenException("No organization associated with the user.");
throw new ForbiddenException("OAuthClientGuard - No organization associated with the user.");
}
const oAuthClient = await this.oAuthClientRepository.getOAuthClient(oAuthClientId);
if (!oAuthClient) {
throw new NotFoundException("OAuth client not found.");
throw new NotFoundException("OAuthClientGuard - OAuth client not found.");
}
return Boolean(user.isSystemAdmin || oAuthClient.organizationId === organizationId);
}
getOrganizationId(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const user: UserWithProfile = request.user;
const authMethodOrganizationId = request.organizationId;
if (authMethodOrganizationId) return authMethodOrganizationId;
const userOrganizationId = user ? this.usersService.getUserMainOrgId(user) : null;
return userOrganizationId;
}
}
@@ -8,9 +8,12 @@ import { OAuthClientsController } from "@/modules/oauth-clients/controllers/oaut
import { OAuthFlowController } from "@/modules/oauth-clients/controllers/oauth-flow/oauth-flow.controller";
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
import { OAuthClientUsersService } from "@/modules/oauth-clients/services/oauth-clients-users.service";
import { OAuthClientsInputService } from "@/modules/oauth-clients/services/oauth-clients/oauth-clients-input.service";
import { OAuthClientsOutputService } from "@/modules/oauth-clients/services/oauth-clients/oauth-clients-output.service";
import { OAuthClientsService } from "@/modules/oauth-clients/services/oauth-clients/oauth-clients.service";
import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.service";
import { OrganizationsModule } from "@/modules/organizations/organizations.module";
import { OrganizationsTeamsService } from "@/modules/organizations/services/organizations-teams.service";
import { OrganizationsTeamsService } from "@/modules/organizations/teams/index/services/organizations-teams.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { RedisModule } from "@/modules/redis/redis.module";
import { StripeModule } from "@/modules/stripe/stripe.module";
@@ -18,6 +21,7 @@ import { TokensModule } from "@/modules/tokens/tokens.module";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { UsersModule } from "@/modules/users/users.module";
import { Global, Module } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
@Global()
@Module({
@@ -40,6 +44,10 @@ import { Global, Module } from "@nestjs/common";
OAuthFlowService,
OAuthClientUsersService,
OrganizationsTeamsService,
OAuthClientsService,
OAuthClientsInputService,
OAuthClientsOutputService,
JwtService,
],
controllers: [OAuthClientUsersController, OAuthClientsController, OAuthFlowController],
exports: [OAuthClientRepository],
@@ -1,24 +1,19 @@
import { JwtService } from "@/modules/jwt/jwt.service";
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import type { PlatformOAuthClient } from "@prisma/client";
import type { CreateOAuthClientInput } from "@calcom/platform-types";
import type { PlatformOAuthClient, Prisma } from "@prisma/client";
@Injectable()
export class OAuthClientRepository {
constructor(
private readonly dbRead: PrismaReadService,
private readonly dbWrite: PrismaWriteService,
private jwtService: JwtService
) {}
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
async createOAuthClient(organizationId: number, data: CreateOAuthClientInput) {
async createOAuthClient(
organizationId: number,
data: Omit<Prisma.PlatformOAuthClientCreateInput, "organization">
) {
return this.dbWrite.prisma.platformOAuthClient.create({
data: {
...data,
secret: this.jwtService.sign(data),
organizationId,
},
});
@@ -86,7 +81,7 @@ export class OAuthClientRepository {
async updateOAuthClient(
clientId: string,
updateData: Partial<CreateOAuthClientInput>
updateData: Prisma.PlatformOAuthClientUpdateInput
): Promise<PlatformOAuthClient> {
return this.dbWrite.prisma.platformOAuthClient.update({
where: { id: clientId },
@@ -1,12 +1,12 @@
import { EventTypesService_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/services/event-types.service";
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
import { OrganizationsTeamsService } from "@/modules/organizations/services/organizations-teams.service";
import { OrganizationsTeamsService } from "@/modules/organizations/teams/index/services/organizations-teams.service";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { CreateManagedUserInput } from "@/modules/users/inputs/create-managed-user.input";
import { UpdateManagedUserInput } from "@/modules/users/inputs/update-managed-user.input";
import { UsersRepository } from "@/modules/users/users.repository";
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
import { User, CreationSource } from "@prisma/client";
import { User, CreationSource, PlatformOAuthClient } from "@prisma/client";
import { createNewUsersConnectToOrgIfExists, slugify } from "@calcom/platform-libraries";
@@ -16,16 +16,13 @@ export class OAuthClientUsersService {
private readonly userRepository: UsersRepository,
private readonly tokensRepository: TokensRepository,
private readonly eventTypesService: EventTypesService_2024_04_15,
private readonly schedulesService: SchedulesService_2024_04_15,
private readonly organizationsTeamsService: OrganizationsTeamsService
private readonly schedulesService: SchedulesService_2024_04_15
) {}
async createOauthClientUser(
oAuthClientId: string,
body: CreateManagedUserInput,
isPlatformManaged: boolean,
organizationId?: number
) {
async createOAuthClientUser(oAuthClient: PlatformOAuthClient, body: CreateManagedUserInput) {
const oAuthClientId = oAuthClient.id;
const organizationId = oAuthClient.organizationId;
const existingUser = await this.getExistingUserByEmail(oAuthClientId, body.email);
if (existingUser) {
throw new ConflictException(
@@ -35,7 +32,9 @@ export class OAuthClientUsersService {
let user: User;
if (!organizationId) {
throw new BadRequestException("You cannot create a managed user outside of an organization");
throw new BadRequestException(
"You cannot create a managed user outside of an organization - the OAuth client does not belong to any organization."
);
} else {
const email = this.getOAuthUserEmail(oAuthClientId, body.email);
user = (
@@ -57,7 +56,7 @@ export class OAuthClientUsersService {
autoAccept: true,
},
},
isPlatformManaged,
isPlatformManaged: true,
timeFormat: body.timeFormat,
weekStart: body.weekStart,
timeZone: body.timeZone,
@@ -79,7 +78,9 @@ export class OAuthClientUsersService {
user.id
);
await this.eventTypesService.createUserDefaultEventTypes(user.id);
if (oAuthClient.areDefaultEventTypesEnabled) {
await this.eventTypesService.createUserDefaultEventTypes(user.id);
}
if (body.timeZone) {
const defaultSchedule = await this.schedulesService.createUserDefaultSchedule(user.id, body.timeZone);
@@ -0,0 +1,29 @@
import { JwtService } from "@/modules/jwt/jwt.service";
import { Injectable } from "@nestjs/common";
import { PERMISSION_MAP } from "@calcom/platform-constants";
import { CreateOAuthClientInput } from "@calcom/platform-types";
@Injectable()
export class OAuthClientsInputService {
constructor(private readonly jwtService: JwtService) {}
transformCreateOAuthClientInput(input: CreateOAuthClientInput) {
const transformed = {
...input,
permissions: this.transformPermissions(input.permissions),
};
return {
...transformed,
secret: this.jwtService.sign(transformed),
};
}
transformPermissions(permissions: Array<keyof typeof PERMISSION_MAP | "*">): number {
const values = permissions.includes("*")
? Object.values(PERMISSION_MAP)
: permissions.map((p) => PERMISSION_MAP[p as keyof typeof PERMISSION_MAP]);
return values.reduce((acc, val) => acc | val, 0);
}
}
@@ -0,0 +1,43 @@
import { Injectable } from "@nestjs/common";
import { PlatformOAuthClient } from "@prisma/client";
import { PERMISSIONS, PERMISSION_MAP } from "@calcom/platform-constants";
import { PlatformOAuthClientDto } from "@calcom/platform-types";
@Injectable()
export class OAuthClientsOutputService {
transformPermissions(permissionsNumber: number): Array<keyof typeof PERMISSION_MAP> {
const permissionNumbers = PERMISSIONS.filter(
(permission) => (permissionsNumber & permission) === permission
);
return permissionNumbers.map(
(permission) =>
Object.entries(PERMISSION_MAP).find(
([_, value]) => value === permission
)?.[0] as keyof typeof PERMISSION_MAP
);
}
transformOAuthClient(client: PlatformOAuthClient): PlatformOAuthClientDto {
return {
id: client.id,
name: client.name,
secret: client.secret,
permissions: this.transformPermissions(client.permissions),
logo: client.logo,
redirectUris: client.redirectUris,
organizationId: client.organizationId,
createdAt: client.createdAt,
bookingRedirectUri: client.bookingRedirectUri ?? undefined,
bookingCancelRedirectUri: client.bookingCancelRedirectUri ?? undefined,
bookingRescheduleRedirectUri: client.bookingRescheduleRedirectUri ?? undefined,
areEmailsEnabled: client.areEmailsEnabled,
areDefaultEventTypesEnabled: client.areDefaultEventTypesEnabled,
};
}
transformOAuthClients(clients: PlatformOAuthClient[]): PlatformOAuthClientDto[] {
return clients.map((client) => this.transformOAuthClient(client));
}
}
@@ -0,0 +1,53 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { CreateOAuthClientInput, UpdateOAuthClientInput } from "@calcom/platform-types";
import { OAuthClientRepository } from "../../oauth-client.repository";
import { OAuthClientsInputService } from "./oauth-clients-input.service";
import { OAuthClientsOutputService } from "./oauth-clients-output.service";
@Injectable()
export class OAuthClientsService {
constructor(
private readonly oauthClientRepository: OAuthClientRepository,
private readonly oauthClientsInputService: OAuthClientsInputService,
private readonly oauthClientsOutputService: OAuthClientsOutputService
) {}
async createOAuthClient(organizationId: number, input: CreateOAuthClientInput) {
const transformedInput = this.oauthClientsInputService.transformCreateOAuthClientInput(input);
const { id, secret } = await this.oauthClientRepository.createOAuthClient(
organizationId,
transformedInput
);
return {
clientId: id,
clientSecret: secret,
};
}
async getOAuthClients(organizationId: number) {
const clients = await this.oauthClientRepository.getOrganizationOAuthClients(organizationId);
return this.oauthClientsOutputService.transformOAuthClients(clients);
}
async getOAuthClientById(clientId: string) {
const client = await this.oauthClientRepository.getOAuthClient(clientId);
if (!client) {
throw new NotFoundException(`OAuth client with ID ${clientId} not found`);
}
return this.oauthClientsOutputService.transformOAuthClient(client);
}
async updateOAuthClient(clientId: string, input: UpdateOAuthClientInput) {
const client = await this.oauthClientRepository.updateOAuthClient(clientId, input);
return this.oauthClientsOutputService.transformOAuthClient(client);
}
async deleteOAuthClient(clientId: string) {
const client = await this.oauthClientRepository.deleteOAuthClient(clientId);
return this.oauthClientsOutputService.transformOAuthClient(client);
}
}
@@ -1,7 +1,7 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { CreateOrganizationAttributeInput } from "@/modules/organizations/inputs/attributes/create-organization-attribute.input";
import { UpdateOrganizationAttributeInput } from "@/modules/organizations/inputs/attributes/update-organization-attribute.input";
import { CreateOrganizationAttributeInput } from "@/modules/organizations/attributes/index/inputs/create-organization-attribute.input";
import { UpdateOrganizationAttributeInput } from "@/modules/organizations/attributes/index/inputs/update-organization-attribute.input";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
@@ -6,16 +6,16 @@ import { PlatformPlanGuard } from "@/modules/auth/guards/billing/platform-plan.g
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 { CreateOrganizationAttributeInput } from "@/modules/organizations/inputs/attributes/create-organization-attribute.input";
import { UpdateOrganizationAttributeInput } from "@/modules/organizations/inputs/attributes/update-organization-attribute.input";
import { CreateOrganizationAttributesOutput } from "@/modules/organizations/outputs/attributes/create-organization-attributes.output";
import { DeleteOrganizationAttributesOutput } from "@/modules/organizations/outputs/attributes/delete-organization-attributes.output";
import { CreateOrganizationAttributeInput } from "@/modules/organizations/attributes/index/inputs/create-organization-attribute.input";
import { UpdateOrganizationAttributeInput } from "@/modules/organizations/attributes/index/inputs/update-organization-attribute.input";
import { CreateOrganizationAttributesOutput } from "@/modules/organizations/attributes/index/outputs/create-organization-attributes.output";
import { DeleteOrganizationAttributesOutput } from "@/modules/organizations/attributes/index/outputs/delete-organization-attributes.output";
import {
GetOrganizationAttributesOutput,
GetSingleAttributeOutput,
} from "@/modules/organizations/outputs/attributes/get-organization-attributes.output";
import { UpdateOrganizationAttributesOutput } from "@/modules/organizations/outputs/attributes/update-organization-attributes.output";
import { OrganizationAttributesService } from "@/modules/organizations/services/attributes/organization-attributes.service";
} from "@/modules/organizations/attributes/index/outputs/get-organization-attributes.output";
import { UpdateOrganizationAttributesOutput } from "@/modules/organizations/attributes/index/outputs/update-organization-attributes.output";
import { OrganizationAttributesService } from "@/modules/organizations/attributes/index/services/organization-attributes.service";
import {
Body,
Controller,
@@ -1,4 +1,4 @@
import { CreateOrganizationAttributeOptionInput } from "@/modules/organizations/inputs/attributes/options/create-organization-attribute-option.input";
import { CreateOrganizationAttributeOptionInput } from "@/modules/organizations/attributes/options/inputs/create-organization-attribute-option.input";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { AttributeType } from "@prisma/client";
import { Type } from "class-transformer";
@@ -1,5 +1,5 @@
import { CreateOrganizationAttributeInput } from "@/modules/organizations/inputs/attributes/create-organization-attribute.input";
import { UpdateOrganizationAttributeInput } from "@/modules/organizations/inputs/attributes/update-organization-attribute.input";
import { CreateOrganizationAttributeInput } from "@/modules/organizations/attributes/index/inputs/create-organization-attribute.input";
import { UpdateOrganizationAttributeInput } from "@/modules/organizations/attributes/index/inputs/update-organization-attribute.input";
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
@@ -1,5 +1,5 @@
import { Attribute } from "@/modules/organizations/outputs/attributes/attribute.output";
import { BaseOutputDTO } from "@/modules/organizations/outputs/attributes/base.output";
import { Attribute } from "@/modules/organizations/attributes/index/outputs/attribute.output";
import { BaseOutputDTO } from "@/modules/organizations/attributes/index/outputs/base.output";
import { Expose, Type } from "class-transformer";
import { ValidateNested } from "class-validator";
@@ -1,5 +1,5 @@
import { Attribute } from "@/modules/organizations/outputs/attributes/attribute.output";
import { BaseOutputDTO } from "@/modules/organizations/outputs/attributes/base.output";
import { Attribute } from "@/modules/organizations/attributes/index/outputs/attribute.output";
import { BaseOutputDTO } from "@/modules/organizations/attributes/index/outputs/base.output";
import { Expose, Type } from "class-transformer";
import { ValidateNested } from "class-validator";
@@ -1,5 +1,5 @@
import { Attribute } from "@/modules/organizations/outputs/attributes/attribute.output";
import { BaseOutputDTO } from "@/modules/organizations/outputs/attributes/base.output";
import { Attribute } from "@/modules/organizations/attributes/index/outputs/attribute.output";
import { BaseOutputDTO } from "@/modules/organizations/attributes/index/outputs/base.output";
import { ApiProperty } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import { IsOptional, ValidateNested } from "class-validator";

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