Compare commits

..
203 Commits
Author SHA1 Message Date
Keith Williams 55f1019908 chore: v4.6.3 (#17161)
release.yml / release (push) Canceled after 0s
2024-10-18 09:01:23 -03:00
Keith Williams 863fc695ec perf: Add index for invalid column in Credential (#17162)
* perf: Add index for invalid column in Credential

* Added missing file change
2024-10-18 11:42:54 +00:00
Keith Williams d931fb1f9c perf: Add indices to Membership (#17160) 2024-10-18 08:31:16 -03:00
Hariom Balhara fd054dfb8d fix: select_any_in operator - Broken only for attributes (#17148)
* Fix select any_in operator for attributes - Broken only for attributres

* Fix ts error
2024-10-18 10:19:25 +00:00
Hariom BalharaandMorgan 699e08b2ee fix: Possible perf improvement and logging for team members routing logic (#17154)
* chore: increase pagination managed users endpoint (#17147)

* Add server-timings and used concurrency 2 for teamMembers matching

---------

Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2024-10-18 09:44:50 +00:00
Alex van Andel e1228ca03c fix: Hide invite_new_member_description cost from users within an organisation (#17149) 2024-10-18 00:22:40 +01:00
Morgan 9ad69c20cf fix: event-types locations output schema apiv2 (#17150) 2024-10-17 21:07:31 +03:00
Somay Chauhan 9a5efd39ce feat: event team Assignment tab atom (#17145)
* feat: event team Assignment tab atom

* Update event-types-atom.service.ts

* Update event-types-atom.service.ts
2024-10-17 17:33:59 +00:00
Morgan 497b0804d3 feat: create event type atom (#17142)
* feat: create event type atom

* fixup! feat: create event type atom

* fixup! fixup! feat: create event type atom

* docs: base doc for create event type atom
2024-10-17 21:51:23 +05:30
Morgan 8b50f419e5 chore: increase pagination managed users endpoint (#17147) 2024-10-17 14:32:35 +00:00
Alex van Andel 9208827406 chore: Release v4.6.2 (#17146)
release.yml / release (push) Canceled after 0s
2024-10-17 15:22:59 +01:00
Udit Takkar 8891381d89 chore: add logs for debugging (#17111)
* chore: add logs

* fix: filter in prisma query

* test: add test for personal event types

* chore: remove OR condition
2024-10-17 13:43:38 +00:00
Hariom Balhara ab39f0c8b6 Add support for multiselect_some_in for attributes query (#17144) 2024-10-17 12:16:34 +00:00
Vadim Rusin cd2382e091 fix: Add error message for taken username (#17129) 2024-10-17 04:44:52 +00:00
Syed Ali Shahbaz 154c54a2aa fix: Update openapi-v1.json bookings post example (#17132)
* Update openapi-v1.json

* Update openapi-v1.json
2024-10-16 20:59:10 -03:00
sean-brydon e949a4c529 fix: pass from org link to all instances of event.public (#17136)
* pass from org link to all instances of event.public

* fix type error

* fix type error
2024-10-16 14:57:39 +01:00
64b321ac9c feat: added custom class name to booker and availability atom (#17105)
* added custom class name for booker atoms wrapper

* atomsWrapper

* added props to availability atom

* allowDelete
* allowSetToDefault
* added customClassNames -> hiddenSwitchClassname, deleteButtonClassname

* Update availability.tsx

* fixup! Merge branch 'main' into add-custom-classname-to-booker-atom-wrapper

---------

Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Morgan Vernay <morgan@cal.com>
2024-10-16 12:04:33 +00:00
e90e060739 feat: Event availability platform wrapper (#17091)
* moved listSchedules to schedule repository

* Create EventAvailabilityTabPlatformWrapper.tsx

* Revert "moved listSchedules to schedule repository"

This reverts commit b5feacfabbadbf9d75eb205dfad8f70b7773a5cb.

* fix: active state of tabs items

* added event availability platform wrapper

* Update event-types.tsx

* better types

only pick the types we need and omit the rest

* fix: type-check failing

---------

Co-authored-by: Morgan Vernay <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2024-10-16 13:24:13 +03:00
Hariom Balhara 123074f4ba fix: Hotfix - Revert hideEventTypeDetails handling in Booker.tsx (#17130)
* Revert "fix: DatePicker not showing up in mobile mode when hideEventTypeDetails is true (#17037)"

This reverts commit 1f08bc5a4f.

* Revert "feat: Booker atom enable hiding event details (#16906)"

This reverts commit ba5b9e951a.

* Keep the playground test scenarios
2024-10-16 10:01:04 +00:00
MorganandKeith Williams 8115c86e37 chore: refactor create event -type forms (#17106)
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-10-16 08:15:54 +00:00
Syed Ali Shahbaz 92a48b466c chore: developer docs updates (#17112)
* remove mention of data proxy

* fix self hosting broken app link

* fix booking doc

* deploy buttons and more options

* fix capitalization
2024-10-15 22:50:54 +00:00
Calcom BotandReplexica 7a4298dc00 feat: update translations (#17120)
Co-authored-by: Replexica <support@replexica.com>
2024-10-15 22:28:53 +00:00
Alex van Andel 3d379c65e8 Chore: release v4.6.1 (#17125)
release.yml / release (push) Canceled after 0s
2024-10-15 19:08:07 +00:00
Alex van Andel b1d509ba30 fix: organizationId called on possibly undefined profile array (#17123) 2024-10-15 18:56:23 +00:00
Alex van Andel 6360e73901 chore: Release v4.6.0 (#17121)
release.yml / release (push) Canceled after 0s
2024-10-15 17:53:06 +00:00
7e44e686e8 feat: attributes filter / refactor of user data table (#17014)
* WIP restored from .git cache

* fix exports

* sortable row model

* feat column visibility component

* wip filters with nuqs

* pull in unique values from table into filters

* correctly assign filters via v/f

* inital selection bar refactor

* data-table selection bar + optmistic update of delete

* dynamic link

* migrate member list table to new data-table

* total list shows filtered value > db valuie

* add filters for attributes

* type errors

* make content bigger on lg

* add mb-6 to teams user datatable to match spacing spec

* correctly render multi-badge

* fix: masss asignment optimistic UI

* fix type errors

* remove log

* fix toolbar type error

* chore: Remove debug artifact

* type errors

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

* use max-w-fit

* chore: Remove unused translation now we don't specify 'mass' in assign

* perf: fix: use the onBlur event to prevent focus loss whilst the list is rerendering

* Move the data-table exports together in the main barrel, then import

* fix exports that were lost in a merge

* fix exports that were lost in a merge

* fix groupteammapping/availbilityslider

* fix overflow problems

* add scrollbar-thin class

* fix type error

* user serverside values for faceted filters

* pass filters to serverside

* filter serverside

* fix team server side filter

* add loaded x of y

* attributes icon change

* correct implementation for text/input attr optimistic

* type check fixes

* fix platform checks

* fix types again

* fix types again

* fix types again

* add use client

* add use client

* fix-types

* fix: Add missing translation in EN

* fix e2e tests via testid

* fix e2e tests via testid

* fix: Member invite popup not popping up

* Update copyInviteLink to new-member-button testid

* Hopefully fix test ids this time

* fix: Use the right buttons on the right pages

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-10-15 17:45:11 +00:00
Udit Takkar 0b914bef79 fix: update meeting token if expired (#17096) 2024-10-15 10:41:18 -07:00
a48d190af3 feat: #15416 Expand round robin availability beyond default schedule (#15618)
* add feature to change host schedule

* update for type-check:ci

* Update SingleForm.tsx for linterr

* update as per design review

* update for rerendering

* migration files

* On Delete set null for schedule

if schedule is deleted, no need to delete the host

* updated schema

* added testcases

* checking permissions before

* updated for comments

* update for initial value

* updated and cleanup

* set initial value

* update after merge

* updated nit style

* update for console warning and added comments

* nit/chore

* chore

* update for typechecks

* update for scheduleId param after merge

* update after merge or new changes in metadata.config

* update after weights functionality

* updated description text and column name as per review suggestion

* resolved merge conflicts

* fix typecheck due to changes in getScheduleSchema

* update after merge having refactor

* update refactored EventTypeWebWrapper after merge

* updated props

* updated trpc err code and added log

* update due to refactor in EventAvailabilityTab

* perf: Optimise TS type + select only the data that's needed for a specific function

---------

Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com>
Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-10-15 17:36:00 +01:00
Rajiv SahalandKeith Williams c21f0caecf chore: revamp platform docs (#17117)
* all atoms have standalone page

* restructure tabs for platfom pages

* remove unused page

* add missing icons

* cleanup intro page for platform

* update loom links

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-10-15 15:21:09 +00:00
Anik Dhabal Babu 1f42a152b0 fix: link is not rendering properly for SMS and WhatsApp workflows (#17116) 2024-10-15 15:11:29 +00:00
Hariom Balhara b8f0cc6fa1 fix: Add back missing Any in and Not in operators for Single Select (#17102)
* fix: Missing any_in and not_anhy_in opperators

* Add tests
2024-10-15 15:07:40 +00:00
Anik Dhabal Babu c6f84e6c4b fix: Issue chargin no show fee (#17066) 2024-10-15 15:05:53 +00:00
Morgan 9c3f4ec055 feat: allow delete event-type platform atoms (#17065)
* feat: allow delete event-type platform atoms

* fixup! feat: allow delete event-type platform atoms
2024-10-15 14:40:57 +00:00
Alex van Andel f0cfbede7e fix: Fix TS error + set isPending on Button (#17118) 2024-10-15 13:59:31 +00:00
Keith Williams e2a825a9a0 Revert "feat: update github workflows to install playwright in a separate job (#17070)" (#17114)
This reverts commit 0b3b268eed.
2024-10-15 08:23:52 -03:00
Keith Williams 963a2a0b76 fix: Playwright install (#17113) 2024-10-15 07:58:38 -03:00
Benny Joo 4037367f8c fix: theme flickering (#16903)
* fix: theme flickering

* finalise
2024-10-15 11:13:39 +01:00
Aditya GhadgeandKeith Williams 0b3b268eed feat: update github workflows to install playwright in a separate job (#17070)
* feat: update github workflows to install playwright in a separate job

* Update .github/workflows/pr.yml

* Update .github/workflows/pr.yml

* Update .github/workflows/pr.yml

* Update .github/workflows/pr.yml

* Update .github/workflows/pr.yml

* Update .github/workflows/pr.yml

* Update .github/workflows/pr.yml

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-10-15 10:09:38 +00:00
amrit 2acb5559dc refactor: improve variable logic (#17086)
* Improve app processing with async/await and dynamic imports, also fix eslint errors.

* refactor

* added back a comment
2024-10-15 06:35:26 -03:00
Keith Williams be1c6eb65c fix: PR update workflow duplicate job (#17108) 2024-10-15 05:30:22 -03:00
Keith Williams feefa26c90 chore: Add docs build (#17101)
* chore: Add Docs build to CI

* Added build-docs to flow

* Updated to run in the /docs folder

* Made web app build have consistent name

* Added a kill after the command runs

* Test the build

* Added it to the PR flow
2024-10-15 05:08:32 -03:00
Avishay Maor 2c25f88100 Update constants.ts - fix crashing by adding optional chaining for this value (#17103) 2024-10-15 07:32:27 +00:00
2be9fc8bc0 fix: email-address with apostrophe not accepted (#15535)
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Omar López <zomars@me.com>
Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com>
2024-10-15 00:21:26 +00:00
Peer Richelsen 5927b42560 Update mint.json (#17085) 2024-10-14 18:48:03 -03:00
Rajiv SahalandMorgan 5726d18027 feat: member management for platform (#16803)
* init members page for platform

* add missing icon

* add members tab to sidebar

* use data from useMe query instead of useSession

* return user profiles since platform users are stored there

* small refactor

* fixup

* remove unused logs from console

* fixup

* resolve merge conflicts

* add missing tabs for members and billing

* update schema

* fixup

* memoise selection options for org and platform

* update onSubmit handler

* resolve merge conflicts

* add members tab

* improve team billing view when user not subscribed

* update members tab

* add function to find if user is admin of team

* update invite members handler to handle platform user as well

---------

Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2024-10-14 21:19:02 +03:00
Anik Dhabal Babu 3312d9cfc6 fix: 500 status code visible when cancelling event (#16957)
* fix: 500 status code visible when cancelling event

* update
2024-10-14 12:58:28 -04:00
Steve Xu c140b01548 fix: Memory leak with cal embed modal box (#17016) 2024-10-14 12:42:57 -04:00
Lauris Skraucis c2085c6be9 refactor: v2 recurring bookings allow specifying recurrence count (#16989)
* fix: CreateBookingInputPipe

* refactor: allow specifying recurrence count

* Update input.service.ts
2024-10-14 17:59:53 +03:00
sean-brydon b8b9d04897 up stripe trails (#17092) 2024-10-14 13:01:01 +00:00
Udit TakkarandSyed Ali Shahbaz 4497c4ce0b perf: improve get bookings performance (#16303)
* refactor: improve get bookings performance

* feat: use map to optimise

* chore: save

* chore: add authorization

* chore: remove condition

* chore: improvements

* chore

* chore: remove return

* chore: use Promise.all

---------

Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>
2024-10-14 17:57:58 +05:30
Anik Dhabal Babu cd06141816 fix: improved code for meeting link is not updated and broken ui in edit location dialog issue (#16013)
* improvise code of issue#15497

* Update editLocation.handler.ts

* update

* Update EditLocationDialog.tsx

* Update editLocation.handler.ts
2024-10-14 08:56:17 +00:00
Rajiv Sahal 013646bf2c fix: atoms tooltip (#17073)
* add tooltip classname prop for styling

* fix incorrect styling

* update props for connect buttons
2024-10-14 09:37:19 +03:00
Anik Dhabal BabuandAlex van Andel 12bbbe3617 fix: Daterangepicker is not opening in some browsers (#17087)
* fix: daterangepicker issue

* update

* fix: useTeamPlan isn't relevant on self-hosted

* chore: Revert UpgradeTeamsBadge fixes, unrelevant to this PR

* fix: Fix button width for other languages

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-10-14 06:46:37 +05:30
Peer Richelsen 2c7c9fd716 feat: telli.so app (#17083) 2024-10-12 17:34:23 +00:00
Keith Williams 11fc2a738a fix: Docs build issue (#17082) 2024-10-12 16:53:43 +00:00
Calcom BotandReplexica 44ab25b4a0 feat: update translations (#17076)
Co-authored-by: Replexica <support@replexica.com>
2024-10-12 13:30:54 -03:00
Ezhil Shanmugham 4a2c0cb164 fix: lock on user view (#17077)
* fix: lock on user view

* fix: lock on user view
2024-10-12 13:54:12 +00:00
Joe Au-YeungandUdit Takkar b1d9e2b84c feat: Salesforce choose how to save attendees & other options (#17009)
* Refactor get SF user and create event

* Add new Salesforce options

* Pass app options to CrmService

* Add record enum

* Add creating new lead and contact under an account

* Handle if the contact already exists but not connected to account

* Create a lead if an account doesn't exist

* Merge fix

* Refactor - add generateCreateRecordBody

* Type fix

* Clean up

* Add getAppOptions to other CRM services

* Type fixes

* Fix typo

* feat: Salesforce round robin skip - choose which entity to search on (#17038)

* Add option to search which entity for the owner

* Add logic to search entity for skipping RR assignment

* Type fixes

* Disable license

* Skip license check in component

* Revert license changes

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-10-12 10:02:27 +00:00
Carina WollendorferandCarinaWolli 47b9e8a8ac fix: attendee name workflow variables in spanish (#17068)
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2024-10-11 09:12:23 -07:00
Benny JooandAlex van Andel 42265021fe chore: settings/my-account - remove pages router (#17056)
* remove pages router and use app router

* fix page

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-10-11 16:30:03 +01:00
Anik Dhabal BabuandUdit Takkar 0b0fee3985 fix: phone number input field is missing from mail (#17035)
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-10-11 11:17:18 +00:00
Benny JooandAlex van Andel 5718cc5e17 chore: remove react-query, update next.js to v13.5.6 (#17057)
* chore: remove react-query as unneeded

* chore: Re-gen lockfile

* chore: Bump next.js to v13.5.6

* yarn.lock regen after apps/console next version bump

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-10-11 10:06:20 +00:00
Benny Joo 361889ded7 add node-gyp as dev dependency (#17058) 2024-10-11 10:28:37 +01:00
Rajiv Sahal 2260ddcebc add missing tab for billing in navigation (#17060) 2024-10-11 12:42:32 +05:30
Keith Williams 80c3b91077 chore: Update CI to not run all checks for docs/translations (#17054) 2024-10-11 09:44:13 +05:30
Calcom BotandReplexica a11cf130bf feat: update translations (#17051)
Co-authored-by: Replexica <support@replexica.com>
2024-10-10 20:46:33 +00:00
Omar López f9d6ea2a00 chore: v4.5.11 (#17053)
release.yml / release (push) Canceled after 0s
2024-10-10 13:23:28 -07:00
Udit Takkar 50f6aa5f58 perf: refactor and replacing viewer.teams.getMinimal with viewer.teams.get (#16552) 2024-10-10 12:51:07 -07:00
Keith Williams 132746af74 perf: Use UNION to get public user event types (#17052) 2024-10-10 19:39:32 +00:00
395381ddcc feat: automatic no show (#16727)
Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: zomars <zomars@me.com>
2024-10-10 10:57:04 -07:00
Keith Williams ef88effd9f perf: Add index to EventType for parentId (#17049) 2024-10-10 17:46:12 +00:00
Calcom BotandReplexica 673a2be7c7 feat: update translations (#17042)
Co-authored-by: Replexica <support@replexica.com>
2024-10-10 17:19:27 +00:00
Shrey TannaandAlex van Andel b1cd3e940e feat: Add Eastern and Eastern Pacific time zones #16880 (#16974)
* add eastern and eastern pacific timezones

* fixed issue while running tests.

* fix: Find Braz..il instead of Brasil

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-10-10 16:26:17 +00:00
Alex van Andel 711bec8d71 chore: Add typings for DOMPurify (#17047) 2024-10-10 17:17:13 +01:00
Syed Ali Shahbaz 7529e331a3 Pick attendee id in response (#17041) 2024-10-10 15:40:58 +00:00
Peer RichelsenandAlex van Andel cc147d0797 chore: docs changes (#17031)
* Update introduction.mdx

* added new logo

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-10-10 15:24:21 +00:00
c8e8800647 chore: Update EWS package (#16950)
* Update ews package

* Hide exchange version if using NTLM

* Remove instance of gzip

* Update yarn.lock file

* Updated yarn.lock

* Update yarn.lock

* Update yarn.lock

* Update yarn.lock (again)

* chore: Increase readability of [number] indexes by using find

* chore: Async not needed

* fix: Move 'use client' to appropriate file

* refactor

* install deasync directly as dev dependency

* fix type error

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: Benny Joo <sldisek783@gmail.com>
2024-10-10 15:48:58 +01:00
99caae8665 feat: advanced tab platform wrapper (#16941)
* fixed error in advanced tab atom build

-- used `DOMPurify` instead of `sanitize-html`

* hide BookerLayoutSelector for platform and removePlatformClientIdFromEmail

* fixup! Merge branch 'main' into event-advanced-platform-wrapper

* undo linting changes

* undo linting changes

* fix: active state of tabs items

---------

Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Morgan Vernay <morgan@cal.com>
2024-10-10 17:09:03 +03:00
Hariom Balhara 1f08bc5a4f fix: DatePicker not showing up in mobile mode when hideEventTypeDetails is true (#17037) 2024-10-10 18:09:53 +05:30
Morgan 5594e5c713 feat: google meet conferencing api v2 (#17023)
* feat: google meet conferencing api v2

* feat: add set default google meet conferencing app

* fixup! feat: add set default google meet conferencing app
2024-10-10 09:28:53 +00:00
Rajiv SahalandMorgan 34afc7b674 feat: additional calendar selector for calendar settings atom (#16874)
* update translations

* fixup

* add onSuccess prop

* add additional calendar selector prop to add multiple calendars

* update props for calendar settings atom

* pass caledar redirect urls for google and apple calendar redirects

* fix merge conflicts

* add onSuccess prop to connect atoms

* fixup

* fixup

---------

Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2024-10-10 09:02:40 +00:00
Somay Chauhan 513a58c91c feat: event type tabs platform wrapper (#16891)
* added event-type platform wrappers

* added weekly

* Update RecurringEventController.tsx
2024-10-10 10:55:13 +03:00
Syed Ali Shahbaz 375b9190a3 add slot endpoint (#17034) 2024-10-09 20:59:10 +00:00
Anik Dhabal Babu 83d7bf322a fix: add missing options for team memberlist table (#17017)
* fix: missing option for team memberlist table

* update
2024-10-09 18:23:45 +01:00
06429e27fb test: Add Attributes Routing e2e and some more unit tests (#17032)
* Initial commit

* routingForm to Booking a particular team member working

* Happy path working

* Fixes

* Fix router query params forwarding

* Add basicConfig within app

* Tests

* More tests

* Update packages/app-store/routing-forms/components/SingleForm.tsx

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

* WIP

* Fix lint issues

* Fix tests -TS and add new logic

* Add getEventTypeRedirectUrl tests

* Remove booking title changes code

* More changes

* Add tests for getRoutedUsers

* More tests

* Update testUtils.ts

---------

Co-authored-by: Omar López <zomars@me.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-10-09 22:47:16 +05:30
Benny Joo 90bcd711a9 fix: padding in TeamPill (and hence TeamRole) (#17030) 2024-10-09 15:21:26 +00:00
Keith Williams 8d61b452b1 chore: Removed development only docs tags (#17028) 2024-10-09 11:58:58 -03:00
Hariom BalharaandOmar López 03d0b98155 feat: Skip contact owner even if it matches attribute routing (#17015)
Co-authored-by: Omar López <zomars@me.com>
2024-10-09 07:30:12 -07:00
de503add83 feat: add nextcloud talk app (#16455)
* Initial draft of nextcloud app

* Add video adapter for creating a new conversation via API

* Make links dynamic, add nc user and pwd for auth, fix link creation

* Add nextcloudTalk app to yarn.lock

* Fix screenshot name

* Add OAuth2 handler

* Fix type for booking reference and fix access token header param, (for creating and deleting a meeting)

* Remove comment

* Add README.md file

* Fix redirect URL for authenticating Nextcloud user

---------

Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2024-10-09 17:52:30 +05:30
Keith Williams 1a4cf5f91d fix: URLs to images in docs (#17022) 2024-10-09 11:48:26 +00:00
Calcom BotandReplexica ed53645783 feat: update translations (#17021)
Co-authored-by: Replexica <support@replexica.com>
2024-10-09 10:37:44 +00:00
sean-brydon c7b1fbdf67 feat: mass assign attributes (#16995)
* UI popover on user table

* fix multi select state

* mass assignment

* add i18n
2024-10-09 12:02:48 +02:00
sateshcharan 6d7f7108e5 fix schema.prisma path (#17018) 2024-10-09 08:55:30 +00:00
Hariom Balhara d9aab9088d feat: Support headless router as well in embed (#17012)
* Support /router/embed path and add Headless router usecase in playground

* Fix broken seeded-form testing wrong thing
2024-10-09 13:24:45 +05:30
Hariom Balhara c80daf43b8 Fix prettier error and EMailField import error in website (#17011) 2024-10-09 08:30:29 +02:00
Omar López 2bdf65ce8c fix: billing webhook secret (#17005)
* fix: billing webhook secret

* Update __handler.test.ts
2024-10-08 21:26:39 +00:00
Keith Williams 343e2ac9d7 chore: v4.5.10 (#17001)
release.yml / release (push) Canceled after 0s
2024-10-08 16:59:25 -03:00
Benny Joo 670b82fd23 fix: add fallback to data needed in SettingsLayout (#17004) 2024-10-08 15:51:38 -04:00
Keith Williams e6f81d09c8 chore: Update PR template to account for new docs (#17003) 2024-10-08 15:35:23 -03:00
Benny Joo 8f91ffe692 Revert "remove pages router and use app router (#16793)" (#17002)
This reverts commit 664a92a1d0.
2024-10-08 15:00:43 -03:00
Benny Joo f5dbdae4a9 fix: Close OOO Create Modal on backdrop click (#17000) 2024-10-08 17:42:28 +00:00
Calcom BotandReplexica e99f6048d6 feat: update translations (#16999)
Co-authored-by: Replexica <support@replexica.com>
2024-10-08 23:08:47 +05:30
654a204878 feat: Attribute based routing from Team Routing Form to Team Event(with assigned users matching the attribute logic) (#16823)
* Initial commit

* routingForm to Booking a particular team member working

* Happy path working

* Fixes

* Fix router query params forwarding

* Add basicConfig within app

* Tests

* More tests

* Update packages/app-store/routing-forms/components/SingleForm.tsx

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

---------

Co-authored-by: Omar López <zomars@me.com>
Co-authored-by: Benny Joo <sldisek783@gmail.com>
2024-10-08 21:12:32 +05:30
Syed Ali Shahbaz 7928933852 fixes (#16990) 2024-10-08 15:36:16 +00:00
Lauris SkraucisandMorgan Vernay c4cdba1015 refactor: throttler rate limits for oauth client & access token (#16962)
Co-authored-by: Morgan Vernay <morgan@cal.com>
2024-10-08 17:34:41 +03:00
Benny Joo 5ed36a7fe1 chore: remove react code in getLayout (#16997)
* chore: no need to pass title, description in getLayout

* acutally, we do
2024-10-08 14:22:26 +00:00
Joe Au-YeungandBenny Joo e77a2f6963 fix: Salesforce assign event to organizer (#16971)
* Refactor get SF user and create event

* address code nit

---------

Co-authored-by: Benny Joo <sldisek783@gmail.com>
2024-10-08 14:06:51 +00:00
Lauris Skraucis a10d3599e2 refactor: platform bookings hooks & bookings API (#16963)
* chore: delete unused bookings hook

* refactor: group bookings hooks in folder

* refactor: rename useGetBooking, useGetBookings to useBooking, useBookings

* refactor: booking inputs and outputs

* chore: make bookings controller work with new inputs and outputs

* make examples app work

* refactor: deprecate fields instead of removing them

* readd eventtypeid

* swagger regenerate

* make recurring booking backwards compatible

* fix test

* update changelog

* swagger update

* fix import

* chore: update lock file
2024-10-08 14:05:28 +02:00
Alex van Andel d99f171597 perf: Only render the TimezoneChangeDialog when needed (#16986)
* perf: Only render the TimezoneChangeDialog when needed

* fix: Import error

* Minor style fixes
2024-10-08 10:41:53 +01:00
Syed Ali ShahbazandKeith Williams da55306a5a chore: add dev docs on mintlify (#16935)
* --init

* progress...

* add more docs

* bunch of changes and added back platform

* development guides added

* more guides in develop with cal

* self hosted WIP

* deployments

* fix deployment steps

* self-hosted guides

* ..

* Removed the development only sections

* Removed 'with Cal.com'

* use steps component for steps

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-10-08 02:32:16 -03:00
Benny Joo 66378160df chore: remove log (#16981) 2024-10-07 22:10:25 +00:00
Anik Dhabal Babu 8aee8d9d3b fix: SMS reminders are being sent out with an HTML code (#16966) 2024-10-07 17:51:04 -04:00
Calcom BotandReplexica 79e33a4d26 feat: update translations (#16972)
Co-authored-by: Replexica <support@replexica.com>
2024-10-07 15:37:32 -03:00
Carina WollendorferandCarinaWolli b5fa43f086 feat: checkbox to count managed events for team-wide limits (#16923)
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2024-10-07 11:36:50 -04:00
Joe Au-Yeung 0d757039f7 chore: Fixing ICS file in workflows & ICS calendar descriptions [CAL-4409] (#16731)
* Remove title and subtitle from ICS calendar description

* Remove unused method

* Use generateIcsString function for workflows

* Type fixes

* Refactor typing of CalEventParser

* WIP

* Type fixes

* Fix test

* Fix tests

* type fixes

* Remove duplicate code before `scheduleEmailReminder`
2024-10-07 10:50:50 -04:00
Lauris Skraucis 44f6f2e320 refactor: v2 throttler guard (#16922)
* chore: add logs

* refactor: replace deprecated redis.setex with redis.set

* chore: log response headers
2024-10-07 11:02:41 +00:00
Benny Joo d8eb1df61d fix: add suppressHydrationWarning to app router layout (#16960) 2024-10-07 12:40:09 +02:00
Lauris Skraucis ef7cac6c50 fix: booker atom phone booking field (#16945)
* fix: booker atom phone booking field

* chore: show usual booker in examples app

* refactor: import styles file manually
2024-10-07 12:39:54 +02:00
Benny Joo 21dd44733f fix: make theme logic safe and add better e2e tests (#16959)
* fix: improve theme logic

* remove null from ThemeLabelProps value

* add better e2e tests
2024-10-07 11:23:30 +01:00
Lauris Skraucis b0bfec7247 feat: Booker atom read only fields (#16904)
* refactor: include user-readonly in BookingFields

* feat: add read only name and email booking fields

* feat: Booker atom prop for read only name and email

* refactor: simplify props type
2024-10-07 15:03:07 +05:30
Lauris Skraucis ba5b9e951a feat: Booker atom enable hiding event details (#16906)
* refactor: Booker component hideEventTypeDetails hides sidebar

* feat: Booker atom hideEventTypeDetails prop

* fix: redundant border appearing if event details hidden

* Revert "fix: redundant border appearing if event details hidden"

This reverts commit 63122a906a8e41b54074387e1a6a4f0e4489a8a9.

* fix: border
2024-10-07 09:52:47 +02:00
Lauris Skraucis 5e3865b645 docs: v2 mintlify update (#16961) 2024-10-07 06:54:36 +00:00
Rajiv Sahal a02240b579 fix: add missing ApiOperation tag v2 (#16947)
* add missing api operation tag

* update openapi spec for docs
2024-10-06 20:04:25 -03:00
Benny Joo 376caa412d fix: DOM attribute warning in event-types edit page (#16953) 2024-10-05 03:39:11 +00:00
Benny Joo 8722745185 chore: improve readability of some tests (#16954) 2024-10-05 08:49:29 +05:30
+12 a4a3eb5ea9 refactor: Billing service (#15366)
* WIP: Billing service

* WIP

* Update __handler.ts

* Update index.ts

* WIP

* WIP

Signed-off-by: zomars <zomars@me.com>

* WIP

Signed-off-by: zomars <zomars@me.com>

* Update delete.handler.ts

* Update delete.handler.ts

* Update internal-team-billing.ts

* WIP

* Type fixes

Signed-off-by: zomars <zomars@me.com>

* WIP

Signed-off-by: zomars <zomars@me.com>

* Discard changes to apps/api/v2/src/ee/event-types/event-types_2024_04_15/controllers/event-types.controller.ts

* Discard changes to packages/app-store/skype/config.json

* style: update text area (#15934)

* chore: update text-editor input

* chore: update text-editor input

* final update

* Update Editor.tsx

---------

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

* fix: #15697 Assignment warning modal poping up ,even when hosts are added . (#15699)

* removed reduntand check on assignedusers

* update for managed eventtype

* formatted

* comments

* Updated comments

* extracted checkForEmptyAssignment and added tests

* updated comments

* updated to show dialog also when not yet saved

* update translations

* updated comments

* updated translation

* updated types

* chore: update naming and comments

* Delete apps/web/lib/checkForEmptyAssignment.ts

deleted since file was renamed

* Delete apps/web/test/lib/checkForEmptyAssignment.test.ts

deleted as the file is renamed to be more descriptive

* update to do teamcheck before

* chore: revert name to CheckForEmptyAssignment

* updated check conditions

* updated useEffect dependencies

---------

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

* fix: getting an error when a team member tries to leave (#15925)

a team

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

* feat: add transitions to more components (#15916)

* add transitions to more components

* chore: Remove duplicate class

* fix: Change minimum number of teams required for org self-serve (#15955)

* fix: Change minimum number of teams required for org self-serve

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* refactor: Use a new constant for displaying org helper text dialogue

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* Update packages/lib/constants.ts

* Update turbo.json

---------

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>

* feat: pwa ready and add shortcut for quick access (#15957)

* chore: Update site.webmanifest with additional display properties

* chore: Update site.webmanifest with additional display properties

* Update apps/web/public/site.webmanifest

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>

* i18n: update translations for "by proceeding, ..." (#15921)

* feat: Add title attribute to iframe in embed.ts (#15944)

* feat: Add title attribute to iframe in embed.ts

* Update packages/embeds/embed-core/src/embed.ts

---------

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

* fix: Assignment reminder modal appears when deleting a team event type (#15544)

* fix: Assignment reminder modal appears when deleting a team event type

* update

* Update EventTypeSingleLayout.tsx

* Update event-types-single-view.tsx

* update

* Early return https://handbook.cal.com/engineering/best-practices/prefer-early-returns

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Hariom <hariombalhara@gmail.com>

* fix: Add CORP and COEP headers to embedded pages (#15275)

* Add CORP headers

* Improve test

* Add unit tests as well

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>

* feat: No-show bookings - do not count towards a member's round robin assignment (#15323)

* feat: No-show bookings - do not count towards a member's round robin assignment

* filter no show organizer

* remove logs

* fix: filter bookings where host attendee is no show

* fix: use not condition for noShow

* chore: test

* add default false for noShowHost

* Revert "chore: test"

This reverts commit c914a8fc4a14ca9c7d8c4a08ff8b0f463789171c.

* chore: integration test

* fix: noShowHost not working for null

* Update packages/lib/server/getLuckyUser.ts

* chore: update test description

---------

Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: gh0st91848 <gh0st91848@gmail.com>
Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>

* refactor: v1 orgs unlimited teams (#15908)

* refactor: v1 orgs unlimited teams

* fix: response message ownerId

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>

* fix: refresh connect atoms on token change (#15933)

* added dropdown

* change comment

* fix: added types

---------

Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>

* fix: Next.js bundle analysis (#15903)

* fix: Next.js bundle analysis

* Added the main checkout back

* fix: type in webhook payload (#15912)

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

* fix: auto accept (#15975)

* fix: auto accept

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

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

---------

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

* fix: Broken GitHub workflows (#15979)

* test: Delete credential endpoint (#15322)

* Init

* Add mock trpc context

* Intro mockDatabaseClient

* Introduce mockDatabaseClient class

* Add delete video app test

* Add calendar test

* Remove unused func from bookingScenario

* Remove console.log

* Add app repository

* Add createMany method to event type repository

* Remove instance of MockDatabaseClient from video test

* Add destination calendar repository

* Remove instances of MockDatabaseClient

* abstract logic to own handler

* Remove dev dependency

* Clean up

* Type fix

* Pull yarn.lock from main

---------

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

* fix: #15967 Show better error when wrong variable is used in custom event name (#15974)

* update to show exact err msg with custom event name

* updated tests for validateCustomEventName

---------

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

* WIP

Signed-off-by: zomars <zomars@me.com>

* Update yarn.lock

* Update publish.handler.ts

* Update internal-team-billing.test.ts

* rename create to init

* remove sync services

* wip tests for delete team

* wip tets

* wip tests

* tests/internal-test

* remove return that is inaccessable

* remove team calls to use repository

* remove redudant file

* update team repo

* add stripe mocks and test

* fix constants

* tests to main stripe handler

* remove logs

* fix constants

* Update packages/features/ee/billing/api/webhook/_customer.subscription.deleted.team-plan.ts

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

* move workflow logic to a service

* use static method > creating new class

* fix: remove http code deep in repo + tests

* Feedback

* Update index.ts

* Type fix

* Lazy load fixes

---------

Signed-off-by: zomars <zomars@me.com>
Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>
Co-authored-by: Rohan Advani <122167726+RNAdvani@users.noreply.github.com>
Co-authored-by: unknown <adhabal2002@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: Vijay <vijayraghav22@gmail.com>
Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com>
Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com>
Co-authored-by: Hichem Fantar <hichemfantar2049@gmail.com>
Co-authored-by: Souptik Datta <souptikdatta2001@gmail.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Johannes Maendle <141119154+jomaendle2@users.noreply.github.com>
Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: gh0st91848 <gh0st91848@gmail.com>
Co-authored-by: Lauris Skraucis <lauris.skraucis@gmail.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
Co-authored-by: sean-brydon <sean@cal.com>
Co-authored-by: sean <sean@brydon.io>
2024-10-04 13:44:50 -07:00
Benny Joo b560475d89 fix: flaky one in local e2e test (#16949) 2024-10-04 20:36:52 +00:00
Calcom BotandReplexica 4872daef60 feat: update translations (#16943)
Co-authored-by: Replexica <support@replexica.com>
2024-10-04 20:15:18 +00:00
Anik Dhabal Babu dfa92f5cb6 fix: currency conversion error for paypal (#16917)
* fix: currency conversion error for paypal

* type-error
2024-10-05 01:11:09 +05:30
Benny Joo babb1a3bf7 fix annoying warning due to key spread (#16948) 2024-10-04 19:39:20 +00:00
Benny Joo 7b5a2726ab fix: translations for insights, routing-forms, apps store, etc (#16933)
* remove outdated translations for insights

* use i18n strings for insights

* use i18n strings for routing forms

* use i18n strings for apps store

* fix more pages

* refactor

* fix
2024-10-04 09:45:51 -03:00
sean-brydon 7d4653296e add trial days to stripe teams checkout (#16940) 2024-10-04 12:42:51 +00:00
Hariom Balhara 644fb38f87 test: more Embed Page Params filtering tests (#16937)
* Add rescheduleUid as config param scenario

* Restructure test buttons

* Use correct namespace as per rename
2024-10-04 12:01:59 +01:00
Ash Davis 743b155a88 fix: rescheduledBy to carry into success url redirect (#16931) 2024-10-04 10:59:52 +01:00
Benny JooandAlex van Andel 664a92a1d0 remove pages router and use app router (#16793)
Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-10-04 10:28:21 +01:00
Hariom Balhara 8ae71f6160 fix: Certain query params being filtered out from embed (#16936) 2024-10-04 12:59:45 +05:30
Omar López ab1eab9c54 chore: v4.5.9 (#16926)
release.yml / release (push) Canceled after 0s
2024-10-03 12:26:35 -07:00
MuhammadandAnik Dhabal Babu a64b7752c9 fix: Tooltip must be used within TooltipProvider (#16918)
* fixes #16833

* Update index.tsx

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2024-10-03 15:37:11 +00:00
Keith WilliamsandSyed Ali Shahbaz be728e9c01 feat: add Mintlify docs (#16787)
* feat: Add Mintlify docs

* Fixed the mint.json for v2

* Fixed versioning issue

* Add titles to ICS feed endpoints

* Added errors to v1

* Added rate-limit to API v1

* feat: added v1-v2 differences and v1 auth

* Trying to eliminate reasons for v1 not showing on publication

* Used the swagger openapi validator

* remove deprecated v1 endpoints

* Moved api docs into new folders without api-reference

* Renamed api to api-reference

* removed the versioning

* Got rid of anchor warnings

* Fixed naming

* Just as a test - using the same v2 openapi spec for v1 reference

* Removed 'externalDocs' from v1

* Removed securitySchemes

* Updated the diff between v1/v2

* Added v1 in front of /attendees to test

* Moved paths up and removed externalDocs

* Testing - Added content to the response

* Reduced paths to 1

* Testing: anything at this point

* Fixed validation

* Moved the other .mdx files to see if that's disrupting something

* Trying with a tab

* Empty tags array

* Added back servers field

* Removed all other schemas

* Removed v1 for now

* Added platform docs

* Language fixes

* Added v1 back

* add API V1 response for attendees

* remove unnecessary endpoint docs in API V1

* Removing platform and API for now

* Updated v2 openapi doc

---------

Co-authored-by: Syed Ali Shahbaz <alishahbaz7@gmail.com>
2024-10-03 15:26:01 +04:00
Benny Joo 2146c04444 fix: i18n for app router (#16909)
* fix: translations for app router

* fix build error
2024-10-03 00:32:33 +01:00
Calcom BotandReplexica 0b94473c7f feat: update translations (#16911)
Co-authored-by: Replexica <support@replexica.com>
2024-10-02 17:44:36 -04:00
2a1dc619ee feat: Multiple Private links per Event Type (#15896)
* feat: Change hashedLink field to array

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* feat: Implement core single-use links logic

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Get private link from list of hashedLinks on event list page

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix defalut single-use links form field value

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix some type errors while compiling

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Use onChange callback instead of setting form values directly

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* feat: Add e2e tests for single-use links

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* refactor: Refactor single-use-links admin interface

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix settings toggle bugs

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* chore: Remove redundant inline comments

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Remove debug statements

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* chore: Remove single-use links e2e tests

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* feat: Remove private-link feature and override with single-use-links

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix type errors

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* refactor: Remove redundant migrations

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Add managedEvents restriction

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix single-use-links for org

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix recommended UI changes

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix duration not respected for private links

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix team event page title

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* feat: Add logic to copy each single-use-links from event listing page

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* feat: Add single-use links support for managed event types

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix some type errors

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix type errors

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* refactor: Disable adding new single-use links when field is locked

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Address feedbacks

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* refactor: Hide add new link button for locked single-use link field

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* chore: Use empty string for single-use link fallback value condition

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix org single-use links in listing page

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* feat: Auto toggle unlock button for managed event's single-use links option

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* Revert "feat: Auto toggle unlock button for managed event's single-use links option"

This reverts commit 5a2ed6f0bf428d52de153335499f02f42ccdf18f.

* chore: Disable parent toggle for single-use-links

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* feat: Remove tooltip and give info message below field

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* add tooltip

* tooltip message

* fix: Fix typo

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix typescript type errors

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* fix: Fix few unit tests

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* refactor: Remove redundant query

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

* merge conflict fix

* More merge conflict fix and refactor

* fix tests, code refactor

* fix: type check

* fix: duration config and keep links when updating event type

* fix: e2e

* refactor: Replace single-use-links with multiple-private-links

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>

---------

Signed-off-by: Souptik Datta <souptikdatta2001@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: Amit91848 <samit91848@gmail.com>
2024-10-03 00:58:54 +05:30
Benny JooandKeith Williams 48a2fc2f67 fix: translations for sidebar (#16910)
* fix: translations for sidebar

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

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-10-02 18:21:25 +00:00
4553455098 chore: refactor shell to individual files (#16893)
* banners

* useAuthHooks

* fixes to redirect and banner

* extract useIntercom to custom hook

* use app theme

* extract user-dropdown to new component

* Navigation Item

* navigation and profile dropdown

* Fix import

* navigation and sidebar

* fix type errors

* fix banners being an async call

* fix types

* fix banner prop type

* fix mobile nav item import

* fix banner types

* (revert) layout banner render method to fix type error

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
2024-10-02 15:35:56 +01:00
b4f1b5aebe refactor: handleNewBooking #4 (#15673)
* refactor: handleNewBooking #3

* refactor: create booking factor

* refactor: handleNewBooking

* refactor: seats and rescheduleUId

* chore: remove comment

* fix: type err

* chore: add missing statement

* chore: use less params and other improvements

* chore: name

* chore: improvement

* fix: type err

* Typo fix

* chore: fix type err

* refactor: more readable

* refactor: improve code

* fix: conflicts

---------

Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>
2024-10-02 10:26:25 -04:00
a99e285d76 fix: fix ui overflow on phone for calendar settings (#16661)
* fix: fix ui overflow on phone for calendar settings

* fix: overflow issue with long emails

* Update CalendarSwitch.tsx

---------

Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2024-10-02 12:24:25 +00:00
Lauris Skraucis bdea436f8b docs: v2 refresh tokens and slots endpoints swagger (#16788)
* docs: oauth refresh endpoint

* docs: slots reserve and delete

* docs: get slots

* swagger

* fix: reserving slot

* Revert "fix: reserving slot"

This reverts commit 8a3ce8464d5dbf67e58da6d3b1aeb51df97240cb.

* Update oauth-flow.controller.ts
2024-10-02 08:44:05 +00:00
Alex van Andel 182d0fa228 fix: Better defaulting to NEXT_PUBLIC_LOGGER_LEVEL=4 (#16900)
* fix: Better defaulting to NEXT_PUBLIC_LOGGER_LEVEL=4

* chore: Minor fixes to prettyLogTemplate (as it wasnt very pretty)
2024-10-01 17:38:02 +00:00
Alex van Andel 0d7f560c43 chore: improve instrumentation deps (#16899)
* Remove Sentry from direct import in instrumentation file

* chore: Exclude Sentry configs when not needed
2024-10-01 17:52:13 +01:00
Alex van Andel 1377f1a214 chore: Release v4.5.8 (#16896)
release.yml / release (push) Canceled after 0s
2024-10-01 15:38:59 +01:00
Lauris Skraucis e8dfa50119 fix: booker atom recurring event (#16719)
* fix: BookerEmbed prop type

* fix: booker atom not displaying recurring event

* fix: count interpolation in i18n
2024-10-01 14:00:04 +00:00
706e8e4c1f feat: added workflows to all actions (#16691)
* feat: added workflows

* moved the condition from Editor to excludedToolbarItems

* revert editor changes

* Update WorkflowStepContainer.tsx

* update

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: unknown <adhabal2002@gmail.com>
2024-10-01 18:50:17 +05:30
Alex van Andel a95729f4a1 chore: Couple fixes to improve error reporting (#16895)
* chore: Couple fixes to improve error reporting

* tweak: Fix error message

* refactor: Use findUniqueOrThrow instead of guard

* fix: Broken test, missing ID - suspect it passes because only one record exists

* chore: Minor refactor to split ZodEffect from ZodType

* fix: Satify typescript
2024-10-01 09:18:51 -03:00
Lauris Skraucis 4b6a389212 feat: v2 rate limiting (#16882)
* refactor: pass redis storage to throttler guard

* chore: upgrade throttler to latest

* feat: ApiKey RateLimit table

* chore: upgrade redis storage throttler

* feat: rate limit by api key

* refactor: on delete api key cascade rate limit

* fix: permissions guard work with oauth credentials

* chore: set rate limit in env

* tests: throttler

* feat: include rate limit name in response

* fix: correctly handle multiple rate limits

* chore: remove unused import

* delete migrations

* chore: prisma migration

* doc

* dummy

* fix: permissions guard unit test

* refactor: remove route specific @Throttles

* fix: permissions guard
2024-10-01 12:01:56 +00:00
Morgan 9d3be8de03 chore: improve event-type atom desc, data fetch (#16890) 2024-10-01 10:38:37 +00:00
Benny Joo b283f1f8cd fix: theme is not configured in app router (#16889)
* fix: theme is not configured in app router

* fix type error

* remove logs

* use testBothFutureAndLegacyRoutes

* add APP_ROUTER_SETTINGS_MY_ACCOUNT_ENABLED
2024-10-01 04:39:37 -04:00
5ff52e1239 chore: add saml signup test / improve signup e2e test (#16849)
* add comment to signup-view

* add a basic test for saml button in signup

* add a test for cookie consent checkbox

* refactor and remove duplicates

* rename data-testid for saml button

* add test for saml

* remove code not needed

* better naming

* improve

* address code nit

* skip saml test when needed

* fix flag

* improve

* improve more

* refactor

* refactor

* refactor

* fix and add 1 more test

* remove tag

* remove unneeded code

* fix

* fix test

* it needs to be parallel mode

* reduce code

* simplify

* fix

* fix flake

* fix another flake

* add comments + refactor

---------

Co-authored-by: unknown <adhabal2002@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2024-10-01 09:34:20 +01:00
Calcom BotandReplexica 2b1cb9f878 feat: update translations (#16886)
Co-authored-by: Replexica <support@replexica.com>
2024-10-01 06:23:01 +00:00
Benny Joo 74a46e8ba3 chore: (1) settings/security - remove pages router and use app router (#16795)
* remove pages router and use app router

* add settings layout

* remove env vars
2024-09-30 23:27:58 +01:00
Jevtić NenadandRajiv Sahal 5b5f7c1c48 fix: Fix conditional check for oAuth client id (#16809)
Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
2024-09-30 18:56:17 -03:00
Udit Takkar 9375efffe3 feat: prevent sending multiple instant meeting request (#16881) 2024-09-30 18:54:55 -03:00
sean-brydon da59c9de12 fix getEventTypeWorkflows (#16879) 2024-09-30 22:09:18 +01:00
2a734faf45 fix: undefined in meeting url workflow variable (#16771)
* make bookerUrl mandatory

* add missing bookerUrl

* add fallback

* fix roundRObinReassignment

* clean up

* allow bookerUrl to be undefined

* code clean up

* make bookerUrl mandatory

* fix type errors

* fix type error

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
2024-09-30 15:25:51 -04:00
Calcom BotandReplexica 934cefecce feat: update translations (#16884)
Co-authored-by: Replexica <support@replexica.com>
2024-09-30 15:18:41 +00:00
Rajiv SahalandMorgan c88811aeee feat: stripe connect atom (#16190)
* update stripe service

* init endpoints for stripe connect atom

* update stripe controller

* update stripe service

* add generic function to create app credential

* update stripe controller

* update stripe service

* add handler to construct redirectUrl

* restructure files for better readibility

* better naming

* replace STRIPE_PRIVATE_KEY with STRIPE_API_KEY

* fix naming

* remove unused query param

* frontend for stripe connect atom

* custom hooks for stripe connect atom

* abstract response schema into separate file

* fixup

* input dto for stripe controller

* update stripe module

* update endpoints module to include stripe module

* updatte stripe module

* fixups and add check endpoint to stripe controller

* add method to check stripe account

* add helper fn to get on error return value

* update stripe connect atom

* custom hook to check user stripe credentials

* add stripe connect to atom exports

* update stripe connect styling

* add qs stringify package

* translations for stripe connect atom

* updaet typing

* update output dtos for stripe endpoints

* add error message

* fix merge conflicts

* add stripe connect atom to atom exports

* add query param for error rediect link

* add handler for onCheck success and error redirect link

* update index value

* fix merge conflicts

* fixup

* resolve merge conflicts

* war with merge conflicts

* update examples app

---------

Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2024-09-30 19:56:22 +05:30
Rajiv Sahal f46c3c65fb filter connected calendars before displaying it in tooltip (#16883) 2024-09-30 19:45:28 +05:30
Rajiv Sahal 1d203dc566 feat: frontend to handle multiple calendars for connect atoms (#16527)
* handle multiple calendars in connect atoms

* resolve merge conflicts

* fixup

* frontend for multiple calendars

* fixup

* remove comment

* add missing props

* add prop for multi calendar view

* add multi calendar support

* fixup
2024-09-30 11:33:18 +00:00
Rajiv Sahal 26a1c749f7 chore: refactor billing service v2 (#16805) 2024-09-30 13:56:21 +03:00
MorganandSomay Chauhan ad347cb59f feat: Event Type Atom base pr (#16831)
* feat: Event Type Atom base pr

* fixup! Merge branch 'main' into chore-event-type-atom-platform-wrapper-base-pr

* Update EventTypeWebWrapper.tsx

---------

Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com>
2024-09-30 13:44:11 +03:00
Udit TakkarandSyed Ali Shahbaz ac300ff670 refactor: enable infinite scrolling for all (#16463)
* refactor: enable infinite scrolling for all

* chore: remove unused code

* fix: tests

* chore: type err

* chore: update email embed test

* chore: update tests

* chore: update tests

* chore: fix horizontal tabitem

* chore

* fix: conflicts

* chore: conflict

* fix: E2E tests

* chore: remove idle

* fix test

---------

Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>
2024-09-30 10:44:04 +01:00
c834b927b6 refactor: event advanced web wrapper (#16711)
* chore: EventTypeWebWrapper base pr

* fixup! chore: EventTypeWebWrapper base pr

* fixup! Merge branch 'main' into morgan/cal-4183-eventtypeatom-web-wrapper-base

* wip

* fix: error

* Event type atom wrapper handles app dir

* fixup! Merge branch 'main' into morgan/cal-4183-eventtypeatom-web-wrapper-base

* fixup! fixup! Merge branch 'main' into morgan/cal-4183-eventtypeatom-web-wrapper-base

* remove console log

* review comments

* fixup! review comments

* refactor: event advanced web wrapper

* rename `connectedCalendars` -> `calendarsQueryData`

* Update BookerLayoutSelector.tsx

* moved useMeQuery up the parent tree

---------

Co-authored-by: Morgan Vernay <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2024-09-30 12:15:11 +03:00
Somay Chauhan 34ba27407b refactor: event availability web wrapper (#16808)
* refactor: event availability web wrapper

* useMeQuery moved up the parent component
2024-09-30 08:16:18 +00:00
Somay Chauhan 8431cd2ef8 refactor: event recurring web wrapper (#16764) 2024-09-30 08:11:13 +00:00
Benny Joo cd09a56491 fix hydration error from html mismatch (#16876) 2024-09-30 06:04:27 +05:30
Calcom BotandReplexica 5c05a422a8 feat: update translations (#16851)
Co-authored-by: Replexica <support@replexica.com>
2024-09-28 22:42:30 +00:00
Benny Joo e805c0f00a fix spacing in signup (#16850) 2024-09-27 18:43:30 +00:00
Priyansh 2fa7f7931d Fix TODO in AppCard.tsx (#16863) 2024-09-27 17:51:19 +00:00
sean-brydon 20729b3a4e chore: Move getRemindersFromRemovedTeams and deleteAllWorkflowReminders to workflow repo (#16861)
* wip

* move deleteAllWorkflowReminders to repo
2024-09-27 10:42:09 -04:00
Lauris Skraucis 4d9777af8b docs: v2 event-types (#16854)
* docs: optional get event-types query params

* docs: create event type input

* docs: update event type input

* docs: child inputs of create and update event type inputs

* docs: updated swagger

* refactor: add disabled option to booking window

* refactor: seats description

* swagger
2024-09-27 09:48:22 +00:00
Hariom Balhara 1534588b34 feat: Forward all the page params to embed (#16330)
* Forward all query params

* Add Unit tests

* Add example in playground
2024-09-27 15:14:56 +05:30
Morgan 7183ec7f1b fix: add teamId to platform urls (#16852) 2024-09-27 09:19:20 +03:00
Hariom BalharaandPeer Richelsen d836497d56 fix: Don't AutoScroll to embed when multiple-duration event's booking page is embedded (#16411)
* Fix and add test and eslint rule

* Fix eslint errors

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2024-09-27 09:57:04 +05:30
Syed Ali ShahbazandUdit Takkar 38fa0fae1d fix: insights UI/UX (#16610)
* remove old code remnant

* -

* WIP

* type change

* --

* typefix

* fix type

* fix type

* change type name

* add basewhere to eventsByStatus

* add basewhere to the rest

* fix rendering null popular event list item

* URL params for start and endtime to have YYYY-MM-DD format

* remove console log

* resolve suggestion

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-09-27 03:36:32 +00:00
Mohit 2872b263fd fix: <a href> is not clickable cause of z-index (#16842) 2024-09-27 02:38:31 +00:00
Keith Williams 92e53adc8e chore: v4.5.7 (#16848)
release.yml / release (push) Canceled after 0s
2024-09-27 08:19:58 +09:00
Calcom BotandReplexica 72cc4ab13e feat: update translations (#16843)
Co-authored-by: Replexica <support@replexica.com>
2024-09-26 22:41:09 +00:00
4e82ffe2ad feat: adding Bolna Voice AI integration for cal.com (#16828)
* fix: #11213, #11215

* Use default colour

* adding bolna app for cal.com

* cleanup by removing redundant changes

---------

Co-authored-by: Siddharth Movaliya <siddraj1992@gmail.com>
Co-authored-by: Sean Brydon <sean@cal.com>
2024-09-26 21:20:28 +00:00
Benny Joo 90f6c7e239 feat: New UI for SignUp / Login (#16802) 2024-09-26 15:27:56 -04:00
Keith Williams ffa58d1cdb chore: v4.5.6 (#16837)
release.yml / release (push) Canceled after 0s
2024-09-27 03:00:13 +09:00
Calcom BotandReplexica f834e93652 feat: update translations (#16839)
Co-authored-by: Replexica <support@replexica.com>
2024-09-26 17:59:54 +00:00
ae7fae7da4 feat: Add hideCalendarEventDetails option to event types (#16817)
* Add `hideCalendarEventDetails` to DB

Co-authored-by: Alex van Andel <emrysal@users.noreply.github.com>

* Add option to hide calendar event details

* Pass `hideCalendarEventDetails` to event object

* Add to API

* Add to CalendarEvent class

* Pass `hideCalendarEventDetails` to calendar services

* Adjust test

* fix: move `hideCalendarEventDetails` to `api/v2/event-types_2024_06_14` and remove from older versions

- Added `hideCalendarEventDetails` to `api/v2/event-types_2024_06_14`
- Removed `hideCalendarEventDetails` from `api/v1` and `api/v2/event-types_2024_04_15`

* fix: calEventRaw is undefined (use event instead)

* chore: Remove debug artifact

* fix: description id + update to copy

* fix: Attempt at fixing type error

* Add hideCalendarEventDetails to test builder

---------

Co-authored-by: Alex van Andel <emrysal@users.noreply.github.com>
Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-09-26 17:08:25 +00:00
Keith Williams b6c6e41603 chore: Allow redirecting /docs to external docs solution (#16836)
* chore: Allow redirecting /docs to external docs solution

* Added DOCS_URL to .env.example
2024-09-26 16:35:35 +00:00
Lauris Skraucis e4dc2d0877 fix: platform cancel booking webhook not triggered (#16827)
* fix: pass oauth id to webhooks upon cancel booking

* chore: v2 use latest libraries
2024-09-26 14:49:53 +00:00
Lauris Skraucis e43690f190 chore: bump slots rate limit (#16826) 2024-09-26 13:54:12 +00:00
Lauris Skraucis 5bbccad41d fix: selected calendars atom deselect calendar (#16825) 2024-09-26 08:26:33 +00:00
Calcom BotandReplexica bc53037f37 feat: update translations (#16813)
Co-authored-by: Replexica <support@replexica.com>
2024-09-25 23:23:31 +00:00
Nick Holden b4a1a8e7bf chore: Replace campsite.co with campsite.com (#16819) 2024-09-25 18:41:07 +00:00
Keith Williams ac43d90d53 feat: Improve API v2 docs (#16818)
* feat: Improve API v2 docs

* Consistency

* Made the descriptions complete sentences with period

* Update apps/api/v2/src/ee/schedules/schedules_2024_06_11/controllers/schedules.controller.ts
2024-09-25 18:09:53 +00:00
Anik Dhabal Babu 2b24b4472d fix: OOO issue with setting the start and end dates to the same (#16810) 2024-09-25 13:44:42 +00:00
Peer Richelsen 715cbc1c38 chore: small changes to license page (#16812) 2024-09-25 15:14:38 +02:00
Alex van Andel d670976a69 chore: Release v4.5.5 (#16804)
release.yml / release (push) Canceled after 0s
2024-09-24 21:35:29 +00:00
Benny Joo 17ff01af75 fix: Revert "feat: Update UI of signup / login pages (#16710)" (#16801)
* Revert "feat: Update UI of signup / login pages (#16710)"

This reverts commit b879aeef09.

* revert
2024-09-24 20:07:37 +00:00
Alex van Andel 77af36e2af bugfix: Failed foreign key constraint check due to daily_video 0 (#16798) 2024-09-24 19:15:04 +00:00
1076 changed files with 55489 additions and 9989 deletions
+2 -2
View File
@@ -168,13 +168,13 @@ NEXT_PUBLIC_STRIPE_PREMIUM_PLAN_PRICE=
NEXT_PUBLIC_IS_PREMIUM_NEW_PLAN=0
NEXT_PUBLIC_STRIPE_PREMIUM_NEW_PLAN_PRICE=
STRIPE_TEAM_MONTHLY_PRICE_ID=
STRIPE_TEAM_PRODUCT_ID=
STRIPE_ORG_MONTHLY_PRICE_ID=
STRIPE_WEBHOOK_SECRET=
STRIPE_WEBHOOK_SECRET_APPS=
STRIPE_PRIVATE_KEY=
STRIPE_CLIENT_ID=
# Use for internal Public API Keys and optional
API_KEY_PREFIX=cal_
# ***********************************************************************************************************
@@ -334,8 +334,8 @@ AB_TEST_BUCKET_PROBABILITY=50
# whether we redirect to the future/event-types from event-types or not
APP_ROUTER_EVENT_TYPES_ENABLED=0
APP_ROUTER_SETTINGS_DEVELOPER_ENABLED=0
APP_ROUTER_SETTINGS_SECURITY_ENABLED=0
APP_ROUTER_SETTINGS_ADMIN_ENABLED=0
APP_ROUTER_SETTINGS_MY_ACCOUNT_ENABLED=0
APP_ROUTER_SETTINGS_PLATFORM_ENABLED=0
APP_ROUTER_SETTINGS_ORG_ENABLED=0
APP_ROUTER_APPS_INSTALLED_CATEGORY_ENABLED=0
+1 -1
View File
@@ -12,7 +12,7 @@
## Mandatory Tasks (DO NOT REMOVE)
- [ ] I have self-reviewed the code (A decent size PR without self-review might be rejected).
- [ ] I have added a Docs issue [here](https://github.com/calcom/docs/issues/new) if this PR makes changes that would require a [documentation change](https://docs.cal.com/docs). If N/A, write N/A here and check the checkbox.
- [ ] I have updated the developer docs in /docs if this PR makes changes that would require a [documentation change](https://cal.com/docs). If N/A, write N/A here and check the checkbox.
- [ ] I confirm automated tests are in place that prove my fix is effective or that my feature works.
## How should this be tested?
+41
View File
@@ -0,0 +1,41 @@
# This is just to test this file
name: Build
on:
workflow_call:
jobs:
build:
name: Build Docs
permissions:
contents: read
runs-on: buildjet-2vcpu-ubuntu-2204
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/dangerous-git-checkout
- name: Cache Docs build
uses: buildjet/cache@v4
id: cache-docs-build
env:
cache-name: docs-build
key-1: ${{ hashFiles('yarn.lock') }}
key-2: ${{ hashFiles('docs/**.*', '!**/node_modules') }}
key-3: ${{ github.event.pull_request.number || github.ref }}
key-4: ${{ github.sha }}
with:
path: |
**/docs/**
key: ${{ runner.os }}-${{ env.cache-name }}-${{ env.key-1 }}-${{ env.key-2 }}-${{ env.key-3 }}-${{ env.key-4 }}
- name: Run build
working-directory: docs
run: |
export NODE_OPTIONS="--max_old_space_size=8192"
if [ ${{ steps.cache-docs-build.outputs.cache-hit }} == 'true' ]; then
echo "Cache hit for Docs build. Skipping build."
else
npm install -g mintlify
mintlify dev &
sleep 5 # Let it run for 5 seconds
kill $!
fi
shell: bash
+9 -1
View File
@@ -33,7 +33,7 @@ jobs:
with:
filters: |
has-files-requiring-all-checks:
- "!(**.md|.github/CODEOWNERS)"
- "!(**.md|.github/CODEOWNERS|docs/**|apps/web/public/static/locales/**/common.json)"
- name: Get Latest Commit SHA
id: get_sha
run: |
@@ -139,6 +139,13 @@ jobs:
uses: ./.github/workflows/atoms-production-build.yml
secrets: inherit
build-docs:
name: Production builds
needs: [changes, check-label, deps]
if: ${{ needs.check-label.outputs.run-e2e == 'true' && needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
uses: ./.github/workflows/docs-build.yml
secrets: inherit
build:
name: Production builds
needs: [changes, check-label, deps]
@@ -225,6 +232,7 @@ jobs:
build-api-v1,
build-api-v2,
build-atoms,
build-docs,
e2e,
e2e-api-v2,
e2e-embed,
@@ -39,7 +39,7 @@ env:
jobs:
build:
name: Web App
name: Build Web App
runs-on: buildjet-4vcpu-ubuntu-2204
timeout-minutes: 30
steps:
+3 -2
View File
@@ -1,5 +1,6 @@
import { z } from "zod";
import { emailSchema } from "@calcom/lib/emailSchema";
import { _AttendeeModel as Attendee } from "@calcom/prisma/zod";
import { timeZone } from "~/lib/validations/shared/timeZone";
@@ -14,7 +15,7 @@ export const schemaAttendeeBaseBodyParams = Attendee.pick({
const schemaAttendeeCreateParams = z
.object({
bookingId: z.number().int(),
email: z.string().email(),
email: emailSchema,
name: z.string(),
timeZone: timeZone,
})
@@ -23,7 +24,7 @@ const schemaAttendeeCreateParams = z
const schemaAttendeeEditParams = z
.object({
name: z.string().optional(),
email: z.string().email().optional(),
email: emailSchema.optional(),
timeZone: timeZone.optional(),
})
.strict();
+1
View File
@@ -73,6 +73,7 @@ export const schemaBookingReadPublic = Booking.extend({
attendees: z
.array(
_AttendeeModel.pick({
id: true,
email: true,
name: true,
timeZone: true,
@@ -1,16 +1,18 @@
import { withValidation } from "next-validations";
import { z } from "zod";
import { emailSchema } from "@calcom/lib/emailSchema";
import { baseApiParams } from "./baseApiParams";
// Extracted out as utility function so can be reused
// at different endpoints that require this validation.
export const schemaQueryAttendeeEmail = baseApiParams.extend({
attendeeEmail: z.string().email(),
attendeeEmail: emailSchema,
});
export const schemaQuerySingleOrMultipleAttendeeEmails = z.object({
attendeeEmail: z.union([z.string().email(), z.array(z.string().email())]).optional(),
attendeeEmail: z.union([emailSchema, z.array(emailSchema)]).optional(),
});
export const withValidQueryAttendeeEmail = withValidation({
@@ -1,16 +1,18 @@
import { withValidation } from "next-validations";
import { z } from "zod";
import { emailSchema } from "@calcom/lib/emailSchema";
import { baseApiParams } from "./baseApiParams";
// Extracted out as utility function so can be reused
// at different endpoints that require this validation.
export const schemaQueryUserEmail = baseApiParams.extend({
email: z.string().email(),
email: emailSchema,
});
export const schemaQuerySingleOrMultipleUserEmails = z.object({
email: z.union([z.string().email(), z.array(z.string().email())]),
email: z.union([emailSchema, z.array(emailSchema)]),
});
export const withValidQueryUserEmail = withValidation({
+1
View File
@@ -11,6 +11,7 @@ export const schemaTeamBaseBodyParams = Team.omit({ id: true, createdAt: true })
smsLockState: true,
smsLockReviewedByAdmin: true,
bookingLimits: true,
includeManagedEventsInLimits: true,
});
const schemaTeamRequiredParams = z.object({
+3 -2
View File
@@ -1,5 +1,6 @@
import { z } from "zod";
import { emailSchema } from "@calcom/lib/emailSchema";
import { checkUsername } from "@calcom/lib/server/checkUsername";
import { _UserModel as User } from "@calcom/prisma/zod";
import { iso8601 } from "@calcom/prisma/zod-utils";
@@ -92,7 +93,7 @@ export const schemaUserBaseBodyParams = User.pick({
// Here we can both require or not (adding optional or nullish) and also rewrite validations for any value
// for example making weekStart only accept weekdays as input
const schemaUserEditParams = z.object({
email: z.string().email().toLowerCase(),
email: emailSchema.toLowerCase(),
username: usernameSchema,
weekStart: z.nativeEnum(weekdays).optional(),
brandColor: z.string().min(4).max(9).regex(/^#/).optional(),
@@ -115,7 +116,7 @@ const schemaUserEditParams = z.object({
// merging both BaseBodyParams with RequiredParams, and omiting whatever we want at the end.
const schemaUserCreateParams = z.object({
email: z.string().email().toLowerCase(),
email: emailSchema.toLowerCase(),
username: usernameSchema,
weekStart: z.nativeEnum(weekdays).optional(),
brandColor: z.string().min(4).max(9).regex(/^#/).optional(),
+1 -1
View File
@@ -33,7 +33,7 @@
"@sentry/nextjs": "^8.8.0",
"bcryptjs": "^2.4.3",
"memory-cache": "^0.2.0",
"next": "^13.5.4",
"next": "^13.5.6",
"next-api-middleware": "^1.0.1",
"next-axiom": "^0.17.0",
"next-swagger-doc": "^0.3.6",
@@ -2,7 +2,7 @@ import type { NextApiRequest } from "next";
import handleCancelBooking from "@calcom/features/bookings/lib/handleCancelBooking";
import { defaultResponder } from "@calcom/lib/server";
import { schemaBookingCancelParams } from "@calcom/prisma/zod-utils";
import { bookingCancelSchema } from "@calcom/prisma/zod-utils";
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
@@ -65,7 +65,7 @@ import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransform
*/
async function handler(req: NextApiRequest) {
const { id, allRemainingBookings, cancellationReason } = schemaQueryIdParseInt
.merge(schemaBookingCancelParams.pick({ allRemainingBookings: true, cancellationReason: true }))
.merge(bookingCancelSchema.pick({ allRemainingBookings: true, cancellationReason: true }))
.parse({
...req.query,
allRemainingBookings: req.query.allRemainingBookings === "true",
+2 -1
View File
@@ -26,4 +26,5 @@ WEB_APP_URL=http://localhost:3000/
CALCOM_LICENSE_KEY=
API_KEY_PREFIX=cal_
GET_LICENSE_KEY_URL="https://console.cal.com/api/license"
IS_E2E=false
IS_E2E=false
DOCS_URL=
+4 -3
View File
@@ -28,13 +28,14 @@
"dependencies": {
"@calcom/platform-constants": "*",
"@calcom/platform-enums": "*",
"@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.40",
"@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.46",
"@calcom/platform-libraries-0.0.2": "npm:@calcom/platform-libraries@0.0.2",
"@calcom/platform-types": "*",
"@calcom/platform-utils": "*",
"@calcom/prisma": "*",
"@golevelup/ts-jest": "^0.4.0",
"@microsoft/microsoft-graph-types-beta": "^0.42.0-preview",
"@nest-lab/throttler-storage-redis": "1.0.0",
"@nestjs/bull": "^10.1.1",
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.1.1",
@@ -43,7 +44,7 @@
"@nestjs/passport": "^10.0.2",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/swagger": "^7.3.0",
"@nestjs/throttler": "^5.1.2",
"@nestjs/throttler": "6.2.1",
"@sentry/node": "^8.8.0",
"body-parser": "^1.20.2",
"bull": "^4.12.4",
@@ -57,10 +58,10 @@
"ioredis": "^5.3.2",
"luxon": "^3.4.4",
"nest-winston": "^1.9.4",
"nestjs-throttler-storage-redis": "^0.4.1",
"next-auth": "^4.22.1",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"qs-stringify": "^1.2.1",
"querystring": "^0.2.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1",
-2
View File
@@ -3,8 +3,6 @@ import { Controller, Get, Version, VERSION_NEUTRAL } from "@nestjs/common";
import { ApiTags as DocsTags, ApiExcludeController as DocsExcludeController } from "@nestjs/swagger";
@Controller()
@DocsTags("Health - development only")
@DocsExcludeController(getEnv("NODE_ENV") === "production")
export class AppController {
@Get("health")
@Version(VERSION_NEUTRAL)
+373 -14
View File
@@ -1,26 +1,385 @@
import { AppModule } from "@/app.module";
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
import { CustomThrottlerGuard } from "@/lib/throttler-guard";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
import { INestApplication } from "@nestjs/common";
import { TestingModule } from "@nestjs/testing";
import { Test } from "@nestjs/testing";
import * as request from "supertest";
import { ApiKeysRepositoryFixture } from "test/fixtures/repository/api-keys.repository.fixture";
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
import { OrganizationRepositoryFixture } from "test/fixtures/repository/organization.repository.fixture";
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
import { RateLimitRepositoryFixture } from "test/fixtures/repository/rate-limit.repository.fixture";
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
describe("AppController (e2e)", () => {
let app: INestApplication;
import { X_CAL_CLIENT_ID, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
import { User, PlatformOAuthClient, Team, RateLimit } from "@calcom/prisma/client";
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
describe("AppController", () => {
describe("Rate limiting", () => {
let app: INestApplication;
let userRepositoryFixture: UserRepositoryFixture;
let apiKeysRepositoryFixture: ApiKeysRepositoryFixture;
let rateLimitRepositoryFixture: RateLimitRepositoryFixture;
const userEmail = "app-rate-limits-e2e@api.com";
let user: User;
app = moduleFixture.createNestApplication();
await app.init();
});
let organization: Team;
let oAuthClient: PlatformOAuthClient;
let organizationsRepositoryFixture: OrganizationRepositoryFixture;
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
let profilesRepositoryFixture: ProfileRepositoryFixture;
it("/ (GET)", () => {
return request(app.getHttpServer()).get("/health").expect("OK");
});
let apiKeyString: string;
afterAll(async () => {
await app.close();
let rateLimit: RateLimit;
let apiKeyStringWithRateLimit: string;
let apiKeyStringWithMultipleLimits: string;
let firstRateLimitWithMultipleLimits: RateLimit;
let secondRateLimitWithMultipleLimits: RateLimit;
const mockDefaultLimit = 5;
const mockDefaultTtl = 2500;
const mockDefaultBlockDuration = 5000;
beforeEach(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
imports: [AppModule, PrismaModule, UsersModule, TokensModule, SchedulesModule_2024_04_15],
}).compile();
jest.spyOn(CustomThrottlerGuard.prototype, "getDefaultLimit").mockReturnValue(mockDefaultLimit);
jest.spyOn(CustomThrottlerGuard.prototype, "getDefaultTtl").mockReturnValue(mockDefaultTtl);
jest
.spyOn(CustomThrottlerGuard.prototype, "getDefaultBlockDuration")
.mockReturnValue(mockDefaultBlockDuration);
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
user = await userRepositoryFixture.create({
email: userEmail,
username: userEmail,
});
apiKeysRepositoryFixture = new ApiKeysRepositoryFixture(moduleRef);
const { keyString } = await apiKeysRepositoryFixture.createApiKey(user.id, null);
apiKeyString = `cal_test_${keyString}`;
rateLimitRepositoryFixture = new RateLimitRepositoryFixture(moduleRef);
const { apiKey, keyString: keyStringWithRateLimit } = await apiKeysRepositoryFixture.createApiKey(
user.id,
null
);
apiKeyStringWithRateLimit = `cal_test_${keyStringWithRateLimit}`;
rateLimit = await rateLimitRepositoryFixture.createRateLimit("long", apiKey.id, 2000, 3, 4000);
const { apiKey: apiKeyWithMultipleLimits, keyString: keyStringWithMultipleLimits } =
await apiKeysRepositoryFixture.createApiKey(user.id, null);
apiKeyStringWithMultipleLimits = `cal_test_${keyStringWithMultipleLimits}`;
firstRateLimitWithMultipleLimits = await rateLimitRepositoryFixture.createRateLimit(
"short",
apiKeyWithMultipleLimits.id,
1000,
2,
2000
);
secondRateLimitWithMultipleLimits = await rateLimitRepositoryFixture.createRateLimit(
"long",
apiKeyWithMultipleLimits.id,
2000,
3,
4000
);
organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);
organization = await organizationsRepositoryFixture.create({ name: "ecorp" });
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
oAuthClient = await createOAuthClient(organization.id);
profilesRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
await profilesRepositoryFixture.create({
uid: "asd-asd",
username: userEmail,
user: { connect: { id: user.id } },
organization: { connect: { id: organization.id } },
});
app = moduleRef.createNestApplication();
await app.init();
});
async function createOAuthClient(organizationId: number) {
const data = {
logo: "logo-url",
name: "name",
redirectUris: ["http://localhost:5555"],
permissions: 1023,
};
const secret = "secret";
const client = await oauthClientRepositoryFixture.create(organizationId, data, secret);
return client;
}
it(
"api key with default rate limit - should enforce rate limits and reset after block duration",
async () => {
const limit = mockDefaultLimit;
const blockDuration = mockDefaultBlockDuration;
for (let i = 1; i <= limit; i++) {
const response = await request(app.getHttpServer())
.get("/v2/me")
.set({ Authorization: `Bearer ${apiKeyString}` })
.expect(200);
expect(response.headers["x-ratelimit-limit-default"]).toBe(limit.toString());
expect(response.headers["x-ratelimit-remaining-default"]).toBe((limit - i).toString());
expect(Number(response.headers["x-ratelimit-reset-default"])).toBeGreaterThan(0);
}
const blockedResponse = await request(app.getHttpServer())
.get("/v2/me")
.set("Authorization", `Bearer ${apiKeyString}`)
.expect(429);
expect(blockedResponse.headers["x-ratelimit-limit-default"]).toBe(limit.toString());
expect(blockedResponse.headers["x-ratelimit-remaining-default"]).toBe("0");
expect(Number(blockedResponse.headers["x-ratelimit-reset-default"])).toBeGreaterThanOrEqual(
blockDuration / 1000
);
await new Promise((resolve) => setTimeout(resolve, blockDuration));
const afterBlockResponse = await request(app.getHttpServer())
.get("/v2/me")
.set("Authorization", `Bearer ${apiKeyString}`)
.expect(200);
expect(afterBlockResponse.headers["x-ratelimit-limit-default"]).toBe(limit.toString());
expect(afterBlockResponse.headers["x-ratelimit-remaining-default"]).toBe((limit - 1).toString());
expect(Number(afterBlockResponse.headers["x-ratelimit-reset-default"])).toBeGreaterThan(0);
},
15 * 1000
);
it(
"api key with custom rate limit - should enforce rate limits and reset after block duration",
async () => {
const limit = rateLimit.limit;
const blockDuration = rateLimit.blockDuration;
const name = rateLimit.name;
for (let i = 1; i <= limit; i++) {
const response = await request(app.getHttpServer())
.get("/v2/me")
.set({ Authorization: `Bearer ${apiKeyStringWithRateLimit}` })
.expect(200);
expect(response.headers[`x-ratelimit-limit-${name}`]).toBe(limit.toString());
expect(response.headers[`x-ratelimit-remaining-${name}`]).toBe((limit - i).toString());
expect(Number(response.headers[`x-ratelimit-reset-${name}`])).toBeGreaterThan(0);
}
const blockedResponse = await request(app.getHttpServer())
.get("/v2/me")
.set("Authorization", `Bearer ${apiKeyStringWithRateLimit}`)
.expect(429);
expect(blockedResponse.headers[`x-ratelimit-limit-${name}`]).toBe(limit.toString());
expect(blockedResponse.headers[`x-ratelimit-remaining-${name}`]).toBe("0");
expect(Number(blockedResponse.headers[`x-ratelimit-reset-${name}`])).toBeGreaterThanOrEqual(
blockDuration / 1000
);
await new Promise((resolve) => setTimeout(resolve, blockDuration));
const afterBlockResponse = await request(app.getHttpServer())
.get("/v2/me")
.set("Authorization", `Bearer ${apiKeyStringWithRateLimit}`)
.expect(200);
expect(afterBlockResponse.headers[`x-ratelimit-limit-${name}`]).toBe(limit.toString());
expect(afterBlockResponse.headers[`x-ratelimit-remaining-${name}`]).toBe((limit - 1).toString());
expect(Number(afterBlockResponse.headers[`x-ratelimit-reset-${name}`])).toBeGreaterThan(0);
},
15 * 1000
);
it(
"api key with multiple rate limits - should enforce both short and long rate limits",
async () => {
const shortLimit = firstRateLimitWithMultipleLimits.limit;
const longLimit = secondRateLimitWithMultipleLimits.limit;
const shortName = firstRateLimitWithMultipleLimits.name;
const longName = secondRateLimitWithMultipleLimits.name;
const shortBlock = firstRateLimitWithMultipleLimits.blockDuration;
const longBlock = secondRateLimitWithMultipleLimits.blockDuration;
let requestsMade = 0;
// note(Lauris): exhaust short limit to have remaining 0 for it
for (let i = 1; i <= shortLimit; i++) {
const response = await request(app.getHttpServer())
.get("/v2/me")
.set({ Authorization: `Bearer ${apiKeyStringWithMultipleLimits}` })
.expect(200);
requestsMade++;
expect(response.headers[`x-ratelimit-limit-${shortName}`]).toBe(shortLimit.toString());
expect(response.headers[`x-ratelimit-remaining-${shortName}`]).toBe((shortLimit - i).toString());
expect(Number(response.headers[`x-ratelimit-reset-${shortName}`])).toBeGreaterThan(0);
expect(response.headers[`x-ratelimit-limit-${longName}`]).toBe(longLimit.toString());
expect(response.headers[`x-ratelimit-remaining-${longName}`]).toBe((longLimit - i).toString());
expect(Number(response.headers[`x-ratelimit-reset-${longName}`])).toBeGreaterThan(0);
}
// note(Lauris): short limit exhausted, now exhaust long limit to have remaining 0 for it
for (let i = requestsMade; i < longLimit; i++) {
const responseAfterShortLimit = await request(app.getHttpServer())
.get("/v2/me")
.set({ Authorization: `Bearer ${apiKeyStringWithMultipleLimits}` })
.expect(200);
requestsMade++;
expect(responseAfterShortLimit.headers[`x-ratelimit-limit-${shortName}`]).toBe(
shortLimit.toString()
);
expect(responseAfterShortLimit.headers[`x-ratelimit-remaining-${shortName}`]).toBe("0");
expect(Number(responseAfterShortLimit.headers[`x-ratelimit-reset-${shortName}`])).toBeGreaterThan(
0
);
expect(responseAfterShortLimit.headers[`x-ratelimit-limit-${longName}`]).toBe(longLimit.toString());
expect(responseAfterShortLimit.headers[`x-ratelimit-remaining-${longName}`]).toBe(
(longLimit - requestsMade).toString()
);
expect(Number(responseAfterShortLimit.headers[`x-ratelimit-reset-${longName}`])).toBeGreaterThan(0);
}
// note(Lauris): both have remaining 0 so now exceed both
const blockedResponseLong = await request(app.getHttpServer())
.get("/v2/me")
.set({ Authorization: `Bearer ${apiKeyStringWithMultipleLimits}` })
.expect(429);
expect(blockedResponseLong.headers[`x-ratelimit-limit-${shortName}`]).toBe(shortLimit.toString());
expect(blockedResponseLong.headers[`x-ratelimit-remaining-${shortName}`]).toBe("0");
expect(Number(blockedResponseLong.headers[`x-ratelimit-reset-${shortName}`])).toBeGreaterThanOrEqual(
firstRateLimitWithMultipleLimits.blockDuration / 1000
);
expect(blockedResponseLong.headers[`x-ratelimit-limit-${longName}`]).toBe(longLimit.toString());
expect(blockedResponseLong.headers[`x-ratelimit-remaining-${longName}`]).toBe("0");
expect(Number(blockedResponseLong.headers[`x-ratelimit-reset-${longName}`])).toBeGreaterThanOrEqual(
secondRateLimitWithMultipleLimits.blockDuration / 1000
);
// note(Lauris): wait for short limit to reset
await new Promise((resolve) => setTimeout(resolve, shortBlock));
const responseAfterShortLimitReload = await request(app.getHttpServer())
.get("/v2/me")
.set({ Authorization: `Bearer ${apiKeyStringWithMultipleLimits}` })
.expect(200);
expect(responseAfterShortLimitReload.headers[`x-ratelimit-limit-${shortName}`]).toBe(
shortLimit.toString()
);
expect(responseAfterShortLimitReload.headers[`x-ratelimit-remaining-${shortName}`]).toBe(
(shortLimit - 1).toString()
);
expect(
Number(responseAfterShortLimitReload.headers[`x-ratelimit-reset-${shortName}`])
).toBeGreaterThan(0);
expect(responseAfterShortLimitReload.headers[`x-ratelimit-limit-${longName}`]).toBe(
longLimit.toString()
);
expect(responseAfterShortLimitReload.headers[`x-ratelimit-remaining-${longName}`]).toBe(
(longLimit - requestsMade).toString()
);
expect(
Number(responseAfterShortLimitReload.headers[`x-ratelimit-reset-${longName}`])
).toBeGreaterThan(0);
// note(Lauris): wait for long limit to reset
await new Promise((resolve) => setTimeout(resolve, longBlock));
const responseAfterLongLimitReload = await request(app.getHttpServer())
.get("/v2/me")
.set({ Authorization: `Bearer ${apiKeyStringWithMultipleLimits}` })
.expect(200);
expect(responseAfterLongLimitReload.headers[`x-ratelimit-limit-${shortName}`]).toBe(
shortLimit.toString()
);
expect(responseAfterLongLimitReload.headers[`x-ratelimit-remaining-${shortName}`]).toBe(
(shortLimit - 1).toString()
);
expect(
Number(responseAfterLongLimitReload.headers[`x-ratelimit-reset-${shortName}`])
).toBeGreaterThan(0);
expect(responseAfterLongLimitReload.headers[`x-ratelimit-limit-${longName}`]).toBe(
longLimit.toString()
);
expect(responseAfterLongLimitReload.headers[`x-ratelimit-remaining-${longName}`]).toBe(
(longLimit - 1).toString()
);
expect(Number(responseAfterLongLimitReload.headers[`x-ratelimit-reset-${longName}`])).toBeGreaterThan(
0
);
},
30 * 1000
);
it(
"non api key with default rate limit - should enforce rate limits and reset after block duration",
async () => {
const limit = mockDefaultLimit;
const blockDuration = mockDefaultBlockDuration;
for (let i = 1; i <= limit; i++) {
const response = await request(app.getHttpServer())
.get("/v2/me")
.set(X_CAL_CLIENT_ID, oAuthClient.id)
.set(X_CAL_SECRET_KEY, oAuthClient.secret)
.expect(200);
expect(response.headers["x-ratelimit-limit-default"]).toBe(limit.toString());
expect(response.headers["x-ratelimit-remaining-default"]).toBe((limit - i).toString());
expect(Number(response.headers["x-ratelimit-reset-default"])).toBeGreaterThan(0);
}
const blockedResponse = await request(app.getHttpServer())
.get("/v2/me")
.set(X_CAL_CLIENT_ID, oAuthClient.id)
.set(X_CAL_SECRET_KEY, oAuthClient.secret)
.expect(429);
expect(blockedResponse.headers["x-ratelimit-limit-default"]).toBe(limit.toString());
expect(blockedResponse.headers["x-ratelimit-remaining-default"]).toBe("0");
expect(Number(blockedResponse.headers["x-ratelimit-reset-default"])).toBeGreaterThanOrEqual(
blockDuration / 1000
);
await new Promise((resolve) => setTimeout(resolve, blockDuration));
const afterBlockResponse = await request(app.getHttpServer())
.get("/v2/me")
.set(X_CAL_CLIENT_ID, oAuthClient.id)
.set(X_CAL_SECRET_KEY, oAuthClient.secret)
.expect(200);
expect(afterBlockResponse.headers["x-ratelimit-limit-default"]).toBe(limit.toString());
expect(afterBlockResponse.headers["x-ratelimit-remaining-default"]).toBe((limit - 1).toString());
expect(Number(afterBlockResponse.headers["x-ratelimit-reset-default"])).toBeGreaterThan(0);
},
15 * 1000
);
afterAll(async () => {
await userRepositoryFixture.deleteByEmail(userEmail);
await organizationsRepositoryFixture.delete(organization.id);
await app.close();
});
});
});
+18 -5
View File
@@ -1,6 +1,7 @@
import appConfig from "@/config/app";
import { CustomThrottlerGuard } from "@/lib/throttler-guard";
import { AppLoggerMiddleware } from "@/middleware/app.logger.middleware";
import { RedirectsMiddleware } from "@/middleware/app.redirects.middleware";
import { RewriterMiddleware } from "@/middleware/app.rewrites.middleware";
import { JsonBodyMiddleware } from "@/middleware/body/json.body.middleware";
import { RawBodyMiddleware } from "@/middleware/body/raw.body.middleware";
@@ -12,12 +13,12 @@ import { JwtModule } from "@/modules/jwt/jwt.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { RedisModule } from "@/modules/redis/redis.module";
import { RedisService } from "@/modules/redis/redis.service";
import { ThrottlerStorageRedisService } from "@nest-lab/throttler-storage-redis";
import { BullModule } from "@nestjs/bull";
import { MiddlewareConsumer, Module, NestModule, RequestMethod } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { APP_GUARD, APP_INTERCEPTOR } from "@nestjs/core";
import { seconds, ThrottlerModule } from "@nestjs/throttler";
import { ThrottlerStorageRedisService } from "nestjs-throttler-storage-redis";
import { AppController } from "./app.controller";
@@ -33,16 +34,19 @@ import { AppController } from "./app.controller";
BullModule.forRoot({
redis: `${process.env.REDIS_URL}${process.env.NODE_ENV === "production" ? "?tls=true" : ""}`,
}),
// Rate limiting here is handled by the CustomThrottlerGuard
ThrottlerModule.forRootAsync({
imports: [RedisModule],
inject: [RedisService],
useFactory: (redisService: RedisService) => ({
// note(Lauris): IMPORTANT: rate limiting is enforced by CustomThrottlerGuard, but we need to have at least one
// entry in the throttlers array otherwise CustomThrottlerGuard is not invoked at all. If we specify only ThrottlerModule
// without .forRootAsync then throttler options are not passed to CustomThrottlerGuard containing redis connection etc.
// So we need to specify at least one dummy throttler here and CustomThrottlerGuard is actually handling the default and custom rate limits.
throttlers: [
{
name: "long",
ttl: seconds(60), // Time to live for the long period in seconds
limit: 120, // Maximum number of requests within the long ttl
name: "dummy",
ttl: seconds(60),
limit: 120,
},
],
storage: new ThrottlerStorageRedisService(redisService.redis),
@@ -55,6 +59,13 @@ import { AppController } from "./app.controller";
],
controllers: [AppController],
providers: [
{
provide: ThrottlerStorageRedisService,
useFactory: (redisService: RedisService) => {
return new ThrottlerStorageRedisService(redisService.redis);
},
inject: [RedisService],
},
{
provide: APP_INTERCEPTOR,
useClass: ResponseInterceptor,
@@ -79,6 +90,8 @@ export class AppModule implements NestModule {
.forRoutes("*")
.apply(AppLoggerMiddleware)
.forRoutes("*")
.apply(RedirectsMiddleware)
.forRoutes("/")
.apply(RewriterMiddleware)
.forRoutes("/");
}
@@ -14,7 +14,7 @@ export class BookingsRepository_2024_08_13 {
});
}
async getByIdsWithAttendeesAndUser(ids: number[]) {
async getByIdsWithAttendeesAndUserAndEvent(ids: number[]) {
return this.dbRead.prisma.booking.findMany({
where: {
id: {
@@ -24,6 +24,7 @@ export class BookingsRepository_2024_08_13 {
include: {
attendees: true,
user: true,
eventType: true,
},
});
}
@@ -36,7 +37,7 @@ export class BookingsRepository_2024_08_13 {
});
}
async getByIdWithAttendeesAndUser(id: number) {
async getByIdWithAttendeesAndUserAndEvent(id: number) {
return this.dbRead.prisma.booking.findUnique({
where: {
id,
@@ -44,11 +45,12 @@ export class BookingsRepository_2024_08_13 {
include: {
attendees: true,
user: true,
eventType: true,
},
});
}
async getByUidWithAttendeesAndUser(uid: string) {
async getByUidWithAttendeesAndUserAndEvent(uid: string) {
return this.dbRead.prisma.booking.findUnique({
where: {
uid,
@@ -56,11 +58,12 @@ export class BookingsRepository_2024_08_13 {
include: {
attendees: true,
user: true,
eventType: true,
},
});
}
async getRecurringByUidWithAttendeesAndUser(uid: string) {
async getRecurringByUidWithAttendeesAndUserAndEvent(uid: string) {
return this.dbRead.prisma.booking.findMany({
where: {
recurringEventId: uid,
@@ -68,6 +71,7 @@ export class BookingsRepository_2024_08_13 {
include: {
attendees: true,
user: true,
eventType: true,
},
});
}
@@ -1,8 +1,6 @@
import { BookingUidGuard } from "@/ee/bookings/2024-08-13/guards/booking-uid.guard";
import { CancelBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/cancel-booking.output";
import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output";
import { GetBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/get-booking.output";
import { GetBookingsOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/get-bookings.output";
import { MarkAbsentBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/mark-absent.output";
import { RescheduleBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/reschedule-booking.output";
import { BookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/bookings.service";
@@ -36,6 +34,7 @@ import { User } from "@prisma/client";
import { Request } from "express";
import { BOOKING_READ, BOOKING_WRITE, SUCCESS_STATUS } from "@calcom/platform-constants";
import { GetBookingOutput_2024_08_13, GetBookingsOutput_2024_08_13 } from "@calcom/platform-types";
import {
CreateBookingInputPipe,
CreateBookingInput,
@@ -1,7 +1,6 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output";
import { GetBookingsOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/get-bookings.output";
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
@@ -29,6 +28,7 @@ import {
CreateBookingInput_2024_08_13,
BookingOutput_2024_08_13,
RecurringBookingOutput_2024_08_13,
GetBookingsOutput_2024_08_13,
} from "@calcom/platform-types";
import { PlatformOAuthClient, Team } from "@calcom/prisma/client";
@@ -2,8 +2,6 @@ import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { CancelBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/cancel-booking.output";
import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output";
import { GetBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/get-booking.output";
import { GetBookingsOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/get-bookings.output";
import { MarkAbsentBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/mark-absent.output";
import { RescheduleBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/reschedule-booking.output";
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
@@ -30,6 +28,7 @@ import {
VERSION_2024_08_13,
X_CAL_CLIENT_ID,
} from "@calcom/platform-constants";
import { GetBookingOutput_2024_08_13, GetBookingsOutput_2024_08_13 } from "@calcom/platform-types";
import {
CreateBookingInput_2024_08_13,
BookingOutput_2024_08_13,
@@ -58,6 +57,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
let user: User;
let eventTypeId: number;
const eventTypeSlug = "peer-coding";
let recurringEventTypeId: number;
let createdBooking: BookingOutput_2024_08_13;
@@ -100,7 +100,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
};
await schedulesService.createUserSchedule(user.id, userSchedule);
const event = await eventTypesRepositoryFixture.create(
{ title: "peer coding", slug: "peer-coding", length: 60 },
{ title: "peer coding", slug: eventTypeSlug, length: 60 },
user.id
);
eventTypeId = event.id;
@@ -184,7 +184,10 @@ describe("Bookings Endpoints 2024-08-13", () => {
timeZone: "Europe/Rome",
language: "it",
},
meetingUrl: "https://meet.google.com/abc-def-ghi",
location: "https://meet.google.com/abc-def-ghi",
bookingFieldsResponses: {
customField: "customValue",
},
};
return request(app.getHttpServer())
@@ -208,14 +211,24 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(data.end).toEqual(new Date(Date.UTC(2030, 0, 8, 14, 0, 0)).toISOString());
expect(data.duration).toEqual(60);
expect(data.eventTypeId).toEqual(eventTypeId);
expect(data.eventType).toEqual({
id: eventTypeId,
slug: eventTypeSlug,
});
expect(data.attendees[0]).toEqual({
name: body.attendee.name,
timeZone: body.attendee.timeZone,
language: body.attendee.language,
absent: false,
});
expect(data.meetingUrl).toEqual(body.meetingUrl);
expect(data.location).toEqual(body.location);
expect(data.meetingUrl).toEqual(body.location);
expect(data.absentHost).toEqual(false);
expect(data.bookingFieldsResponses).toEqual({
name: body.attendee.name,
email: body.attendee.email,
...body.bookingFieldsResponses,
});
createdBooking = data;
} else {
throw new Error(
@@ -235,7 +248,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
timeZone: "Europe/Rome",
language: "it",
},
meetingUrl: "https://meet.google.com/abc-def-ghi",
location: "https://meet.google.com/abc-def-ghi",
};
return request(app.getHttpServer())
@@ -268,7 +281,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
language: body.attendee.language,
absent: false,
});
expect(firstBooking.meetingUrl).toEqual(body.meetingUrl);
expect(firstBooking.location).toEqual(body.location);
expect(firstBooking.recurringBookingUid).toBeDefined();
expect(firstBooking.absentHost).toEqual(false);
@@ -288,7 +301,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
language: body.attendee.language,
absent: false,
});
expect(secondBooking.meetingUrl).toEqual(body.meetingUrl);
expect(secondBooking.location).toEqual(body.location);
expect(secondBooking.absentHost).toEqual(false);
const thirdBooking = data[2];
@@ -307,7 +320,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
language: body.attendee.language,
absent: false,
});
expect(thirdBooking.meetingUrl).toEqual(body.meetingUrl);
expect(thirdBooking.location).toEqual(body.location);
expect(thirdBooking.absentHost).toEqual(false);
createdRecurringBooking = data;
@@ -343,7 +356,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(data.duration).toEqual(createdBooking.duration);
expect(data.eventTypeId).toEqual(createdBooking.eventTypeId);
expect(data.attendees[0]).toEqual(createdBooking.attendees[0]);
expect(data.meetingUrl).toEqual(createdBooking.meetingUrl);
expect(data.location).toEqual(createdBooking.location);
expect(data.absentHost).toEqual(createdBooking.absentHost);
} else {
throw new Error(
@@ -377,7 +390,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(data.eventTypeId).toEqual(createdRecurringBooking[0].eventTypeId);
expect(data.recurringBookingUid).toEqual(createdRecurringBooking[0].recurringBookingUid);
expect(data.attendees[0]).toEqual(createdRecurringBooking[0].attendees[0]);
expect(data.meetingUrl).toEqual(createdRecurringBooking[0].meetingUrl);
expect(data.location).toEqual(createdRecurringBooking[0].location);
expect(data.absentHost).toEqual(createdRecurringBooking[0].absentHost);
} else {
throw new Error(
@@ -414,7 +427,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(firstBooking.eventTypeId).toEqual(createdRecurringBooking[0].eventTypeId);
expect(firstBooking.recurringBookingUid).toEqual(recurringBookingUid);
expect(firstBooking.attendees[0]).toEqual(createdRecurringBooking[0].attendees[0]);
expect(firstBooking.meetingUrl).toEqual(createdRecurringBooking[0].meetingUrl);
expect(firstBooking.location).toEqual(createdRecurringBooking[0].location);
expect(firstBooking.absentHost).toEqual(createdRecurringBooking[0].absentHost);
const secondBooking = data[1];
@@ -428,7 +441,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(secondBooking.eventTypeId).toEqual(createdRecurringBooking[1].eventTypeId);
expect(secondBooking.recurringBookingUid).toEqual(recurringBookingUid);
expect(secondBooking.attendees[0]).toEqual(createdRecurringBooking[1].attendees[0]);
expect(secondBooking.meetingUrl).toEqual(createdRecurringBooking[1].meetingUrl);
expect(secondBooking.location).toEqual(createdRecurringBooking[1].location);
expect(secondBooking.absentHost).toEqual(createdRecurringBooking[1].absentHost);
const thirdBooking = data[2];
@@ -442,7 +455,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(thirdBooking.eventTypeId).toEqual(createdRecurringBooking[2].eventTypeId);
expect(thirdBooking.recurringBookingUid).toEqual(recurringBookingUid);
expect(thirdBooking.attendees[0]).toEqual(createdRecurringBooking[2].attendees[0]);
expect(thirdBooking.meetingUrl).toEqual(createdRecurringBooking[2].meetingUrl);
expect(thirdBooking.location).toEqual(createdRecurringBooking[2].location);
expect(thirdBooking.absentHost).toEqual(createdRecurringBooking[2].absentHost);
createdRecurringBooking = data;
@@ -764,7 +777,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(data.duration).toEqual(createdBooking.duration);
expect(data.eventTypeId).toEqual(createdBooking.eventTypeId);
expect(data.attendees[0]).toEqual(createdBooking.attendees[0]);
expect(data.meetingUrl).toEqual(createdBooking.meetingUrl);
expect(data.location).toEqual(createdBooking.location);
expect(data.absentHost).toEqual(createdBooking.absentHost);
rescheduledBooking = data;
@@ -815,7 +828,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(data.recurringBookingUid).toEqual(createdRecurringBooking[0].recurringBookingUid);
expect(data.eventTypeId).toEqual(createdRecurringBooking[0].eventTypeId);
expect(data.attendees[0]).toEqual(createdRecurringBooking[0].attendees[0]);
expect(data.meetingUrl).toEqual(createdRecurringBooking[0].meetingUrl);
expect(data.location).toEqual(createdRecurringBooking[0].location);
expect(data.absentHost).toEqual(createdRecurringBooking[0].absentHost);
const oldBooking = await bookingsRepositoryFixture.getByUid(createdRecurringBooking[0].uid);
@@ -885,7 +898,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(data.duration).toEqual(booking.duration);
expect(data.eventTypeId).toEqual(booking.eventTypeId);
expect(data.attendees[0]).toEqual(booking.attendees[0]);
expect(data.meetingUrl).toEqual(booking.meetingUrl);
expect(data.location).toEqual(booking.location);
});
});
@@ -918,7 +931,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(data.eventTypeId).toEqual(booking.eventTypeId);
expect(data.attendees[0].absent).toEqual(true);
expect(data.absentHost).toEqual(booking.absentHost);
expect(data.meetingUrl).toEqual(booking.meetingUrl);
expect(data.location).toEqual(booking.location);
});
});
});
@@ -955,7 +968,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(data.duration).toEqual(rescheduledBooking.duration);
expect(data.eventTypeId).toEqual(rescheduledBooking.eventTypeId);
expect(data.attendees[0]).toEqual(rescheduledBooking.attendees[0]);
expect(data.meetingUrl).toEqual(rescheduledBooking.meetingUrl);
expect(data.location).toEqual(rescheduledBooking.location);
expect(data.absentHost).toEqual(rescheduledBooking.absentHost);
const cancelledBooking = await bookingsRepositoryFixture.getByUid(rescheduledBooking.uid);
@@ -1005,10 +1018,6 @@ describe("Bookings Endpoints 2024-08-13", () => {
});
});
function responseDataIsBooking(data: any): data is BookingOutput_2024_08_13 {
return !Array.isArray(data) && typeof data === "object" && data && "id" in data;
}
function responseDataIsRecurranceBooking(data: any): data is RecurringBookingOutput_2024_08_13 {
return (
!Array.isArray(data) &&
@@ -1019,10 +1028,303 @@ describe("Bookings Endpoints 2024-08-13", () => {
);
}
function responseDataIsRecurringBooking(data: any): data is RecurringBookingOutput_2024_08_13[] {
return Array.isArray(data);
afterAll(async () => {
await oauthClientRepositoryFixture.delete(oAuthClient.id);
await teamRepositoryFixture.delete(organization.id);
await userRepositoryFixture.deleteByEmail(user.email);
await bookingsRepositoryFixture.deleteAllBookings(user.id, user.email);
await app.close();
});
});
function responseDataIsBooking(data: any): data is BookingOutput_2024_08_13 {
return !Array.isArray(data) && typeof data === "object" && data && "id" in data;
}
function responseDataIsRecurringBooking(data: any): data is RecurringBookingOutput_2024_08_13[] {
return Array.isArray(data);
}
describe("Recurring bookings", () => {
let app: INestApplication;
let organization: Team;
let userRepositoryFixture: UserRepositoryFixture;
let bookingsRepositoryFixture: BookingsRepositoryFixture;
let schedulesService: SchedulesService_2024_04_15;
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
let oAuthClient: PlatformOAuthClient;
let teamRepositoryFixture: TeamRepositoryFixture;
const userEmail = "bookings-controller-e2e@api.com";
let user: User;
const maxRecurrenceCount = 3;
let recurringEventTypeId: number;
beforeAll(async () => {
const moduleRef = await withApiAuth(
userEmail,
Test.createTestingModule({
imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15],
})
)
.overrideGuard(PermissionsGuard)
.useValue({
canActivate: () => true,
})
.compile();
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef);
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
schedulesService = moduleRef.get<SchedulesService_2024_04_15>(SchedulesService_2024_04_15);
organization = await teamRepositoryFixture.create({ name: "organization bookings" });
oAuthClient = await createOAuthClient(organization.id);
user = await userRepositoryFixture.create({
email: userEmail,
});
const userSchedule: CreateScheduleInput_2024_04_15 = {
name: "working time",
timeZone: "Europe/Rome",
isDefault: true,
};
await schedulesService.createUserSchedule(user.id, userSchedule);
const recurringEvent = await eventTypesRepositoryFixture.create(
// note(Lauris): freq 2 means weekly, interval 1 means every week and count 3 means 3 weeks in a row
{
title: "peer coding recurring",
slug: "peer-coding-recurring",
length: 60,
recurringEvent: { freq: 2, count: maxRecurrenceCount, interval: 1 },
},
user.id
);
recurringEventTypeId = recurringEvent.id;
app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication);
await app.init();
});
async function createOAuthClient(organizationId: number) {
const data = {
logo: "logo-url",
name: "name",
redirectUris: ["http://localhost:5555"],
permissions: 32,
};
const secret = "secret";
const client = await oauthClientRepositoryFixture.create(organizationId, data, secret);
return client;
}
it("should not create recurring booking with recurrenceCount larger than event type recurrence count", async () => {
const recurrenceCount = 1000;
const body: CreateRecurringBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 1, 4, 13, 0, 0)).toISOString(),
eventTypeId: recurringEventTypeId,
attendee: {
name: "Mr Proper Recurring",
email: "mr_proper_recurring@gmail.com",
timeZone: "Europe/Rome",
language: "it",
},
location: "https://meet.google.com/abc-def-ghi",
recurrenceCount,
};
return request(app.getHttpServer())
.post("/v2/bookings")
.send(body)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(400);
});
it("should create a recurring booking with recurrenceCount smaller than event type recurrence count", async () => {
const recurrenceCount = maxRecurrenceCount - 1;
const body: CreateRecurringBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 1, 4, 13, 0, 0)).toISOString(),
eventTypeId: recurringEventTypeId,
attendee: {
name: "Mr Proper Recurring",
email: "mr_proper_recurring@gmail.com",
timeZone: "Europe/Rome",
language: "it",
},
location: "https://meet.google.com/abc-def-ghi",
recurrenceCount,
};
return request(app.getHttpServer())
.post("/v2/bookings")
.send(body)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201)
.then(async (response) => {
const responseBody: CreateBookingOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
expect(responseDataIsRecurringBooking(responseBody.data)).toBe(true);
if (responseDataIsRecurringBooking(responseBody.data)) {
const data: RecurringBookingOutput_2024_08_13[] = responseBody.data;
expect(data.length).toEqual(maxRecurrenceCount - 1);
const firstBooking = data[0];
expect(firstBooking.id).toBeDefined();
expect(firstBooking.uid).toBeDefined();
expect(firstBooking.hosts[0].id).toEqual(user.id);
expect(firstBooking.status).toEqual("accepted");
expect(firstBooking.start).toEqual(new Date(Date.UTC(2030, 1, 4, 13, 0, 0)).toISOString());
expect(firstBooking.end).toEqual(new Date(Date.UTC(2030, 1, 4, 14, 0, 0)).toISOString());
expect(firstBooking.duration).toEqual(60);
expect(firstBooking.eventTypeId).toEqual(recurringEventTypeId);
expect(firstBooking.attendees[0]).toEqual({
name: body.attendee.name,
timeZone: body.attendee.timeZone,
language: body.attendee.language,
absent: false,
});
expect(firstBooking.location).toEqual(body.location);
expect(firstBooking.recurringBookingUid).toBeDefined();
expect(firstBooking.absentHost).toEqual(false);
const secondBooking = data[1];
expect(secondBooking.id).toBeDefined();
expect(secondBooking.uid).toBeDefined();
expect(secondBooking.hosts[0].id).toEqual(user.id);
expect(secondBooking.status).toEqual("accepted");
expect(secondBooking.start).toEqual(new Date(Date.UTC(2030, 1, 11, 13, 0, 0)).toISOString());
expect(secondBooking.end).toEqual(new Date(Date.UTC(2030, 1, 11, 14, 0, 0)).toISOString());
expect(secondBooking.duration).toEqual(60);
expect(secondBooking.eventTypeId).toEqual(recurringEventTypeId);
expect(secondBooking.recurringBookingUid).toBeDefined();
expect(secondBooking.attendees[0]).toEqual({
name: body.attendee.name,
timeZone: body.attendee.timeZone,
language: body.attendee.language,
absent: false,
});
expect(secondBooking.location).toEqual(body.location);
expect(secondBooking.absentHost).toEqual(false);
} else {
throw new Error(
"Invalid response data - expected recurring booking but received non array response"
);
}
});
});
it("should create a recurring booking with recurrenceCount equal to event type recurrence count", async () => {
const recurrenceCount = maxRecurrenceCount;
const body: CreateRecurringBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 1, 4, 13, 0, 0)).toISOString(),
eventTypeId: recurringEventTypeId,
attendee: {
name: "Mr Proper Recurring",
email: "mr_proper_recurring@gmail.com",
timeZone: "Europe/Rome",
language: "it",
},
location: "https://meet.google.com/abc-def-ghi",
recurrenceCount,
};
return request(app.getHttpServer())
.post("/v2/bookings")
.send(body)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201)
.then(async (response) => {
const responseBody: CreateBookingOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
expect(responseDataIsRecurringBooking(responseBody.data)).toBe(true);
if (responseDataIsRecurringBooking(responseBody.data)) {
const data: RecurringBookingOutput_2024_08_13[] = responseBody.data;
expect(data.length).toEqual(maxRecurrenceCount);
const firstBooking = data[0];
expect(firstBooking.id).toBeDefined();
expect(firstBooking.uid).toBeDefined();
expect(firstBooking.hosts[0].id).toEqual(user.id);
expect(firstBooking.status).toEqual("accepted");
expect(firstBooking.start).toEqual(new Date(Date.UTC(2030, 1, 4, 13, 0, 0)).toISOString());
expect(firstBooking.end).toEqual(new Date(Date.UTC(2030, 1, 4, 14, 0, 0)).toISOString());
expect(firstBooking.duration).toEqual(60);
expect(firstBooking.eventTypeId).toEqual(recurringEventTypeId);
expect(firstBooking.attendees[0]).toEqual({
name: body.attendee.name,
timeZone: body.attendee.timeZone,
language: body.attendee.language,
absent: false,
});
expect(firstBooking.location).toEqual(body.location);
expect(firstBooking.meetingUrl).toEqual(body.location);
expect(firstBooking.recurringBookingUid).toBeDefined();
expect(firstBooking.absentHost).toEqual(false);
const secondBooking = data[1];
expect(secondBooking.id).toBeDefined();
expect(secondBooking.uid).toBeDefined();
expect(secondBooking.hosts[0].id).toEqual(user.id);
expect(secondBooking.status).toEqual("accepted");
expect(secondBooking.start).toEqual(new Date(Date.UTC(2030, 1, 11, 13, 0, 0)).toISOString());
expect(secondBooking.end).toEqual(new Date(Date.UTC(2030, 1, 11, 14, 0, 0)).toISOString());
expect(secondBooking.duration).toEqual(60);
expect(secondBooking.eventTypeId).toEqual(recurringEventTypeId);
expect(secondBooking.recurringBookingUid).toBeDefined();
expect(secondBooking.attendees[0]).toEqual({
name: body.attendee.name,
timeZone: body.attendee.timeZone,
language: body.attendee.language,
absent: false,
});
expect(secondBooking.location).toEqual(body.location);
expect(secondBooking.absentHost).toEqual(false);
const thirdBooking = data[2];
expect(thirdBooking.id).toBeDefined();
expect(thirdBooking.uid).toBeDefined();
expect(thirdBooking.hosts[0].id).toEqual(user.id);
expect(thirdBooking.status).toEqual("accepted");
expect(thirdBooking.start).toEqual(new Date(Date.UTC(2030, 1, 18, 13, 0, 0)).toISOString());
expect(thirdBooking.end).toEqual(new Date(Date.UTC(2030, 1, 18, 14, 0, 0)).toISOString());
expect(thirdBooking.duration).toEqual(60);
expect(thirdBooking.eventTypeId).toEqual(recurringEventTypeId);
expect(thirdBooking.recurringBookingUid).toBeDefined();
expect(thirdBooking.attendees[0]).toEqual({
name: body.attendee.name,
timeZone: body.attendee.timeZone,
language: body.attendee.language,
absent: false,
});
expect(thirdBooking.location).toEqual(body.location);
expect(thirdBooking.absentHost).toEqual(false);
} else {
throw new Error(
"Invalid response data - expected recurring booking but received non array response"
);
}
});
});
afterEach(async () => {
await bookingsRepositoryFixture.deleteAllBookings(user.id, user.email);
});
afterAll(async () => {
await oauthClientRepositoryFixture.delete(oAuthClient.id);
await teamRepositoryFixture.delete(organization.id);
@@ -73,7 +73,9 @@ export class BookingsService_2024_08_13 {
const bookingRequest = await this.inputService.createBookingRequest(request, body);
const booking = await handleInstantMeeting(bookingRequest);
const databaseBooking = await this.bookingsRepository.getByIdWithAttendeesAndUser(booking.bookingId);
const databaseBooking = await this.bookingsRepository.getByIdWithAttendeesAndUserAndEvent(
booking.bookingId
);
if (!databaseBooking) {
throw new Error(`Booking with id=${booking.bookingId} was not found in the database`);
}
@@ -94,7 +96,7 @@ export class BookingsService_2024_08_13 {
throw new Error("Recurring booking was not created");
}
const recurringBooking = await this.bookingsRepository.getRecurringByUidWithAttendeesAndUser(uid);
const recurringBooking = await this.bookingsRepository.getRecurringByUidWithAttendeesAndUserAndEvent(uid);
return this.outputService.getOutputRecurringBookings(recurringBooking);
}
@@ -106,7 +108,7 @@ export class BookingsService_2024_08_13 {
throw new Error("Booking was not created");
}
const databaseBooking = await this.bookingsRepository.getByIdWithAttendeesAndUser(booking.id);
const databaseBooking = await this.bookingsRepository.getByIdWithAttendeesAndUserAndEvent(booking.id);
if (!databaseBooking) {
throw new Error(`Booking with id=${booking.id} was not found in the database`);
}
@@ -115,7 +117,7 @@ export class BookingsService_2024_08_13 {
}
async getBooking(uid: string) {
const booking = await this.bookingsRepository.getByUidWithAttendeesAndUser(uid);
const booking = await this.bookingsRepository.getByUidWithAttendeesAndUserAndEvent(uid);
if (booking) {
const isRecurring = !!booking.recurringEventId;
@@ -125,7 +127,7 @@ export class BookingsService_2024_08_13 {
return this.outputService.getOutputBooking(booking);
}
const recurringBooking = await this.bookingsRepository.getRecurringByUidWithAttendeesAndUser(uid);
const recurringBooking = await this.bookingsRepository.getRecurringByUidWithAttendeesAndUserAndEvent(uid);
if (!recurringBooking.length) {
throw new NotFoundException(`Booking with uid=${uid} was not found in the database`);
}
@@ -149,7 +151,7 @@ export class BookingsService_2024_08_13 {
// note(Lauris): fetchedBookings don't have attendees information and responses and i don't want to add them to the handler query,
// because its used elsewhere in code that does not need that information, so i get ids, fetch bookings and then return them formatted in same order as ids.
const ids = fetchedBookings.bookings.map((booking) => booking.id);
const bookings = await this.bookingsRepository.getByIdsWithAttendeesAndUser(ids);
const bookings = await this.bookingsRepository.getByIdsWithAttendeesAndUserAndEvent(ids);
const bookingMap = new Map(bookings.map((booking) => [booking.id, booking]));
const orderedBookings = ids.map((id) => bookingMap.get(id));
@@ -162,6 +164,7 @@ export class BookingsService_2024_08_13 {
const formatted = {
...booking,
eventType: booking.eventType,
eventTypeId: booking.eventTypeId,
startTime: new Date(booking.startTime),
endTime: new Date(booking.endTime),
@@ -191,7 +194,7 @@ export class BookingsService_2024_08_13 {
throw new Error("Booking was not created");
}
const databaseBooking = await this.bookingsRepository.getByIdWithAttendeesAndUser(booking.id);
const databaseBooking = await this.bookingsRepository.getByIdWithAttendeesAndUserAndEvent(booking.id);
if (!databaseBooking) {
throw new Error(`Booking with id=${booking.id} was not found in the database`);
}
@@ -226,7 +229,7 @@ export class BookingsService_2024_08_13 {
userId: bookingOwnerId,
});
const booking = await this.bookingsRepository.getByUidWithAttendeesAndUser(bookingUid);
const booking = await this.bookingsRepository.getByUidWithAttendeesAndUserAndEvent(bookingUid);
if (!booking) {
throw new Error(`Booking with uid=${bookingUid} was not found in the database`);
@@ -5,7 +5,7 @@ import { hashAPIKey, isApiKey, stripApiKey } from "@/lib/api-key";
import { ApiKeyRepository } from "@/modules/api-key/api-key-repository";
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.service";
import { Injectable, NotFoundException } from "@nestjs/common";
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
import { Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Request } from "express";
@@ -57,9 +57,9 @@ export enum Frequency {
const recurringEventSchema = z.object({
dtstart: z.string().optional(),
interval: z.number().int().optional(),
count: z.number().int().optional(),
freq: z.nativeEnum(Frequency).optional(),
interval: z.number().int(),
count: z.number().int(),
freq: z.nativeEnum(Frequency),
until: z.string().optional(),
});
@@ -89,7 +89,7 @@ export class InputBookingsService_2024_08_13 {
? await this.createBookingRequestOAuthClientParams(oAuthClientId)
: DEFAULT_PLATFORM_PARAMS;
const location = request.body.meetingUrl;
const location = request.body.location || request.body.meetingUrl;
Object.assign(newRequest, { userId, ...oAuthParams, platformBookingLocation: location });
newRequest.body = { ...bodyTransformed, noEmail: !oAuthParams.arePlatformEmailsEnabled };
@@ -147,7 +147,7 @@ export class InputBookingsService_2024_08_13 {
? await this.createBookingRequestOAuthClientParams(oAuthClientId)
: DEFAULT_PLATFORM_PARAMS;
const location = request.body.meetingUrl;
const location = request.body.location || request.body.meetingUrl;
Object.assign(newRequest, {
userId,
...oAuthParams,
@@ -175,14 +175,16 @@ export class InputBookingsService_2024_08_13 {
const occurrence = recurringEventSchema.parse(eventType.recurringEvent);
const repeatsEvery = occurrence.interval;
const repeatsTimes = occurrence.count;
if (inputBooking.recurrenceCount && inputBooking.recurrenceCount > occurrence.count) {
throw new BadRequestException(
"Provided recurrence count is higher than the event type's recurring event count."
);
}
const repeatsTimes = inputBooking.recurrenceCount || occurrence.count;
// note(Lauris): timeBetween 0=yearly, 1=monthly and 2=weekly
const timeBetween = occurrence.freq;
if (!repeatsTimes) {
throw new Error("Repeats times is required");
}
const events = [];
const recurringEventId = uuidv4();
@@ -257,7 +259,7 @@ export class InputBookingsService_2024_08_13 {
}
async transformInputRescheduleBooking(bookingUid: string, inputBooking: RescheduleBookingInput_2024_08_13) {
const booking = await this.bookingsRepository.getByUidWithAttendeesAndUser(bookingUid);
const booking = await this.bookingsRepository.getByUidWithAttendeesAndUserAndEvent(bookingUid);
if (!booking) {
throw new NotFoundException(`Booking with uid=${bookingUid} not found`);
}
@@ -390,7 +392,9 @@ export class InputBookingsService_2024_08_13 {
async transformInputCancelBooking(bookingUid: string, inputBooking: CancelBookingInput_2024_08_13) {
let allRemainingBookings = false;
let uid = bookingUid;
const recurringBooking = await this.bookingsRepository.getRecurringByUidWithAttendeesAndUser(bookingUid);
const recurringBooking = await this.bookingsRepository.getRecurringByUidWithAttendeesAndUserAndEvent(
bookingUid
);
if (recurringBooking.length) {
// note(Lauirs): this means that bookingUid is equal to recurringEventId on individual bookings of recurring one aka main recurring event
@@ -7,14 +7,20 @@ import { z } from "zod";
import { BookingOutput_2024_08_13, RecurringBookingOutput_2024_08_13 } from "@calcom/platform-types";
import { Booking } from "@calcom/prisma/client";
export const bookingResponsesSchema = z.object({
email: z.string(),
name: z.string(),
guests: z.array(z.string()).optional(),
rescheduledReason: z.string().optional(),
});
export const bookingResponsesSchema = z
.object({
email: z.string(),
name: z.string(),
guests: z.array(z.string()).optional(),
rescheduledReason: z.string().optional(),
})
.passthrough();
type DatabaseBooking = Booking & {
eventType: {
id: number;
slug: string;
} | null;
attendees: {
name: string;
email: string;
@@ -38,6 +44,8 @@ export class OutputBookingsService_2024_08_13 {
const booking = {
id: databaseBooking.id,
uid: databaseBooking.uid,
title: databaseBooking.title,
description: databaseBooking.description,
hosts: [databaseBooking.user],
status: databaseBooking.status.toLowerCase(),
cancellationReason: databaseBooking.cancellationReason || undefined,
@@ -46,6 +54,8 @@ export class OutputBookingsService_2024_08_13 {
start: databaseBooking.startTime,
end: databaseBooking.endTime,
duration,
eventType: databaseBooking.eventType,
// note(Lauris): eventTypeId is deprecated
eventTypeId: databaseBooking.eventTypeId,
attendees: databaseBooking.attendees.map((attendee) => ({
name: attendee.name,
@@ -55,18 +65,22 @@ export class OutputBookingsService_2024_08_13 {
absent: !!attendee.noShow,
})),
guests: bookingResponses.guests,
location: databaseBooking.location,
// note(Lauris): meetingUrl is deprecated
meetingUrl: databaseBooking.location,
absentHost: !!databaseBooking.noShowHost,
};
return plainToClass(BookingOutput_2024_08_13, booking, { strategy: "excludeAll" });
const bookingTransformed = plainToClass(BookingOutput_2024_08_13, booking, { strategy: "excludeAll" });
bookingTransformed.bookingFieldsResponses = bookingResponses;
return bookingTransformed;
}
async getOutputRecurringBookings(databaseBookings: DatabaseBooking[]) {
const transformed = [];
for (const booking of databaseBookings) {
const databaseBooking = await this.bookingsRepository.getByIdWithAttendeesAndUser(booking.id);
const databaseBooking = await this.bookingsRepository.getByIdWithAttendeesAndUserAndEvent(booking.id);
if (!databaseBooking) {
throw new Error(`Booking with id=${booking.id} was not found in the database`);
}
@@ -87,6 +101,8 @@ export class OutputBookingsService_2024_08_13 {
const booking = {
id: databaseBooking.id,
uid: databaseBooking.uid,
title: databaseBooking.title,
description: databaseBooking.description,
hosts: [databaseBooking.user],
status: databaseBooking.status.toLowerCase(),
cancellationReason: databaseBooking.cancellationReason || undefined,
@@ -95,6 +111,8 @@ export class OutputBookingsService_2024_08_13 {
start: databaseBooking.startTime,
end: databaseBooking.endTime,
duration,
eventType: databaseBooking.eventType,
// note(Lauris): eventTypeId is deprecated
eventTypeId: databaseBooking.eventTypeId,
attendees: databaseBooking.attendees.map((attendee) => ({
name: attendee.name,
@@ -104,9 +122,12 @@ export class OutputBookingsService_2024_08_13 {
absent: !!attendee.noShow,
})),
guests: bookingResponses.guests,
location: databaseBooking.location,
// note(Lauris): meetingUrl is deprecated
meetingUrl: databaseBooking.location,
recurringBookingUid: databaseBooking.recurringEventId,
absentHost: !!databaseBooking.noShowHost,
bookingFieldsResponses: databaseBooking.responses,
};
return plainToClass(RecurringBookingOutput_2024_08_13, booking, { strategy: "excludeAll" });
@@ -68,6 +68,7 @@ export class CalendarsController {
@Post("/ics-feed/save")
@UseGuards(ApiAuthGuard)
@ApiOperation({ summary: "Save an ICS feed" })
async createIcsFeed(
@GetUser("id") userId: number,
@GetUser("email") userEmail: string,
@@ -78,6 +79,7 @@ export class CalendarsController {
@Get("/ics-feed/check")
@UseGuards(ApiAuthGuard)
@ApiOperation({ summary: "Check an ICS feed" })
async checkIcsFeed(@GetUser("id") userId: number): Promise<ApiResponse> {
return await this.icsFeedService.check(userId);
}
@@ -260,6 +260,7 @@ describe("Event types Endpoints", () => {
},
requiresBookerEmailVerification: false,
hideCalendarNotes: false,
hideCalendarEventDetails: false,
lockTimeZoneToggleOnBookingPage: true,
color: {
darkThemeHex: "#292929",
@@ -297,6 +298,7 @@ describe("Event types Endpoints", () => {
);
expect(createdEventType.hideCalendarNotes).toEqual(body.hideCalendarNotes);
expect(createdEventType.hideCalendarEventDetails).toEqual(body.hideCalendarEventDetails);
expect(createdEventType.lockTimeZoneToggleOnBookingPage).toEqual(
body.lockTimeZoneToggleOnBookingPage
);
@@ -351,6 +353,7 @@ describe("Event types Endpoints", () => {
eventType.requiresBookerEmailVerification
);
expect(fetchedEventType.hideCalendarNotes).toEqual(eventType.hideCalendarNotes);
expect(fetchedEventType.hideCalendarEventDetails).toEqual(eventType.hideCalendarEventDetails);
expect(fetchedEventType.lockTimeZoneToggleOnBookingPage).toEqual(
eventType.lockTimeZoneToggleOnBookingPage
);
@@ -667,6 +670,7 @@ describe("Event types Endpoints", () => {
},
requiresBookerEmailVerification: true,
hideCalendarNotes: true,
hideCalendarEventDetails: true,
lockTimeZoneToggleOnBookingPage: true,
color: {
darkThemeHex: "#292929",
@@ -706,6 +710,7 @@ describe("Event types Endpoints", () => {
body.requiresBookerEmailVerification
);
expect(updatedEventType.hideCalendarNotes).toEqual(body.hideCalendarNotes);
expect(updatedEventType.hideCalendarEventDetails).toEqual(body.hideCalendarEventDetails);
expect(updatedEventType.lockTimeZoneToggleOnBookingPage).toEqual(
body.lockTimeZoneToggleOnBookingPage
);
@@ -724,6 +729,7 @@ describe("Event types Endpoints", () => {
eventType.customName = updatedEventType.customName;
eventType.requiresBookerEmailVerification = updatedEventType.requiresBookerEmailVerification;
eventType.hideCalendarNotes = updatedEventType.hideCalendarNotes;
eventType.hideCalendarEventDetails = updatedEventType.hideCalendarEventDetails;
eventType.lockTimeZoneToggleOnBookingPage = updatedEventType.lockTimeZoneToggleOnBookingPage;
eventType.color = updatedEventType.color;
});
@@ -774,6 +780,7 @@ describe("Event types Endpoints", () => {
eventType.requiresBookerEmailVerification
);
expect(fetchedEventType.hideCalendarNotes).toEqual(eventType.hideCalendarNotes);
expect(fetchedEventType.hideCalendarEventDetails).toEqual(eventType.hideCalendarEventDetails);
expect(fetchedEventType.lockTimeZoneToggleOnBookingPage).toEqual(
eventType.lockTimeZoneToggleOnBookingPage
);
@@ -811,6 +818,7 @@ describe("Event types Endpoints", () => {
eventType.requiresBookerEmailVerification
);
expect(fetchedEventType.hideCalendarNotes).toEqual(eventType.hideCalendarNotes);
expect(fetchedEventType.hideCalendarEventDetails).toEqual(eventType.hideCalendarEventDetails);
expect(fetchedEventType.lockTimeZoneToggleOnBookingPage).toEqual(
eventType.lockTimeZoneToggleOnBookingPage
);
@@ -1,12 +1,9 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { UsersService } from "@/modules/users/services/users.service";
import { UserWithProfile } from "@/modules/users/users.repository";
import { Injectable } from "@nestjs/common";
import { getEventTypeById } from "@calcom/platform-libraries";
import { InputEventTransformed_2024_06_14 } from "@calcom/platform-types";
import type { PrismaClient } from "@calcom/prisma";
@Injectable()
export class EventTypesRepository_2024_06_14 {
@@ -69,21 +66,6 @@ export class EventTypesRepository_2024_06_14 {
});
}
async getUserEventTypeForAtom(
user: UserWithProfile,
isUserOrganizationAdmin: boolean,
eventTypeId: number
) {
return await getEventTypeById({
currentOrganizationId: this.usersService.getUserMainOrgId(user),
eventTypeId,
userId: user.id,
prisma: this.dbRead.prisma as unknown as PrismaClient,
isUserOrganizationAdmin,
isTrpcCall: true,
});
}
async getEventTypeById(eventTypeId: number) {
return this.dbRead.prisma.eventType.findUnique({
where: { id: eventTypeId },
@@ -142,27 +142,6 @@ export class EventTypesService_2024_06_14 {
});
}
async getUserEventTypeForAtom(user: UserWithProfile, eventTypeId: number) {
const organizationId = this.usersService.getUserMainOrgId(user);
const isUserOrganizationAdmin = organizationId
? await this.membershipsRepository.isUserOrganizationAdmin(user.id, organizationId)
: false;
const eventType = await this.eventTypesRepository.getUserEventTypeForAtom(
user,
isUserOrganizationAdmin,
eventTypeId
);
if (!eventType) {
return null;
}
this.checkUserOwnsEventType(user.id, eventType.eventType);
return eventType;
}
async getEventTypesPublicByUsername(username: string): Promise<EventTypesPublic> {
const user = await this.usersRepository.findByUsername(username);
if (!user) {
@@ -242,6 +242,10 @@ export class InputEventTypesService_2024_06_14 {
return transformConfirmationPolicyApiToInternal(requiresConfirmation);
}
transformInputRecurrignEvent(recurrence: CreateEventTypeInput_2024_06_14["recurrence"]) {
if (!recurrence || recurrence.disabled) {
return undefined;
}
return transformRecurrenceApiToInternal(recurrence);
}
@@ -80,6 +80,7 @@ type Input = Pick<
| "eventName"
| "destinationCalendar"
| "useEventTypeDestinationCalendarEmail"
| "hideCalendarEventDetails"
>;
@Injectable()
@@ -111,6 +112,7 @@ export class OutputEventTypesService_2024_06_14 {
hideCalendarNotes,
seatsShowAttendees,
useEventTypeDestinationCalendarEmail,
hideCalendarEventDetails,
} = databaseEventType;
const locations = this.transformLocations(databaseEventType.locations);
@@ -182,6 +184,7 @@ export class OutputEventTypesService_2024_06_14 {
customName,
destinationCalendar,
useDestinationCalendarEmail: useEventTypeDestinationCalendarEmail,
hideCalendarEventDetails,
};
}
@@ -23,8 +23,7 @@ import {
Patch,
UseGuards,
} from "@nestjs/common";
import { ApiResponse, ApiExcludeController as DocsExcludeController } from "@nestjs/swagger";
import { Throttle } from "@nestjs/throttler";
import { ApiExcludeController as DocsExcludeController } from "@nestjs/swagger";
import { SCHEDULE_READ, SCHEDULE_WRITE, SUCCESS_STATUS } from "@calcom/platform-constants";
import { UpdateScheduleInput_2024_04_15 } from "@calcom/platform-types";
@@ -57,11 +56,6 @@ export class SchedulesController_2024_04_15 {
@Get("/default")
@Permissions([SCHEDULE_READ])
@ApiResponse({
status: 200,
description: "Returns the default schedule",
type: GetDefaultScheduleOutput_2024_04_15,
})
async getDefaultSchedule(
@GetUser() user: UserWithProfile
): Promise<GetDefaultScheduleOutput_2024_04_15 | null> {
@@ -78,7 +72,6 @@ export class SchedulesController_2024_04_15 {
@Get("/:scheduleId")
@Permissions([SCHEDULE_READ])
@Throttle({ default: { limit: 10, ttl: 60000 } }) // allow 10 requests per minute (for :scheduleId)
async getSchedule(
@GetUser() user: UserWithProfile,
@Param("scheduleId") scheduleId: number
@@ -18,7 +18,6 @@ import {
UseGuards,
} from "@nestjs/common";
import { ApiHeader, ApiOperation, ApiResponse, ApiTags as DocsTags } from "@nestjs/swagger";
import { Throttle } from "@nestjs/throttler";
import { SCHEDULE_READ, SCHEDULE_WRITE, SUCCESS_STATUS } from "@calcom/platform-constants";
import {
@@ -57,17 +56,19 @@ export class SchedulesController_2024_06_11 {
@ApiOperation({
summary: "Create a schedule",
description: `
Create a schedule for the authenticated user.
The point of creating schedules is for event types to be available at specific times.
First goal of schedules is to have a default schedule. If you are platform customer and created managed users, then it is important to note that each managed user should have a default schedule.
1. If you passed \`timeZone\` when creating managed user, then the default schedule from Monday to Friday from 9AM to 5PM will be created with that timezone. Managed user can then change the default schedule via \`AvailabilitySettings\` atom.
2. If you did not, then we assume you want that user has specific schedule right away. You should create default schedule by specifying
\`"isDefault": true\` in the request body. Until the user has a default schedule that user can't be booked or manage his / her schedule via the AvailabilitySettings atom.
The first goal of schedules is to have a default schedule. If you are platform customer and created managed users, then it is important to note that each managed user should have a default schedule.
1. If you passed \`timeZone\` when creating managed user, then the default schedule from Monday to Friday from 9AM to 5PM will be created with that timezone. The managed user can then change the default schedule via the \`AvailabilitySettings\` atom.
2. If you did not, then we assume you want the user to have this specific schedule right away. You should create a default schedule by specifying
\`"isDefault": true\` in the request body. Until the user has a default schedule the user can't be booked nor manage their schedule via the AvailabilitySettings atom.
Second goal is to create other schedules that event types can point to, so that when that event is booked availability is not checked against the default schedule but against that specific schedule.
After creating a non default schedule you can update event type to point to that schedule via the PATCH \`event-types/{eventTypeId}\` endpoint.
The second goal of schedules is to create another schedule that event types can point to. This is useful for when an event is booked because availability is not checked against the default schedule but instead against that specific schedule.
After creating a non-default schedule, you can update an event type to point to that schedule via the PATCH \`event-types/{eventTypeId}\` endpoint.
When specifying start time and end time for each day use 24 hour format e.g. 08:00, 15:00 etc.
When specifying start time and end time for each day use the 24 hour format e.g. 08:00, 15:00 etc.
`,
})
async createSchedule(
@@ -86,10 +87,12 @@ export class SchedulesController_2024_06_11 {
@Permissions([SCHEDULE_READ])
@ApiResponse({
status: 200,
description: "Returns the default schedule of the authenticated user",
type: GetDefaultScheduleOutput_2024_06_11,
})
@ApiOperation({ summary: "Get default schedule (of the authenticated user)" })
@ApiOperation({
summary: "Get default schedule",
description: "Get the default schedule of the authenticated user.",
})
async getDefaultSchedule(@GetUser() user: UserWithProfile): Promise<GetScheduleOutput_2024_06_11> {
const schedule = await this.schedulesService.getUserScheduleDefault(user.id);
@@ -101,7 +104,6 @@ export class SchedulesController_2024_06_11 {
@Get("/:scheduleId")
@Permissions([SCHEDULE_READ])
@Throttle({ default: { limit: 10, ttl: 60000 } }) // allow 10 requests per minute (for :scheduleId)
@ApiOperation({ summary: "Get a schedule" })
async getSchedule(
@GetUser() user: UserWithProfile,
@@ -117,7 +119,10 @@ export class SchedulesController_2024_06_11 {
@Get("/")
@Permissions([SCHEDULE_READ])
@ApiOperation({ summary: "Get all schedules (of the authenticated user)" })
@ApiOperation({
summary: "Get all schedules",
description: "Get all schedules of the authenticated user.",
})
async getSchedules(@GetUser() user: UserWithProfile): Promise<GetSchedulesOutput_2024_06_11> {
const schedules = await this.schedulesService.getUserSchedules(user.id);
+7
View File
@@ -19,6 +19,13 @@ export type Environment = {
CALCOM_LICENSE_KEY: string;
GET_LICENSE_KEY_URL: string;
API_KEY_PREFIX: string;
DOCS_URL: string;
RATE_LIMIT_DEFAULT_TTL_MS: number;
RATE_LIMIT_DEFAULT_LIMIT_API_KEY: number;
RATE_LIMIT_DEFAULT_LIMIT_OAUTH_CLIENT: number;
RATE_LIMIT_DEFAULT_LIMIT_ACCESS_TOKEN: number;
RATE_LIMIT_DEFAULT_LIMIT: number;
RATE_LIMIT_DEFAULT_BLOCK_DURATION_MS: number;
};
export const getEnv = <K extends keyof Environment>(key: K, fallback?: Environment[K]): Environment[K] => {
+199 -11
View File
@@ -1,42 +1,230 @@
import { isApiKey } from "@/lib/api-key";
import { Injectable, Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { getEnv } from "@/env";
import { hashAPIKey, isApiKey, stripApiKey } from "@/lib/api-key";
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { ThrottlerStorageRedisService } from "@nest-lab/throttler-storage-redis";
import { Inject, Injectable, Logger, UnauthorizedException } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { ThrottlerGuard, ThrottlerModuleOptions, ThrottlerStorage } from "@nestjs/throttler";
import { Request } from "express";
import {
ThrottlerGuard,
ThrottlerException,
ThrottlerRequest,
ThrottlerModuleOptions,
seconds,
} from "@nestjs/throttler";
import { Request, Response } from "express";
import { z } from "zod";
import { X_CAL_CLIENT_ID } from "@calcom/platform-constants";
const rateLimitSchema = z.object({
name: z.string(),
limit: z.number(),
ttl: z.number(),
blockDuration: z.number(),
});
type RateLimitType = z.infer<typeof rateLimitSchema>;
const rateLimitsSchema = z.array(rateLimitSchema);
const sixtySecondsMs = 60 * 1000;
@Injectable()
export class CustomThrottlerGuard extends ThrottlerGuard {
private logger = new Logger("CustomThrottlerGuard");
private defaultTttl = Number(getEnv("RATE_LIMIT_DEFAULT_TTL_MS", sixtySecondsMs));
private defaultLimitApiKey = Number(getEnv("RATE_LIMIT_DEFAULT_LIMIT_API_KEY", 120));
private defaultLimitOAuthClient = Number(getEnv("RATE_LIMIT_DEFAULT_LIMIT_OAUTH_CLIENT", 500));
private defaultLimitAccessToken = Number(getEnv("RATE_LIMIT_DEFAULT_LIMIT_ACCESS_TOKEN", 500));
private defaultLimit = Number(getEnv("RATE_LIMIT_DEFAULT_LIMIT", 120));
private defaultBlockDuration = Number(getEnv("RATE_LIMIT_DEFAULT_BLOCK_DURATION_MS", sixtySecondsMs));
constructor(
options: ThrottlerModuleOptions,
storageService: ThrottlerStorage,
@Inject(ThrottlerStorageRedisService) protected readonly storageService: ThrottlerStorageRedisService,
reflector: Reflector,
private readonly config: ConfigService
private readonly dbRead: PrismaReadService
) {
super(options, storageService, reflector);
this.storageService = storageService;
}
protected async handleRequest(requestProps: ThrottlerRequest): Promise<boolean> {
const { context } = requestProps;
const request = context.switchToHttp().getRequest<Request>();
const response = context.switchToHttp().getResponse<Response>();
const tracker = await this.getTracker(request);
this.logger.log(
`Tracker "${tracker}" generated based on: Bearer token "${request.get(
"Authorization"
)}", OAuth client ID "${request.get(X_CAL_CLIENT_ID)}" and IP "${request.ip}"`
);
if (tracker.startsWith("api_key_")) {
return this.handleApiKeyRequest(tracker, response);
} else {
return this.handleNonApiKeyRequest(tracker, response);
}
}
private async handleApiKeyRequest(tracker: string, response: Response): Promise<boolean> {
const rateLimits = await this.getRateLimitsForApiKeyTracker(tracker);
let allLimitsBlocked = true;
for (const rateLimit of rateLimits) {
const { isBlocked } = await this.incrementRateLimit(tracker, rateLimit, response);
if (!isBlocked) {
allLimitsBlocked = false;
}
}
if (allLimitsBlocked) {
throw new ThrottlerException("Too many requests. Please try again later.");
}
return true;
}
private async handleNonApiKeyRequest(tracker: string, response: Response): Promise<boolean> {
const rateLimit = this.getDefaultRateLimit(tracker);
this.logger.log(`Tracker "${tracker}" uses default rate limits because it is not tracking api key:
${JSON.stringify(rateLimit, null, 2)}
`);
const { isBlocked } = await this.incrementRateLimit(tracker, rateLimit, response);
if (isBlocked) {
throw new ThrottlerException("Too many requests. Please try again later.");
}
return true;
}
private getDefaultRateLimit(tracker: string) {
return {
name: "default",
limit: this.getDefaultLimit(tracker),
ttl: this.getDefaultTtl(),
blockDuration: this.getDefaultBlockDuration(),
};
}
getDefaultLimit(tracker: string) {
if (tracker.startsWith("api_key_")) {
return this.defaultLimitApiKey;
} else if (tracker.startsWith("oauth_client_")) {
return this.defaultLimitOAuthClient;
} else if (tracker.startsWith("access_token_")) {
return this.defaultLimitAccessToken;
} else {
return this.defaultLimit;
}
}
getDefaultTtl() {
return this.defaultTttl;
}
getDefaultBlockDuration() {
return this.defaultBlockDuration;
}
private async getRateLimitsForApiKeyTracker(tracker: string) {
const cacheKey = `rate_limit:${tracker}`;
const cachedRateLimits = await this.storageService.redis.get(cacheKey);
if (cachedRateLimits) {
this.logger.log(`Tracker "${tracker}" rate limits retrieved from redis cache:
${cachedRateLimits}
`);
return rateLimitsSchema.parse(JSON.parse(cachedRateLimits));
}
const apiKey = tracker.replace("api_key_", "");
let rateLimits: RateLimitType[];
const apiKeyRecord = await this.dbRead.prisma.apiKey.findUnique({
where: { hashedKey: apiKey },
select: { id: true },
});
if (!apiKeyRecord) {
throw new UnauthorizedException("Invalid API Key");
}
rateLimits = await this.dbRead.prisma.rateLimit.findMany({
where: { apiKeyId: apiKeyRecord.id },
select: { name: true, limit: true, ttl: true, blockDuration: true },
});
if (rateLimits) {
this.logger.log(`Tracker "${tracker}" rate limits retrieved from database:
${JSON.stringify(rateLimits, null, 2)}`);
}
if (!rateLimits || rateLimits.length === 0) {
rateLimits = [this.getDefaultRateLimit(tracker)];
this.logger.log(`Tracker "${tracker}" rate limits not found in database. Using default rate limits:
${JSON.stringify(rateLimits, null, 2)}`);
}
await this.storageService.redis.set(cacheKey, JSON.stringify(rateLimits), "EX", 3600);
return rateLimits;
}
private async incrementRateLimit(tracker: string, rateLimit: RateLimitType, response: Response) {
const { name, limit, ttl, blockDuration } = rateLimit;
const key = `${tracker}:${limit}:${ttl}`;
const { isBlocked, totalHits, timeToExpire, timeToBlockExpire } = await this.storageService.increment(
key,
ttl,
limit,
blockDuration,
name
);
const nameFirstUpper = name.charAt(0).toUpperCase() + name.slice(1);
response.setHeader(`X-RateLimit-Limit-${nameFirstUpper}`, limit);
response.setHeader(
`X-RateLimit-Remaining-${nameFirstUpper}`,
timeToBlockExpire ? 0 : Math.max(0, limit - totalHits)
);
response.setHeader(`X-RateLimit-Reset-${nameFirstUpper}`, timeToBlockExpire || timeToExpire);
this.logger.log(
`Tracker "${tracker}" rate limit "${name}" incremented. isBlocked ${isBlocked}, totalHits ${totalHits}, timeToExpire ${timeToExpire}, timeToBlockExpire ${timeToBlockExpire}`
);
this.logger.log(
`Tracker "${tracker}" rate limit "${name}" response headers:
X-RateLimit-Limit-${nameFirstUpper}: ${limit},
X-RateLimit-Remaining-${nameFirstUpper}: ${timeToBlockExpire ? 0 : Math.max(0, limit - totalHits)},
X-RateLimit-Reset-${nameFirstUpper}: ${timeToBlockExpire || timeToExpire}`
);
return { isBlocked };
}
protected async getTracker(request: Request): Promise<string> {
const authorizationHeader = request.get("Authorization")?.replace("Bearer ", "");
if (authorizationHeader) {
return isApiKey(authorizationHeader, this.config.get<string>("api.apiKeyPrefix") ?? "cal_")
? `api_key_${authorizationHeader}`
const apiKeyPrefix = getEnv("API_KEY_PREFIX", "cal_");
return isApiKey(authorizationHeader, apiKeyPrefix)
? `api_key_${hashAPIKey(stripApiKey(authorizationHeader, apiKeyPrefix))}`
: `access_token_${authorizationHeader}`;
}
const oauthClientId = request.get(X_CAL_CLIENT_ID);
if (oauthClientId) {
return oauthClientId;
return `oauth_client_${oauthClientId}`;
}
if (request.ip) {
return request.ip;
return `ip_${request.ip}`;
}
this.logger.log(`no tracker found: ${request.url}`);
+7 -4
View File
@@ -114,11 +114,14 @@ async function generateSwagger(app: NestExpressApplication<Server>) {
}
fs.writeFileSync(outputFile, JSON.stringify(document, null, 2), { encoding: "utf8" });
SwaggerModule.setup("docs", app, document, {
customCss: ".swagger-ui .topbar { display: none }",
});
logger.log(`Swagger documentation available in the "/docs" endpoint\n`);
if (!process.env.DOCS_URL) {
SwaggerModule.setup("docs", app, document, {
customCss: ".swagger-ui .topbar { display: none }",
});
logger.log(`Swagger documentation available in the "/docs" endpoint\n`);
}
}
run().catch((error: Error) => {
@@ -0,0 +1,12 @@
import { Injectable, NestMiddleware } from "@nestjs/common";
import { Request, Response } from "express";
@Injectable()
export class RedirectsMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: () => void) {
if (process.env.DOCS_URL && (req.url.startsWith("/v2/docs") || req.url.startsWith("/docs"))) {
return res.redirect(process.env.DOCS_URL);
}
next();
}
}
@@ -1,7 +1,7 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { App } from "@prisma/client";
import { App, Prisma } from "@prisma/client";
@Injectable()
export class AppsRepository {
@@ -10,4 +10,15 @@ export class AppsRepository {
async getAppBySlug(slug: string): Promise<App | null> {
return await this.dbRead.prisma.app.findUnique({ where: { slug } });
}
async createAppCredential(type: string, key: Prisma.InputJsonValue, userId: number, appId: string) {
return this.dbWrite.prisma.credential.create({
data: {
type: type,
key: key,
userId: userId,
appId: appId,
},
});
}
}
@@ -0,0 +1,24 @@
import { EventTypesModule_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.module";
import { SchedulesRepository_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/schedules.repository";
import { AtomsController } from "@/modules/atoms/controllers/atoms.controller";
import { EventTypesAtomService } from "@/modules/atoms/services/event-types-atom.service";
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
import { OrganizationsModule } from "@/modules/organizations/organizations.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { UsersService } from "@/modules/users/services/users.service";
import { UsersRepository } from "@/modules/users/users.repository";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule, EventTypesModule_2024_06_14, OrganizationsModule],
providers: [
EventTypesAtomService,
MembershipsRepository,
UsersRepository,
UsersService,
SchedulesRepository_2024_06_11,
],
exports: [EventTypesAtomService],
controllers: [AtomsController],
})
export class AtomsModule {}
@@ -0,0 +1,83 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { EventTypesAtomService } from "@/modules/atoms/services/event-types-atom.service";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { UserWithProfile } from "@/modules/users/users.repository";
import {
Controller,
Get,
Param,
ParseIntPipe,
UseGuards,
Version,
VERSION_NEUTRAL,
Patch,
Body,
} from "@nestjs/common";
import { ApiTags as DocsTags, ApiExcludeController as DocsExcludeController } from "@nestjs/swagger";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import type { UpdateEventTypeReturn } from "@calcom/platform-libraries";
import { ApiResponse } from "@calcom/platform-types";
/*
Endpoints used only by platform atoms, reusing code from other modules, data is already formatted and ready to be used by frontend atoms
these endpoints should not be recommended for use by third party and are excluded from docs
*/
@Controller({
path: "/v2/atoms",
version: API_VERSIONS_VALUES,
})
@DocsTags("Atoms - endpoints for atoms")
@DocsExcludeController(true)
export class AtomsController {
constructor(private readonly eventTypesService: EventTypesAtomService) {}
@Get("event-types/:eventTypeId")
@Version(VERSION_NEUTRAL)
@UseGuards(ApiAuthGuard)
async getAtomEventType(
@GetUser() user: UserWithProfile,
@Param("eventTypeId", ParseIntPipe) eventTypeId: number
): Promise<ApiResponse<unknown>> {
const eventType = await this.eventTypesService.getUserEventType(user, eventTypeId);
return {
status: SUCCESS_STATUS,
data: eventType,
};
}
@Patch("event-types/:eventTypeId")
@Version(VERSION_NEUTRAL)
@UseGuards(ApiAuthGuard)
async updateAtomEventType(
@GetUser() user: UserWithProfile,
@Param("eventTypeId", ParseIntPipe) eventTypeId: number,
@Body() body: UpdateEventTypeReturn
): Promise<ApiResponse<UpdateEventTypeReturn>> {
const eventType = await this.eventTypesService.updateEventType(eventTypeId, body, user);
return {
status: SUCCESS_STATUS,
data: eventType,
};
}
@Patch("/organizations/:organizationId/teams/:teamId/event-types/:eventTypeId")
@Version(VERSION_NEUTRAL)
@UseGuards(ApiAuthGuard)
async updateAtomTeamEventType(
@GetUser() user: UserWithProfile,
@Param("eventTypeId", ParseIntPipe) eventTypeId: number,
@Param("teamId", ParseIntPipe) teamId: number,
@Body() body: UpdateEventTypeReturn
): Promise<ApiResponse<UpdateEventTypeReturn>> {
const eventType = await this.eventTypesService.updateTeamEventType(eventTypeId, body, user, teamId);
return {
status: SUCCESS_STATUS,
data: eventType,
};
}
}
@@ -0,0 +1,149 @@
import { EventTypesService_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/services/event-types.service";
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
import { OrganizationsEventTypesService } from "@/modules/organizations/services/event-types/organizations-event-types.service";
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { UsersService } from "@/modules/users/services/users.service";
import { UserWithProfile } from "@/modules/users/users.repository";
import { Injectable, NotFoundException, ForbiddenException } from "@nestjs/common";
import {
updateEventType,
TUpdateEventTypeInputSchema,
systemBeforeFieldEmail,
getEventTypeById,
} from "@calcom/platform-libraries";
import { PrismaClient } from "@calcom/prisma/client";
@Injectable()
export class EventTypesAtomService {
constructor(
private readonly membershipsRepository: MembershipsRepository,
private readonly usersService: UsersService,
private readonly dbWrite: PrismaWriteService,
private readonly dbRead: PrismaReadService,
private readonly eventTypeService: EventTypesService_2024_06_14,
private readonly teamEventTypeService: OrganizationsEventTypesService
) {}
async getUserEventType(user: UserWithProfile, eventTypeId: number) {
const organizationId = this.usersService.getUserMainOrgId(user);
const isUserOrganizationAdmin = organizationId
? await this.membershipsRepository.isUserOrganizationAdmin(user.id, organizationId)
: false;
const eventType = await getEventTypeById({
currentOrganizationId: this.usersService.getUserMainOrgId(user),
eventTypeId,
userId: user.id,
prisma: this.dbRead.prisma as unknown as PrismaClient,
isUserOrganizationAdmin,
isTrpcCall: true,
});
if (!eventType) {
throw new NotFoundException(`Event type with id ${eventTypeId} not found`);
}
if (eventType?.team?.id) {
await this.checkTeamOwnsEventType(user.id, eventType.eventType.id, eventType.team.id);
} else {
this.eventTypeService.checkUserOwnsEventType(user.id, eventType.eventType);
}
return eventType;
}
async updateTeamEventType(
eventTypeId: number,
body: TUpdateEventTypeInputSchema,
user: UserWithProfile,
teamId: number
) {
await this.checkCanUpdateTeamEventType(user.id, eventTypeId, teamId, body.scheduleId);
const eventTypeUser = await this.eventTypeService.getUserToUpdateEvent(user);
const bookingFields = [...(body.bookingFields || [])];
if (
!bookingFields.find((field) => field.type === "email") &&
!bookingFields.find((field) => field.type === "phone")
) {
bookingFields.push(systemBeforeFieldEmail);
}
const eventType = await updateEventType({
input: { id: eventTypeId, ...body, bookingFields },
ctx: {
user: eventTypeUser,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
prisma: this.dbWrite.prisma,
},
});
if (!eventType) {
throw new NotFoundException(`Event type with id ${eventTypeId} not found`);
}
return eventType.eventType;
}
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 || [])];
if (
!bookingFields.find((field) => field.type === "email") &&
!bookingFields.find((field) => field.type === "phone")
) {
bookingFields.push(systemBeforeFieldEmail);
}
const eventType = await updateEventType({
input: { id: eventTypeId, ...body, bookingFields },
ctx: {
user: eventTypeUser,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
prisma: this.dbWrite.prisma,
},
});
if (!eventType) {
throw new NotFoundException(`Event type with id ${eventTypeId} not found`);
}
return eventType.eventType;
}
async checkCanUpdateTeamEventType(userId: number, eventTypeId: number, teamId: number, scheduleId: number) {
await this.checkTeamOwnsEventType(userId, eventTypeId, teamId);
await this.teamEventTypeService.validateEventTypeExists(teamId, eventTypeId);
await this.eventTypeService.checkUserOwnsSchedule(userId, scheduleId);
}
async checkTeamOwnsEventType(userId: number, eventTypeId: number, teamId: number) {
const membership = await this.dbRead.prisma.membership.findFirst({
where: {
userId,
teamId,
accepted: true,
OR: [{ role: "ADMIN" }, { role: "OWNER" }],
},
select: {
team: {
select: {
eventTypes: true,
},
},
},
});
if (!membership?.team?.eventTypes?.some((item) => item.id === eventTypeId)) {
throw new ForbiddenException(
`Access denied. Either the team with ID=${teamId} does not own the event type with ID=${eventTypeId}, or your MEMBER role does not have permission to access this resource.`
);
}
}
}
@@ -1,3 +1,4 @@
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { createMock } from "@golevelup/ts-jest";
import { ExecutionContext } from "@nestjs/common";
@@ -26,7 +27,8 @@ describe("PermissionsGuard", () => {
return null;
}
}),
})
}),
createMock<OAuthClientRepository>()
);
});
@@ -38,7 +40,7 @@ describe("PermissionsGuard", () => {
it("should return false", async () => {
const mockContext = createMockExecutionContext({});
jest.spyOn(reflector, "get").mockReturnValue([SCHEDULE_WRITE]);
jest.spyOn(guard, "getOAuthClientPermissions").mockResolvedValue(0);
jest.spyOn(guard, "getOAuthClientPermissionsByAccessToken").mockResolvedValue(0);
await expect(guard.canActivate(mockContext)).resolves.toBe(false);
});
@@ -51,7 +53,7 @@ describe("PermissionsGuard", () => {
let oAuthClientPermissions = 0;
oAuthClientPermissions |= SCHEDULE_WRITE;
jest.spyOn(guard, "getOAuthClientPermissions").mockResolvedValue(oAuthClientPermissions);
jest.spyOn(guard, "getOAuthClientPermissionsByAccessToken").mockResolvedValue(oAuthClientPermissions);
await expect(guard.canActivate(mockContext)).resolves.toBe(true);
});
@@ -62,7 +64,7 @@ describe("PermissionsGuard", () => {
let oAuthClientPermissions = 0;
oAuthClientPermissions |= SCHEDULE_WRITE;
oAuthClientPermissions |= SCHEDULE_READ;
jest.spyOn(guard, "getOAuthClientPermissions").mockResolvedValue(oAuthClientPermissions);
jest.spyOn(guard, "getOAuthClientPermissionsByAccessToken").mockResolvedValue(oAuthClientPermissions);
await expect(guard.canActivate(mockContext)).resolves.toBe(true);
});
@@ -73,7 +75,7 @@ describe("PermissionsGuard", () => {
let oAuthClientPermissions = 0;
oAuthClientPermissions |= SCHEDULE_WRITE;
jest.spyOn(guard, "getOAuthClientPermissions").mockResolvedValue(oAuthClientPermissions);
jest.spyOn(guard, "getOAuthClientPermissionsByAccessToken").mockResolvedValue(oAuthClientPermissions);
await expect(guard.canActivate(mockContext)).resolves.toBe(true);
});
@@ -83,7 +85,7 @@ describe("PermissionsGuard", () => {
let oAuthClientPermissions = 0;
oAuthClientPermissions |= APPS_WRITE;
jest.spyOn(guard, "getOAuthClientPermissions").mockResolvedValue(oAuthClientPermissions);
jest.spyOn(guard, "getOAuthClientPermissionsByAccessToken").mockResolvedValue(oAuthClientPermissions);
await expect(guard.canActivate(mockContext)).resolves.toBe(false);
});
@@ -94,7 +96,63 @@ describe("PermissionsGuard", () => {
let oAuthClientPermissions = 0;
oAuthClientPermissions |= SCHEDULE_WRITE;
jest.spyOn(guard, "getOAuthClientPermissions").mockResolvedValue(oAuthClientPermissions);
jest.spyOn(guard, "getOAuthClientPermissionsByAccessToken").mockResolvedValue(oAuthClientPermissions);
await expect(guard.canActivate(mockContext)).resolves.toBe(false);
});
});
describe("when oauth id is provided", () => {
it("should return true for valid permissions", async () => {
const mockContext = createMockExecutionContext({ "x-cal-client-id": "100" });
jest.spyOn(reflector, "get").mockReturnValue([SCHEDULE_WRITE]);
let oAuthClientPermissions = 0;
oAuthClientPermissions |= SCHEDULE_WRITE;
jest.spyOn(guard, "getOAuthClientPermissionsById").mockResolvedValue(oAuthClientPermissions);
await expect(guard.canActivate(mockContext)).resolves.toBe(true);
});
it("should return true for multiple valid permissions", async () => {
const mockContext = createMockExecutionContext({ "x-cal-client-id": "100" });
jest.spyOn(reflector, "get").mockReturnValue([SCHEDULE_WRITE, SCHEDULE_READ]);
let oAuthClientPermissions = 0;
oAuthClientPermissions |= SCHEDULE_WRITE;
oAuthClientPermissions |= SCHEDULE_READ;
jest.spyOn(guard, "getOAuthClientPermissionsById").mockResolvedValue(oAuthClientPermissions);
await expect(guard.canActivate(mockContext)).resolves.toBe(true);
});
it("should return true for empty Permissions decorator", async () => {
const mockContext = createMockExecutionContext({ "x-cal-client-id": "100" });
jest.spyOn(reflector, "get").mockReturnValue([]);
let oAuthClientPermissions = 0;
oAuthClientPermissions |= SCHEDULE_WRITE;
jest.spyOn(guard, "getOAuthClientPermissionsById").mockResolvedValue(oAuthClientPermissions);
await expect(guard.canActivate(mockContext)).resolves.toBe(true);
});
it("should return false for invalid permissions", async () => {
const mockContext = createMockExecutionContext({ "x-cal-client-id": "100" });
jest.spyOn(reflector, "get").mockReturnValue([SCHEDULE_WRITE]);
let oAuthClientPermissions = 0;
oAuthClientPermissions |= APPS_WRITE;
jest.spyOn(guard, "getOAuthClientPermissionsById").mockResolvedValue(oAuthClientPermissions);
await expect(guard.canActivate(mockContext)).resolves.toBe(false);
});
it("should return false for a missing permission", async () => {
const mockContext = createMockExecutionContext({ "x-cal-client-id": "100" });
jest.spyOn(reflector, "get").mockReturnValue([SCHEDULE_WRITE, SCHEDULE_READ]);
let oAuthClientPermissions = 0;
oAuthClientPermissions |= SCHEDULE_WRITE;
jest.spyOn(guard, "getOAuthClientPermissionsById").mockResolvedValue(oAuthClientPermissions);
await expect(guard.canActivate(mockContext)).resolves.toBe(false);
});
@@ -1,11 +1,13 @@
import { isApiKey } from "@/lib/api-key";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { Injectable, CanActivate, ExecutionContext } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Reflector } from "@nestjs/core";
import { getToken } from "next-auth/jwt";
import { X_CAL_CLIENT_ID } from "@calcom/platform-constants";
import { hasPermissions } from "@calcom/platform-utils";
@Injectable()
@@ -13,7 +15,8 @@ export class PermissionsGuard implements CanActivate {
constructor(
private reflector: Reflector,
private tokensRepository: TokensRepository,
private readonly config: ConfigService
private readonly config: ConfigService,
private readonly oAuthClientRepository: OAuthClientRepository
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
@@ -27,12 +30,13 @@ export class PermissionsGuard implements CanActivate {
const authString = request.get("Authorization")?.replace("Bearer ", "");
const nextAuthSecret = this.config.get("next.authSecret", { infer: true });
const nextAuthToken = await getToken({ req: request, secret: nextAuthSecret });
const oAuthClientId = request.params?.clientId || request.get(X_CAL_CLIENT_ID);
if (nextAuthToken) {
return true;
}
if (!authString) {
if (!authString && !oAuthClientId) {
return false;
}
@@ -41,7 +45,9 @@ export class PermissionsGuard implements CanActivate {
return true;
}
const oAuthClientPermissions = await this.getOAuthClientPermissions(authString);
const oAuthClientPermissions = authString
? await this.getOAuthClientPermissionsByAccessToken(authString)
: await this.getOAuthClientPermissionsById(oAuthClientId);
if (!oAuthClientPermissions) {
return false;
@@ -50,8 +56,13 @@ export class PermissionsGuard implements CanActivate {
return hasPermissions(oAuthClientPermissions, [...requiredPermissions]);
}
async getOAuthClientPermissions(accessToken: string) {
async getOAuthClientPermissionsByAccessToken(accessToken: string) {
const oAuthClient = await this.tokensRepository.getAccessTokenClient(accessToken);
return oAuthClient?.permissions;
}
async getOAuthClientPermissionsById(id: string) {
const oAuthClient = await this.oAuthClientRepository.getOAuthClient(id);
return oAuthClient?.permissions;
}
}
@@ -68,20 +68,14 @@ export class BillingController {
@Param("teamId") teamId: number,
@Body() input: SubscribeToPlanInput
): Promise<ApiResponse<SubscribeTeamToBillingResponseDto | undefined>> {
const { action, url } = await this.billingService.createSubscriptionForTeam(teamId, input.plan);
if (action === "redirect") {
return {
status: "success",
data: {
action: "redirect",
url,
},
};
}
const customerId = await this.billingService.createTeamBilling(teamId);
const url = await this.billingService.redirectToSubscribeCheckout(teamId, input.plan, customerId);
return {
status: "success",
data: {
url,
},
};
}
@@ -92,20 +86,13 @@ export class BillingController {
@Param("teamId") teamId: number,
@Body() input: SubscribeToPlanInput
): Promise<ApiResponse<SubscribeTeamToBillingResponseDto | undefined>> {
const { action, url } = await this.billingService.updateSubscriptionForTeam(teamId, input.plan);
if (action === "redirect") {
return {
status: "success",
data: {
action: "redirect",
url,
},
};
}
const url = await this.billingService.updateSubscriptionForTeam(teamId, input.plan);
return {
status: "success",
data: {
url,
},
};
}
@@ -47,7 +47,7 @@ export class BillingService implements OnModuleDestroy {
}
}
async createSubscriptionForTeam(teamId: number, plan: PlatformPlan) {
async createTeamBilling(teamId: number) {
const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);
let customerId = teamWithBilling?.platformBilling?.customerId;
@@ -60,6 +60,10 @@ export class BillingService implements OnModuleDestroy {
});
}
return customerId;
}
async redirectToSubscribeCheckout(teamId: number, plan: PlatformPlan, customerId?: string) {
const { url } = await this.stripeService.stripe.checkout.sessions.create({
customer: customerId,
line_items: [
@@ -90,7 +94,7 @@ export class BillingService implements OnModuleDestroy {
if (!url) throw new InternalServerErrorException("Failed to create Stripe session.");
return { action: "redirect", url };
return url;
}
async updateSubscriptionForTeam(teamId: number, plan: PlatformPlan) {
@@ -111,7 +115,7 @@ export class BillingService implements OnModuleDestroy {
if (!url) throw new InternalServerErrorException("Failed to create Stripe session.");
return { action: "redirect", url };
return url;
}
async setSubscriptionForTeam(teamId: number, subscriptionId: string, plan: PlatformPlan) {
@@ -0,0 +1,22 @@
import { ConferencingController } from "@/modules/conferencing/controllers/conferencing.controller";
import { ConferencingRepository } from "@/modules/conferencing/repositories/conferencing.respository";
import { ConferencingService } from "@/modules/conferencing/services/conferencing.service";
import { GoogleMeetService } from "@/modules/conferencing/services/google-meet.service";
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { UsersRepository } from "@/modules/users/users.repository";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule],
providers: [
ConferencingService,
ConferencingRepository,
GoogleMeetService,
CredentialsRepository,
UsersRepository,
],
exports: [],
controllers: [ConferencingController],
})
export class ConferencingModule {}
@@ -0,0 +1,137 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { ConferencingAppsOutputDto } from "@/modules/conferencing/outputs/get-conferencing-apps.output";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
import { INestApplication } from "@nestjs/common";
import { NestExpressApplication } from "@nestjs/platform-express";
import { Test } from "@nestjs/testing";
import { User } from "@prisma/client";
import * as request from "supertest";
import { CredentialsRepositoryFixture } from "test/fixtures/repository/credentials.repository.fixture";
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
import { withApiAuth } from "test/utils/withApiAuth";
import {
ERROR_STATUS,
GOOGLE_CALENDAR_ID,
GOOGLE_CALENDAR_TYPE,
GOOGLE_MEET,
GOOGLE_MEET_TYPE,
SUCCESS_STATUS,
} from "@calcom/platform-constants";
import { ApiErrorResponse, ApiSuccessResponse } from "@calcom/platform-types";
describe("Conferencing Endpoints", () => {
describe("conferencing controller e2e tests", () => {
let app: INestApplication;
let userRepositoryFixture: UserRepositoryFixture;
let credentialsRepositoryFixture: CredentialsRepositoryFixture;
const userEmail = "conferencing-controller-user-e2e@api.com";
let user: User;
beforeAll(async () => {
const moduleRef = await withApiAuth(
userEmail,
Test.createTestingModule({
imports: [AppModule, PrismaModule, UsersModule, TokensModule],
})
).compile();
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
credentialsRepositoryFixture = new CredentialsRepositoryFixture(moduleRef);
user = await userRepositoryFixture.create({
email: userEmail,
username: userEmail,
});
app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication);
await app.init();
});
it("should get all the conferencing apps of the auth user", async () => {
return request(app.getHttpServer())
.get(`/v2/conferencing`)
.expect(200)
.then((response) => {
const responseBody: ApiSuccessResponse<ConferencingAppsOutputDto[]> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toEqual([]);
});
});
it("should fail to connect google meet if google calendar is not connected ", async () => {
return request(app.getHttpServer())
.post(`/v2/conferencing/google-meet/connect`)
.expect(400)
.then(async () => {
await credentialsRepositoryFixture.create(GOOGLE_CALENDAR_TYPE, {}, user.id, GOOGLE_CALENDAR_ID);
});
});
it("should connect google meet if google calendar is connected ", async () => {
return request(app.getHttpServer())
.post(`/v2/conferencing/google-meet/connect`)
.expect(200)
.then((response) => {
const responseBody: ApiSuccessResponse<ConferencingAppsOutputDto[]> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
});
});
it("should set google meet as default conferencing app", async () => {
return request(app.getHttpServer())
.post(`/v2/conferencing/google-meet/default`)
.expect(200)
.then(async () => {
const updatedUser = await userRepositoryFixture.get(user.id);
expect(updatedUser).toBeDefined();
if (updatedUser) {
const metadata = updatedUser.metadata as { defaultConferencingApp?: { appSlug?: string } };
expect(metadata?.defaultConferencingApp?.appSlug).toEqual(GOOGLE_MEET);
}
});
});
it("should get all the conferencing apps of the auth user, and contain google meet", async () => {
return request(app.getHttpServer())
.get(`/v2/conferencing`)
.expect(200)
.then((response) => {
const responseBody: ApiSuccessResponse<ConferencingAppsOutputDto[]> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const googleMeet = responseBody.data.find((app) => app.type === GOOGLE_MEET_TYPE);
expect(googleMeet?.userId).toEqual(user.id);
});
});
it("should disconnect google meet", async () => {
return request(app.getHttpServer()).delete(`/v2/conferencing/google-meet/disconnect`).expect(200);
});
it("should get all the conferencing apps of the auth user, and not contain google meet", async () => {
return request(app.getHttpServer())
.get(`/v2/conferencing`)
.expect(200)
.then((response) => {
const responseBody: ApiSuccessResponse<ConferencingAppsOutputDto[]> = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const googleMeet = responseBody.data.find((app) => app.type === GOOGLE_MEET_TYPE);
expect(googleMeet).toBeUndefined();
});
});
afterAll(async () => {
await userRepositoryFixture.deleteByEmail(user.email);
await app.close();
});
});
});
@@ -0,0 +1,121 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import {
ConferencingAppsOutputResponseDto,
ConferencingAppOutputResponseDto,
ConferencingAppsOutputDto,
} from "@/modules/conferencing/outputs/get-conferencing-apps.output";
import { SetDefaultConferencingAppOutputResponseDto } from "@/modules/conferencing/outputs/set-default-conferencing-app.output";
import { ConferencingService } from "@/modules/conferencing/services/conferencing.service";
import { GoogleMeetService } from "@/modules/conferencing/services/google-meet.service";
import {
Controller,
Get,
HttpCode,
HttpStatus,
Logger,
UseGuards,
Post,
Param,
BadRequestException,
Delete,
} from "@nestjs/common";
import { ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { plainToInstance } from "class-transformer";
import { CONFERENCING_APPS, GOOGLE_MEET, SUCCESS_STATUS } from "@calcom/platform-constants";
@Controller({
path: "/v2/conferencing",
version: API_VERSIONS_VALUES,
})
@DocsTags("Conferencing")
export class ConferencingController {
private readonly logger = new Logger("Platform Gcal Provider");
constructor(
private readonly conferencingService: ConferencingService,
private readonly googleMeetService: GoogleMeetService
) {}
@Post("/:app/connect")
@HttpCode(HttpStatus.OK)
@UseGuards(ApiAuthGuard)
@ApiOperation({ summary: "Connect your conferencing application" })
async connect(
@GetUser("id") userId: number,
@Param("app") app: string
): Promise<ConferencingAppOutputResponseDto> {
switch (app) {
case GOOGLE_MEET:
const credential = await this.googleMeetService.connectGoogleMeetApp(userId);
return { status: SUCCESS_STATUS, data: plainToInstance(ConferencingAppsOutputDto, credential) };
default:
throw new BadRequestException(
"Invalid conferencing app, available apps are: ",
CONFERENCING_APPS.join(", ")
);
}
}
@Get("/")
@HttpCode(HttpStatus.OK)
@UseGuards(ApiAuthGuard)
@ApiOperation({ summary: "List your conferencing applications" })
async listConferencingApps(@GetUser("id") userId: number): Promise<ConferencingAppsOutputResponseDto> {
const conferencingApps = await this.conferencingService.getConferencingApps(userId);
const data = conferencingApps.map((conferencingApps) =>
plainToInstance(ConferencingAppsOutputDto, conferencingApps)
);
return { status: SUCCESS_STATUS, data };
}
@Post("/:app/default")
@HttpCode(HttpStatus.OK)
@UseGuards(ApiAuthGuard)
@ApiOperation({ summary: "Set your default conferencing application" })
async default(
@GetUser("id") userId: number,
@Param("app") app: string
): Promise<SetDefaultConferencingAppOutputResponseDto> {
switch (app) {
case GOOGLE_MEET:
await this.googleMeetService.setDefault(userId);
return { status: SUCCESS_STATUS };
default:
throw new BadRequestException(
"Invalid conferencing app, available apps are: ",
CONFERENCING_APPS.join(", ")
);
}
}
@Delete("/:app/disconnect")
@HttpCode(HttpStatus.OK)
@UseGuards(ApiAuthGuard)
@ApiOperation({ summary: "Disconnect your conferencing application" })
async disconnect(
@GetUser("id") userId: number,
@Param("app") app: string
): Promise<ConferencingAppOutputResponseDto> {
switch (app) {
case GOOGLE_MEET:
const credential = await this.googleMeetService.disconnectGoogleMeetApp(userId);
return { status: SUCCESS_STATUS, data: plainToInstance(ConferencingAppsOutputDto, credential) };
default:
throw new BadRequestException(
"Invalid conferencing app, available apps are: ",
CONFERENCING_APPS.join(", ")
);
}
}
}
@@ -0,0 +1,50 @@
import { ApiProperty } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import { IsString, ValidateNested, IsEnum, IsNumber, IsOptional, IsBoolean } from "class-validator";
import { ERROR_STATUS, GOOGLE_MEET_TYPE, SUCCESS_STATUS } from "@calcom/platform-constants";
export class ConferencingAppsOutputDto {
@Expose()
@IsNumber()
@ApiProperty({ description: "Id of the conferencing app credentials" })
id!: number;
@ApiProperty({ example: GOOGLE_MEET_TYPE, description: "Type of conferencing app" })
@Expose()
@IsString()
type!: string;
@ApiProperty({ description: "Id of the user associated to the conferencing app" })
@Expose()
@IsNumber()
userId!: number;
@ApiProperty({ example: true, description: "Whether if the connection is working or not." })
@Expose()
@IsBoolean()
@IsOptional()
invalid?: boolean | null;
}
export class ConferencingAppsOutputResponseDto {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@Expose()
@ValidateNested()
@Type(() => ConferencingAppsOutputDto)
data!: ConferencingAppsOutputDto[];
}
export class ConferencingAppOutputResponseDto {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@Expose()
@ValidateNested()
@Type(() => ConferencingAppsOutputDto)
data!: ConferencingAppsOutputDto;
}
@@ -0,0 +1,10 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsEnum } from "class-validator";
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
export class SetDefaultConferencingAppOutputResponseDto {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
}
@@ -0,0 +1,25 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { GOOGLE_MEET_TYPE } from "@calcom/platform-constants";
@Injectable()
export class ConferencingRepository {
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
async findConferencingApps(userId: number) {
return this.dbRead.prisma.credential.findMany({
where: {
userId,
type: { endsWith: "_video" },
},
});
}
async findGoogleMeet(userId: number) {
return this.dbRead.prisma.credential.findFirst({
where: { userId, type: GOOGLE_MEET_TYPE },
});
}
}
@@ -0,0 +1,14 @@
import { ConferencingRepository } from "@/modules/conferencing/repositories/conferencing.respository";
import { Logger } from "@nestjs/common";
import { Injectable } from "@nestjs/common";
@Injectable()
export class ConferencingService {
private logger = new Logger("ConferencingService");
constructor(private readonly conferencingRepository: ConferencingRepository) {}
async getConferencingApps(userId: number) {
return this.conferencingRepository.findConferencingApps(userId);
}
}
@@ -0,0 +1,71 @@
import { ConferencingRepository } from "@/modules/conferencing/repositories/conferencing.respository";
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
import { UsersRepository } from "@/modules/users/users.repository";
import { BadRequestException, InternalServerErrorException, Logger } from "@nestjs/common";
import { Injectable } from "@nestjs/common";
import { GOOGLE_CALENDAR_TYPE, GOOGLE_MEET_TYPE, GOOGLE_MEET } from "@calcom/platform-constants";
@Injectable()
export class GoogleMeetService {
private logger = new Logger("GoogleMeetService");
constructor(
private readonly conferencingRepository: ConferencingRepository,
private readonly credentialsRepository: CredentialsRepository,
private readonly usersRepository: UsersRepository
) {}
async connectGoogleMeetApp(userId: number) {
const googleCalendar = await this.credentialsRepository.getByTypeAndUserId(GOOGLE_CALENDAR_TYPE, userId);
if (!googleCalendar) {
throw new BadRequestException("Google Meet app requires a Google Calendar connection");
}
if (googleCalendar.invalid) {
throw new BadRequestException(
"Google Meet app requires a valid Google Calendar connection, please reconnect Google Calendar."
);
}
const googleMeet = await this.conferencingRepository.findGoogleMeet(userId);
if (googleMeet) {
throw new BadRequestException("Google Meet is already connected.");
}
const googleMeetCredential = await this.credentialsRepository.upsertAppCredential(
GOOGLE_MEET_TYPE,
{},
userId
);
return googleMeetCredential;
}
async disconnectGoogleMeetApp(userId: number) {
const googleMeet = await this.conferencingRepository.findGoogleMeet(userId);
if (!googleMeet) {
throw new BadRequestException("Google Meet is not connected.");
}
const googleMeetCredential = await this.credentialsRepository.deleteUserCredentialById(
userId,
googleMeet.id
);
return googleMeetCredential;
}
async setDefault(userId: number) {
const user = await this.usersRepository.setDefaultConferencingApp(userId, GOOGLE_MEET);
const metadata = user.metadata as { defaultConferencingApp?: { appSlug?: string } };
if (metadata?.defaultConferencingApp?.appSlug !== GOOGLE_MEET) {
throw new InternalServerErrorException("Could not set Google Meet as default conferencing app");
}
return true;
}
}
@@ -88,6 +88,12 @@ export class CredentialsRepository {
},
});
}
async deleteUserCredentialById(userId: number, credentialId: number) {
return await this.dbWrite.prisma.credential.delete({
where: { id: credentialId, userId },
});
}
}
export type CredentialsWithUserEmail = Awaited<
@@ -1,7 +1,10 @@
import { PlatformEndpointsModule } from "@/ee/platform-endpoints-module";
import { AtomsModule } from "@/modules/atoms/atoms.module";
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 { StripeModule } from "@/modules/stripe/stripe.module";
import { TimezoneModule } from "@/modules/timezones/timezones.module";
import type { MiddlewareConsumer, NestModule } from "@nestjs/common";
import { Module } from "@nestjs/common";
@@ -18,6 +21,9 @@ import { WebhooksModule } from "./webhooks/webhooks.module";
UsersModule,
WebhooksModule,
DestinationCalendarsModule,
AtomsModule,
StripeModule,
ConferencingModule,
],
})
export class EndpointsModule implements NestModule {
@@ -52,8 +52,6 @@ Second, make sure that the logged in user has organizationId set to pass the Org
version: API_VERSIONS_VALUES,
})
@UseGuards(NextAuthGuard, OrganizationRolesGuard)
@DocsExcludeController(getEnv("NODE_ENV") === "production")
@DocsTags("OAuth - development only")
export class OAuthClientsController {
private readonly logger = new Logger("OAuthClientController");
@@ -25,9 +25,11 @@ import {
import {
ApiTags as DocsTags,
ApiExcludeController as DocsExcludeController,
ApiExcludeEndpoint as DocsExcludeEndpoint,
ApiOperation as DocsOperation,
ApiOkResponse as DocsOkResponse,
ApiBadRequestResponse as DocsBadRequestResponse,
ApiHeader as DocsHeader,
} from "@nestjs/swagger";
import { Response as ExpressResponse } from "express";
@@ -37,8 +39,7 @@ import { SUCCESS_STATUS, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
path: "/v2/oauth/:clientId",
version: API_VERSIONS_VALUES,
})
@DocsExcludeController(getEnv("NODE_ENV") === "production")
@DocsTags("OAuth - development only")
@DocsTags("OAuth")
export class OAuthFlowController {
constructor(
private readonly oauthClientRepository: OAuthClientRepository,
@@ -62,6 +63,7 @@ export class OAuthFlowController {
description:
"Bad request if the OAuth client is not found, if the redirect URI is invalid, or if the user has already authorized the client.",
})
@DocsExcludeEndpoint(getEnv("NODE_ENV") === "production")
async authorize(
@Param("clientId") clientId: string,
@Body() body: OAuthAuthorizeInput,
@@ -108,6 +110,7 @@ export class OAuthFlowController {
description:
"Bad request if the authorization code is missing, invalid, or if the client ID and secret do not match.",
})
@DocsExcludeEndpoint(getEnv("NODE_ENV") === "production")
async exchange(
@Headers("Authorization") authorization: string,
@Param("clientId") clientId: string,
@@ -138,6 +141,12 @@ export class OAuthFlowController {
@Post("/refresh")
@HttpCode(HttpStatus.OK)
@UseGuards(ApiAuthGuard)
@DocsTags("Managed users")
@DocsHeader({
name: X_CAL_SECRET_KEY,
description: "OAuth client secret key.",
required: true,
})
async refreshAccessToken(
@Param("clientId") clientId: string,
@Headers(X_CAL_SECRET_KEY) secretKey: string,
@@ -1,6 +1,8 @@
import { ApiProperty as DocsProperty } from "@nestjs/swagger";
import { IsString } from "class-validator";
export class RefreshTokenInput {
@IsString()
@DocsProperty({ description: "Managed user's refresh token." })
refreshToken!: string;
}
@@ -300,6 +300,7 @@ describe("Organizations Event Types Endpoints", () => {
},
requiresBookerEmailVerification: true,
hideCalendarNotes: true,
hideCalendarEventDetails: true,
lockTimeZoneToggleOnBookingPage: true,
color: {
darkThemeHex: "#292929",
@@ -330,6 +331,7 @@ describe("Organizations Event Types Endpoints", () => {
expect(data.confirmationPolicy).toEqual(body.confirmationPolicy);
expect(data.requiresBookerEmailVerification).toEqual(body.requiresBookerEmailVerification);
expect(data.hideCalendarNotes).toEqual(body.hideCalendarNotes);
expect(data.hideCalendarEventDetails).toEqual(body.hideCalendarEventDetails);
expect(data.lockTimeZoneToggleOnBookingPage).toEqual(body.lockTimeZoneToggleOnBookingPage);
expect(data.color).toEqual(body.color);
@@ -162,6 +162,7 @@ describe("Organizations Team Endpoints", () => {
const responseBody: ApiSuccessResponse<OrgMeTeamOutputDto[]> = response.body;
expect(responseBody.data.find((t) => t.id === teamCreatedViaApi.id)).toBeDefined();
expect(responseBody.data.some((t) => t.accepted)).toBeTruthy();
expect(responseBody.data.find((t) => t.id === teamCreatedViaApi.id)?.role).toBe("OWNER");
});
});
@@ -67,7 +67,7 @@ export class OrganizationsTeamsController {
}
@Get("/me")
@ApiOperation({ summary: "Get team membership for user" })
@ApiOperation({ summary: "Get teams membership for user" })
@Roles("ORG_MEMBER")
@PlatformPlan("ESSENTIALS")
async getMyTeams(
@@ -84,13 +84,14 @@ export class OrganizationsTeamsController {
);
return {
status: SUCCESS_STATUS,
data: teams.map((team) =>
plainToClass(
data: teams.map((team) => {
const me = team.members.find((member) => member.userId === user.id);
return plainToClass(
OrgMeTeamOutputDto,
{ ...team, accepted: team.members.find((member) => member.userId === user.id)?.accepted ?? false },
me ? { ...team, role: me.role, accepted: me.accepted } : team,
{ strategy: "excludeAll" }
)
),
);
}),
};
}
@@ -76,4 +76,8 @@ export class UpdateOrgTeamDto {
@IsOptional()
@IsString()
readonly bookingLimits?: string;
@IsOptional()
@IsBoolean()
readonly includeManagedEventsInLimits?: boolean;
}
@@ -100,6 +100,7 @@ import { Module } from "@nestjs/common";
OrganizationsWebhooksService,
WebhooksRepository,
WebhooksService,
OrganizationsEventTypesService,
],
controllers: [
OrganizationsTeamsController,
@@ -1,4 +1,5 @@
import { ApiProperty } from "@nestjs/swagger";
import { MembershipRole } from "@prisma/client";
import { Expose, Type } from "class-transformer";
import { IsEnum, IsString, ValidateNested } from "class-validator";
@@ -9,6 +10,14 @@ export class OrgMeTeamOutputDto extends OrgTeamOutputDto {
@IsString()
@Expose()
readonly accepted!: boolean;
@ApiProperty({
example: MembershipRole.MEMBER,
enum: [MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER],
})
@IsEnum([MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER])
@Expose()
readonly role!: MembershipRole;
}
export class OrgTeamsOutputResponseDto {
@@ -97,7 +97,7 @@ export class OrganizationsTeamsRepository {
},
},
include: {
members: { select: { accepted: true, userId: true } },
members: { select: { accepted: true, userId: true, role: true } },
},
skip,
take,
@@ -65,6 +65,7 @@ type Input = Pick<
| "requiresConfirmationWillBlockSlot"
| "eventName"
| "useEventTypeDestinationCalendarEmail"
| "hideCalendarEventDetails"
>;
@Injectable()
@@ -1,7 +1,7 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { SlotsService } from "@/modules/slots/services/slots.service";
import { Query, Body, Controller, Get, Delete, Post, Req, Res } from "@nestjs/common";
import { ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { ApiTags as DocsTags, ApiCreatedResponse, ApiOkResponse, ApiOperation } from "@nestjs/swagger";
import { Response as ExpressResponse, Request as ExpressRequest } from "express";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
@@ -19,6 +19,21 @@ export class SlotsController {
constructor(private readonly slotsService: SlotsService) {}
@Post("/reserve")
@ApiCreatedResponse({
description: "Successful response returning uid of reserved slot.",
schema: {
type: "object",
properties: {
status: { type: "string", example: "success" },
data: {
type: "object",
properties: {
uid: { type: "string", example: "e2a7bcf9-cc7b-40a0-80d3-657d391775a6" },
},
},
},
},
})
@ApiOperation({ summary: "Reserve a slot" })
async reserveSlot(
@Body() body: ReserveSlotInput,
@@ -35,6 +50,15 @@ export class SlotsController {
}
@Delete("/selected-slot")
@ApiOkResponse({
description: "Response deleting reserved slot by uid.",
schema: {
type: "object",
properties: {
status: { type: "string", example: "success" },
},
},
})
@ApiOperation({ summary: "Delete a selected slot" })
async deleteSelectedSlot(
@Query() params: RemoveSelectedSlotInput,
@@ -50,6 +74,45 @@ export class SlotsController {
}
@Get("/available")
@ApiOkResponse({
description: "Available time slots retrieved successfully",
schema: {
type: "object",
properties: {
status: { type: "string", example: "success" },
data: {
type: "object",
properties: {
slots: {
type: "object",
additionalProperties: {
type: "array",
items: {
type: "object",
properties: {
time: { type: "string", format: "date-time", example: "2024-09-25T08:00:00.000Z" },
},
},
},
},
},
},
},
example: {
status: "success",
data: {
slots: {
"2024-09-25": [{ time: "2024-09-25T08:00:00.000Z" }, { time: "2024-09-25T08:15:00.000Z" }],
"2024-09-26": [
{ time: "2024-09-26T08:00:00.000Z" },
{ time: "2024-09-26T08:15:00.000Z" },
{ time: "2024-09-26T08:30:00.000Z" },
],
},
},
},
},
})
@ApiOperation({ summary: "Get available slots" })
async getAvailableSlots(
@Query() query: GetAvailableSlotsInput,
@@ -0,0 +1,104 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import {
StripConnectOutputDto,
StripConnectOutputResponseDto,
StripCredentialsCheckOutputResponseDto,
StripCredentialsSaveOutputResponseDto,
} from "@/modules/stripe/outputs/stripe.output";
import { StripeService } from "@/modules/stripe/stripe.service";
import { getOnErrorReturnToValueFromQueryState } from "@/modules/stripe/utils/getReturnToValueFromQueryState";
import { UserWithProfile } from "@/modules/users/users.repository";
import {
Controller,
Query,
UseGuards,
Get,
HttpCode,
HttpStatus,
Redirect,
Req,
BadRequestException,
Headers,
} from "@nestjs/common";
import { ApiTags as DocsTags, ApiOperation } from "@nestjs/swagger";
import { plainToClass } from "class-transformer";
import { Request } from "express";
import { stringify } from "querystring";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
@Controller({
path: "/v2/stripe",
version: API_VERSIONS_VALUES,
})
@DocsTags("Stripe")
export class StripeController {
constructor(private readonly stripeService: StripeService) {}
@Get("/connect")
@UseGuards(ApiAuthGuard)
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: "Get stripe connect URL" })
async redirect(
@Req() req: Request,
@Headers("Authorization") authorization: string,
@GetUser() user: UserWithProfile,
@Query("redir") redir?: string | null,
@Query("errorRedir") errorRedir?: string | null
): Promise<StripConnectOutputResponseDto> {
const origin = req.headers.origin;
const accessToken = authorization.replace("Bearer ", "");
const state = {
onErrorReturnTo: !!errorRedir ? errorRedir : origin,
fromApp: false,
returnTo: !!redir ? redir : origin,
accessToken,
};
const stripeRedirectUrl = await this.stripeService.getStripeRedirectUrl(
JSON.stringify(state),
user.email,
user.name
);
return {
status: SUCCESS_STATUS,
data: plainToClass(StripConnectOutputDto, { authUrl: stripeRedirectUrl }, { strategy: "excludeAll" }),
};
}
@Get("/save")
@UseGuards()
@Redirect(undefined, 301)
@ApiOperation({ summary: "Save stripe credentials" })
async save(
@Query("state") state: string,
@Query("code") code: string,
@Query("error") error: string | undefined,
@Query("error_description") error_description: string | undefined
): Promise<StripCredentialsSaveOutputResponseDto> {
const accessToken = JSON.parse(state).accessToken;
// user cancels flow
if (error === "access_denied") {
return { url: getOnErrorReturnToValueFromQueryState(state) };
}
if (error) {
throw new BadRequestException(stringify({ error, error_description }));
}
return await this.stripeService.saveStripeAccount(state, code, accessToken);
}
@Get("/check")
@UseGuards(ApiAuthGuard)
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: "Check stripe connection" })
async check(@GetUser() user: UserWithProfile): Promise<StripCredentialsCheckOutputResponseDto> {
return await this.stripeService.checkIfStripeAccountConnected(user.id);
}
}
@@ -0,0 +1,7 @@
import { IsString, IsOptional } from "class-validator";
export class StripeConnectQueryParamsInputDto {
@IsString()
@IsOptional()
readonly redir?: string;
}
@@ -0,0 +1,33 @@
import { ApiProperty } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import { IsString, ValidateNested, IsEnum } from "class-validator";
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
export class StripConnectOutputDto {
@IsString()
@Expose()
readonly authUrl!: string;
}
export class StripConnectOutputResponseDto {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@Expose()
@ValidateNested()
@Type(() => StripConnectOutputDto)
data!: StripConnectOutputDto;
}
export class StripCredentialsCheckOutputResponseDto {
@ApiProperty({ example: SUCCESS_STATUS })
status!: typeof SUCCESS_STATUS;
}
export class StripCredentialsSaveOutputResponseDto {
@IsString()
@Expose()
readonly url!: string;
}
@@ -1,10 +1,16 @@
import { AppsRepository } from "@/modules/apps/apps.repository";
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { StripeController } from "@/modules/stripe/controllers/stripe.controller";
import { StripeService } from "@/modules/stripe/stripe.service";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
@Module({
imports: [ConfigModule],
imports: [ConfigModule, PrismaModule],
exports: [StripeService],
providers: [StripeService],
providers: [StripeService, AppsRepository, CredentialsRepository, TokensRepository],
controllers: [StripeController],
})
export class StripeModule {}
@@ -1,15 +1,130 @@
import { AppConfig } from "@/config/type";
import { Injectable } from "@nestjs/common";
import { AppsRepository } from "@/modules/apps/apps.repository";
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
import { getReturnToValueFromQueryState } from "@/modules/stripe/utils/getReturnToValueFromQueryState";
import { stripeInstance } from "@/modules/stripe/utils/newStripeInstance";
import { StripeData } from "@/modules/stripe/utils/stripeDataSchemas";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { Injectable, NotFoundException, BadRequestException, UnauthorizedException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import type { Prisma } from "@prisma/client";
import Stripe from "stripe";
import { z } from "zod";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { stripeKeysResponseSchema } from "./utils/stripeDataSchemas";
import stringify = require("qs-stringify");
@Injectable()
export class StripeService {
public stripe: Stripe;
private redirectUri = `${this.config.get("api.url")}/stripe/save`;
constructor(configService: ConfigService<AppConfig>) {
constructor(
configService: ConfigService<AppConfig>,
private readonly config: ConfigService,
private readonly appsRepository: AppsRepository,
private readonly credentialRepository: CredentialsRepository,
private readonly tokensRepository: TokensRepository
) {
this.stripe = new Stripe(configService.get("stripe.apiKey", { infer: true }) ?? "", {
apiVersion: "2020-08-27",
});
}
async getStripeRedirectUrl(state: string, userEmail?: string, userName?: string | null) {
const { client_id } = await this.getStripeAppKeys();
const stripeConnectParams: Stripe.OAuthAuthorizeUrlParams = {
client_id,
scope: "read_write",
response_type: "code",
stripe_user: {
email: userEmail,
first_name: userName || undefined,
/** We need this so E2E don't fail for international users */
country: process.env.NEXT_PUBLIC_IS_E2E ? "US" : undefined,
},
redirect_uri: this.redirectUri,
state: state,
};
const params = z.record(z.any()).parse(stripeConnectParams);
const query = stringify(params);
const url = `https://connect.stripe.com/oauth/authorize?${query}`;
return url;
}
async getStripeAppKeys() {
const app = await this.appsRepository.getAppBySlug("stripe");
const { client_id, client_secret } = stripeKeysResponseSchema.parse(app?.keys);
if (!client_id) {
throw new NotFoundException("Stripe app not found");
}
if (!client_secret) {
throw new NotFoundException("Stripe app not found");
}
return { client_id, client_secret };
}
async saveStripeAccount(state: string, code: string, accessToken: string): Promise<{ url: string }> {
const userId = await this.tokensRepository.getAccessTokenOwnerId(accessToken);
if (!userId) {
throw new UnauthorizedException("Invalid Access token.");
}
const response = await stripeInstance.oauth.token({
grant_type: "authorization_code",
code: code?.toString(),
});
const data: StripeData = { ...response, default_currency: "" };
if (response["stripe_user_id"]) {
const account = await stripeInstance.accounts.retrieve(response["stripe_user_id"]);
data["default_currency"] = account.default_currency;
}
await this.appsRepository.createAppCredential(
"stripe_payment",
data as unknown as Prisma.InputJsonObject,
userId,
"stripe"
);
return { url: getReturnToValueFromQueryState(state) };
}
async checkIfStripeAccountConnected(userId: number): Promise<{ status: typeof SUCCESS_STATUS }> {
const stripeCredentials = await this.credentialRepository.getByTypeAndUserId("stripe_payment", userId);
if (!stripeCredentials) {
throw new NotFoundException("Credentials for stripe not found.");
}
if (stripeCredentials.invalid) {
throw new BadRequestException("Invalid stripe credentials.");
}
const stripeKey = JSON.stringify(stripeCredentials.key);
const stripeKeyObject = JSON.parse(stripeKey);
const stripeAccount = await stripeInstance.accounts.retrieve(stripeKeyObject?.stripe_user_id);
// both of these should be true for an account to be fully active
if (!stripeAccount.payouts_enabled || !stripeAccount.charges_enabled) {
throw new BadRequestException("Stripe account is not an active account");
}
return {
status: SUCCESS_STATUS,
};
}
}
@@ -0,0 +1,19 @@
export const getReturnToValueFromQueryState = (queryState: string | string[] | undefined) => {
let returnTo = "";
try {
returnTo = JSON.parse(`${queryState}`).returnTo;
} catch (error) {
console.info("No 'returnTo' in req.query.state");
}
return returnTo;
};
export const getOnErrorReturnToValueFromQueryState = (queryState: string | string[] | undefined) => {
let returnTo = "";
try {
returnTo = JSON.parse(`${queryState}`).onErrorReturnTo;
} catch (error) {
console.info("No 'onErrorReturnTo' in req.query.state");
}
return returnTo;
};
@@ -0,0 +1,6 @@
import Stripe from "stripe";
const stripeApiKey = process.env.STRIPE_API_KEY || "";
export const stripeInstance = new Stripe(stripeApiKey, {
apiVersion: "2020-08-27",
});
@@ -0,0 +1,24 @@
import { z } from "zod";
export const stripeOAuthTokenSchema = z.object({
access_token: z.string().optional(),
scope: z.string().optional(),
livemode: z.boolean().optional(),
token_type: z.literal("bearer").optional(),
refresh_token: z.string().optional(),
stripe_user_id: z.string().optional(),
stripe_publishable_key: z.string().optional(),
});
export const stripeDataSchema = stripeOAuthTokenSchema.extend({
default_currency: z.string(),
});
export type StripeData = z.infer<typeof stripeDataSchema>;
export const stripeKeysResponseSchema = z.object({
client_id: z.string().startsWith("ca_").min(1),
client_secret: z.string().startsWith("sk_").min(1),
public_key: z.string().startsWith("pk_").min(1),
webhook_secret: z.string().startsWith("whsec_").min(1),
});
@@ -2,7 +2,7 @@ import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { CreateManagedUserInput } from "@/modules/users/inputs/create-managed-user.input";
import { UpdateManagedUserInput } from "@/modules/users/inputs/update-managed-user.input";
import { Injectable } from "@nestjs/common";
import { Injectable, NotFoundException } from "@nestjs/common";
import type { Profile, User, Team } from "@prisma/client";
export type UserWithProfile = User & {
@@ -223,4 +223,29 @@ export class UsersRepository {
});
return profiles.map((profile) => profile.user);
}
async setDefaultConferencingApp(userId: number, appSlug?: string, appLink?: string) {
const user = await this.findById(userId);
if (!user) {
throw new NotFoundException("user not found");
}
return await this.dbWrite.prisma.user.update({
data: {
metadata:
typeof user.metadata === "object"
? {
...user.metadata,
defaultConferencingApp: {
appSlug: appSlug,
appLink: appLink,
},
}
: {},
},
where: { id: userId },
});
}
}
@@ -3,12 +3,12 @@ import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repo
import { UsersService } from "@/modules/users/services/users.service";
import { WebhooksService } from "@/modules/webhooks/services/webhooks.service";
import {
BadRequestException,
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
NotFoundException,
ForbiddenException,
BadRequestException,
} from "@nestjs/common";
import { Request } from "express";
@@ -39,14 +39,10 @@ export class IsOAuthClientWebhookGuard implements CanActivate {
throw new BadRequestException("webhookId parameter not specified in the request");
}
if (!webhookId) {
if (!oAuthClientId) {
throw new BadRequestException("oAuthClientId parameter not specified in the request");
}
if (!user || !webhookId || !oAuthClientId) {
return false;
}
const oAuthClient = await this.oAuthClientRepository.getOAuthClient(oAuthClientId);
if (!oAuthClient) {
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,22 @@
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { TestingModule } from "@nestjs/testing";
export class RateLimitRepositoryFixture {
private dbWrite: PrismaWriteService["prisma"];
constructor(private readonly module: TestingModule) {
this.dbWrite = module.get(PrismaWriteService).prisma;
}
async createRateLimit(name: string, apiKeyId: string, ttl: number, limit: number, blockDuration: number) {
return await this.dbWrite.rateLimit.create({
data: {
name,
apiKeyId,
ttl,
limit,
blockDuration,
},
});
}
}
+4
View File
@@ -16,6 +16,10 @@ const env: Partial<Omit<Environment, "NODE_ENV">> = {
API_KEY_PREFIX: "cal_test_",
GET_LICENSE_KEY_URL: " https://console.cal.com/api/license",
CALCOM_LICENSE_KEY: "c4234812-12ab-42s6-a1e3-55bedd4a5bb7",
RATE_LIMIT_DEFAULT_TTL_MS: 60000,
// note(Lauris): setting high limit so that e2e tests themselves are not rate limited
RATE_LIMIT_DEFAULT_LIMIT: 10000,
RATE_LIMIT_DEFAULT_BLOCK_DURATION_MS: 60000,
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
+1 -1
View File
@@ -24,7 +24,7 @@
"@storybook/blocks": "^7.6.3",
"@storybook/nextjs": "^7.6.3",
"@storybook/preview-api": "^7.6.3",
"next": "^13.5.4",
"next": "^13.5.6",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"storybook-addon-rtl-direction": "^0.0.19"
+1 -1
View File
@@ -14,7 +14,7 @@
"dependencies": {
"highlight.js": "^11.6.0",
"isarray": "2.0.5",
"next": "^13.5.4",
"next": "^13.5.6",
"openapi-snippet": "^0.13.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
+1 -1
View File
@@ -8,8 +8,8 @@ import { FUTURE_ROUTES_ENABLED_COOKIE_NAME, FUTURE_ROUTES_OVERRIDE_COOKIE_NAME }
const ROUTES: [URLPattern, boolean][] = [
["/event-types", process.env.APP_ROUTER_EVENT_TYPES_ENABLED === "1"] as const,
["/settings/developer/:path*", process.env.APP_ROUTER_SETTINGS_DEVELOPER_ENABLED === "1"] as const,
["/settings/security/:path*", process.env.APP_ROUTER_SETTINGS_SECURITY_ENABLED === "1"] as const,
["/settings/admin/:path*", process.env.APP_ROUTER_SETTINGS_ADMIN_ENABLED === "1"] as const,
["/settings/my-account/:path*", process.env.APP_ROUTER_SETTINGS_MY_ACCOUNT_ENABLED === "1"] as const,
["/settings/platform/:path*", process.env.APP_ROUTER_SETTINGS_PLATFORM_ENABLED === "1"] as const,
["/settings/organizations/:path*", process.env.APP_ROUTER_SETTINGS_ORG_ENABLED === "1"] as const,
["/apps/installed/:category", process.env.APP_ROUTER_APPS_INSTALLED_CATEGORY_ENABLED === "1"] as const,
-3
View File
@@ -21,8 +21,5 @@ export const withAppDirSsr =
...("trpcState" in props && {
dehydratedState: props.trpcState,
}),
...("isInfiniteScrollEnabled" in props && {
isInfiniteScrollEnabled: props.isInfiniteScrollEnabled,
}),
};
};
@@ -27,12 +27,12 @@ export const generateMetadata = async ({ params, searchParams }: PageProps) => {
const legacyContext = buildLegacyCtx(headers(), cookies(), params, searchParams);
const data = await getData(legacyContext);
const form = "form" in data ? (data.form as { name?: string; description?: string }) : null;
const formName = form?.name ?? "Routing Forms";
const formDescription = form?.description ?? "";
const formName = form?.name;
const formDescription = form?.description;
return await _generateMetadata(
() => formName,
() => formDescription
(t) => formName ?? t("routing_forms"),
(t) => formDescription ?? t("routing_forms_description")
);
};
@@ -11,8 +11,8 @@ import CategoryPage, { type PageProps } from "~/apps/categories/[category]/categ
export const generateMetadata = async () => {
return await _generateMetadata(
() => "Apps Store",
() => "Connecting people, technology and the workplace."
(t) => t("app_store"),
(t) => t("app_store_description")
);
};
+2 -2
View File
@@ -8,8 +8,8 @@ import Page from "~/apps/categories/categories-view";
export const generateMetadata = async () => {
return await _generateMetadata(
() => "Apps Store",
() => "Connecting people, technology and the workplace."
(t) => t("app_store"),
(t) => t("app_store_description")
);
};
@@ -12,8 +12,8 @@ const getData = withAppDirSsg<Y>(getStaticProps);
export const generateMetadata = async () =>
await _generateMetadata(
() => "Bookings",
() => "Create events to share for people to book on your calendar."
(t) => t("bookings"),
(t) => t("bookings_description")
);
export const generateStaticParams = async () => {
+1 -1
View File
@@ -9,7 +9,7 @@ import InsightsPage from "~/insights/insights-view";
export const generateMetadata = async () =>
await _generateMetadata(
() => "Insights",
(t) => t("insights"),
(t) => t("insights_subtitle")
);
@@ -5,8 +5,8 @@ import PlatformView from "~/settings/platform/platform-view";
export const generateMetadata = async () => {
return await _generateMetadata(
() => "Platform",
() => "Manage everything related to platform."
(t) => t("platform"),
(t) => t("platform_description")
);
};
+1
View File
@@ -67,6 +67,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
lang={locale}
dir={direction}
style={embedColorScheme ? { colorScheme: embedColorScheme as string } : undefined}
suppressHydrationWarning
data-nextjs-router="app">
<head nonce={nonce}>
{!!process.env.NEXT_PUBLIC_HEAD_SCRIPTS && (
+1 -1
View File
@@ -51,7 +51,7 @@ export function WithLayout<T extends Record<string, any>>({
requiresLicense={requiresLicense || !!(Page && "requiresLicense" in Page && Page.requiresLicense)}
nonce={nonce}
themeBasis={null}
isThemeSupported={!!(Page && "isThemeSupported" in Page && Page.isThemeSupported)}
isThemeSupported={Page && "isThemeSupported" in Page ? (Page.isThemeSupported as boolean) : undefined}
isBookingPage={isBookingPage || !!(Page && "isBookingPage" in Page && Page.isBookingPage)}
{...props}>
{pageWithServerLayout}
@@ -0,0 +1,5 @@
import { WithLayout } from "app/layoutHOC";
import { getLayout } from "@calcom/features/settings/appDir/SettingsLayoutAppDir";
export default WithLayout({ getServerLayout: getLayout })<"L">;
@@ -1,5 +1,6 @@
import { _generateMetadata } from "app/_utils";
import { getFixedT } from "app/_utils";
import { revalidatePath } from "next/cache";
import { getServerSessionForAppDir } from "@calcom/feature-auth/lib/get-server-session-for-app-dir";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
@@ -16,9 +17,14 @@ const Page = async () => {
const session = await getServerSessionForAppDir();
const t = await getFixedT(session?.user.locale || "en");
const revalidatePage = async () => {
"use server";
revalidatePath("settings/my-account/general");
};
return (
<SettingsHeader title={t("general")} description={t("general_description")} borderInShellHeader={true}>
<GeneralQueryView />
<GeneralQueryView revalidatePage={revalidatePage} />
</SettingsHeader>
);
};

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