Compare commits

...
128 Commits
Author SHA1 Message Date
Omar López 87d2ec9e75 chore: v4.2.0 (#15482)
release.yml / release (push) Canceled after 0s
* v4.1.13

* Update package.json
2024-06-18 19:42:25 +00:00
Rushikeshandsean-brydon 226686d4dd fix: Large padding on small screens for embedded booking widgets (#15463)
* fix: large padding on small screens for embedded booking widgets

* removed unused

* cssConflict - 'border-booker-width' applies the same CSS properties as 'border'.

---------

Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
2024-06-18 10:35:22 +00:00
Rajiv SahalandRajiv Sahal 518ab82e3b shift pencil icon after input to make it wider (#15460)
Co-authored-by: Rajiv Sahal <rajivsahal@Rajivs-MacBook-Pro.local>
2024-06-18 08:25:18 +00:00
Peer Richelsen 532b78a9b3 added empty screen for missing platform plan (#15467) 2024-06-18 07:37:48 +00:00
1251091300 fix: Offer seats events invites everyone regardless their availability schedule (#15171)
* fix: Offer seats events invites everyone regardless their availibility schedule

* chore: add test

* uncomment

* remove timeout

* only check when first seat

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
2024-06-17 15:30:41 +00:00
Rajdeep Das ce1459011a fix: unexpected scrolling on event-types page (#15452) 2024-06-17 14:25:23 +00:00
Joe Au-YeungandUdit Takkar e1bdac077a fix: Seat Attendee Rescheduling Logic (#14784)
* When rescheduling to new time slot don't trigger reschedule logic

* Add unique iCalUID when rescheduling to new slot

* Generating iCalUID use v4 uuid

* When moving an attendee to a new booking. Only move the attendee

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-06-15 08:57:52 +00:00
Vikas PatilandHariom d666f2926c feat: umami app added (#14783)
Co-authored-by: Hariom <hariombalhara@gmail.com>
2024-06-14 13:42:14 +00:00
Vikas PatilandPeer Richelsen 745f0b0872 feat: twipla app added (#14780)
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2024-06-14 12:34:59 +00:00
65f50e9f25 chore: return accessTokenExpiresAt in oauth exchange and refresh (#15425)
* chore: return accessTokenExpiresAt in oauth exchange and refresh

* fixup! chore: return accessTokenExpiresAt in oauth exchange and refresh

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Morgan Vernay <morgan@cal.com>
2024-06-14 11:25:27 +00:00
Alex van Andel 54162f8568 chore: Release v4.1.12 (#15432)
release.yml / release (push) Canceled after 0s
2024-06-13 22:42:18 +00:00
sean-brydon 0f4b9b2a6e fix (#15431) 2024-06-13 22:18:36 +00:00
Alex van AndelandJack W 70b4e3a9c6 Use "standalone" output to build Next.js as a standalone app when being built e.g. in Docker. (#15405)
Co-authored-by: Jack W <jackweatherilt@outlook.com>
2024-06-13 14:44:49 +00:00
ab44d5b92c add zod.ts for google meet (#15203)
Co-authored-by: Shaik-Sirajuddin <sirajudddinshaik30@gmail.com>
Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com>
2024-06-13 14:00:57 +00:00
Peer Richelsen bed08c1e4f Update semantic-pull-requests.yml (#15421) 2024-06-13 14:00:44 +00:00
Alex van Andel 1e0f7f433f chore: Upgrade Sentry in v1, v2 & web (#15396)
* chore: Upgrade Sentry in v1, v2 & web

* fix: Keep ./instrument to be the first line

* Remove eslint-plugin-import (fixed in prettier)

* Optimistic removal pending some feedback

* Simplified and fixed sentry wrapper

* Create instrumentation.ts also in APIv1

* sentry key in main nextConfig is deprecated
2024-06-13 14:00:27 +00:00
Udit Takkar 0cc7a9fc22 refactor: recording and transcript webhook (#15419)
* refactor: recording and transcript webhook

* refactor: improve code and test
2024-06-13 13:59:57 +00:00
b03b878199 fix: reschedule and cancel unconfirmed event from email (#15013)
Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-06-13 09:09:24 +00:00
7a560cf09b chore: added platform admin to seed.ts (#15119)
* initial commit for platform seed

* seed platform team

* fix type checks

* refactors

* fix merge conflicts

* add seed for setting up platform user and team

* fixup

---------

Co-authored-by: Rajiv Sahal <rajivsahal@Rajivs-MacBook-Pro.local>
Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
2024-06-13 06:53:37 +00:00
Hariom Balhara 58ad441223 fix: margin top in booker embed (#15412) 2024-06-12 14:08:04 +00:00
Alex van Andel d8de919acb Revert "fix: bookings made via API don't include the specified location (#15067)" (#15417)
This reverts commit 219b13d053.
2024-06-12 12:34:56 +00:00
Lauris Skraucis d699b33dcb chore: v2 managed user inform when access token expires (#15414) 2024-06-12 09:05:35 +00:00
Alex van Andel c071df4cd6 release: v4.1.11 (#15406)
release.yml / release (push) Canceled after 0s
2024-06-11 18:23:09 +00:00
219b13d053 fix: bookings made via API don't include the specified location (#15067)
* fix booking via api not picking default location when unspecified

* test:add tests for default location of event for booking

* fix:failing tests

---------

Co-authored-by: Shaik-Sirajuddin <sirajudddinshaik30@gmail.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-06-11 17:06:43 +00:00
Pranav RajveerandPeer Richelsen 5e09281974 fix: fixed the padding at the footer in /signup (#15394)
* fixed the padding at the footer in /signup

* reverted /auth/login Link style to original

* Update apps/web/pages/signup.tsx

---------

Co-authored-by: Peer Richelsen <peer@cal.com>
2024-06-11 16:45:11 +00:00
Udit TakkarandJoe Au-Yeung b66d36a98e feat: generate transcription from recording and API endpoint (#15358)
* feat: generate transcription from recording

* fix: api

* chore: undo

* tests: add unit tests

* chore: refactor move zod type

* fix: add more security check

* chore: update test

* chore: type err

* chore: test

* chore: fix tyoe

* fix: build err

* chore: add try .. catch

* chore: update desc

---------

Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
2024-06-11 15:41:56 +00:00
Lauris Skraucis 68ce9524eb refactor: v2 schedules (#15403)
* refactor: platform-types schedule types

* refactor: lib add bidirectional schedule transformers api <-> atom

* refactor: trpc handlers use renamed lib transformers

* refactor: platform-libraries export new bi-directional transformers

* chore: v2 update platform-libraries

* chore: enable also old platform-libraries

* fix: platform-types support previous types

* refactor: versioning date

* chore: version old schedules as schedules_2024_04_15 module

* chore: version old schedules as schedules_2024_04_15 module

* feat: new 2024_06_11 schedules module

* feat: atoms use refactored schedule api

* refactor: remove ?for=atom in schedules hooks

* fix: unit test
2024-06-11 14:35:53 +00:00
Morgan 357a42b512 fix: atoms useCheck and bump atoms version (#15390) 2024-06-11 13:38:39 +00:00
33d7da88bf feat: go to Assignment tab after creation and warn if existing without assigning (#14882)
* feat: go to Assignment tab after creation and warn if existing without assigning

* Update AssignmentWarningDialog.tsx

* fix: some changes

* fix: some updates

* Update EventTeamTab.tsx

* update

* update

* update test

* some fixes

* refactor one test and update

* Update managed-event-types.e2e.ts

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: Lauris Skraucis <lauris.skraucis@gmail.com>
2024-06-11 09:27:07 +00:00
Martin Sione cd888be61e feat: Add VariableNode and AddVariablesPlugin (#15293) 2024-06-10 13:46:50 +00:00
Joe Au-Yeung 06231ec299 Add better error logging (#15383) 2024-06-10 10:10:19 +00:00
sean-brydonandUdit Takkar e38705c3e8 add missing migration (#15369)
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-06-08 14:20:25 +00:00
Hichem FantarandUdit Takkar 5c95268d1a feat: Datepicker transitions (#15313)
* fix: Kbar component styles

Fix Kbar styles on active state

* refactor: Add transition to event type list item

The commit refactors the event type list item component by adding a transition effect to improve the user experience.

* refactor: Add transition effect to DatePicker component

Add transition effect to improve the user experience in the DatePicker component.

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-06-08 14:05:49 +00:00
Kartik Saini b310eb1a7e feat: Remove minimum of 2 teams for making an Org (#15267)
* feat: Remove min of 2 teams for making an Org

* Set ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE to 0
2024-06-07 14:30:36 +00:00
051510fa36 fix sidebar height not growing (#15223)
Co-authored-by: Rajiv Sahal <rajivsahal@Rajivs-MacBook-Pro.local>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2024-06-07 10:19:07 +00:00
Peer Richelsen 7d1226b823 Delete apps/web/public/.well-known directory (#15362) 2024-06-06 19:59:15 +00:00
Morgan 7732a22c49 fix: event-types controller params validation (#15353) 2024-06-06 19:58:46 +00:00
sean-brydonandPeer Richelsen 2a41cd0770 feat: license creation admin PR (#15024)
* WIP: UI created to see if it matches RFC idea

* Remove schema as we validate on the backend with old+new key schemas

* Add comment about proxy URL request when on older versions

* feat: create custom axios instance to use signature middleware

* fix: update form to respect new schema

* Add cal signature token to trubo env

* use backend mutation for creating license keys

* add loading state to creation button

* update form to have a success state

* fix type error for console.warning :')

* use api version v1

* restore checkLicense from main

* Add env vars to example

* nit: rename page export

* use US spelling

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2024-06-06 18:34:32 +00:00
a574e5e60f fix: trigger workflow only for first recurring event (#15128)
* fix isFirstRecurringEvent param

* code clean up

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
2024-06-06 18:34:17 +00:00
Keith Williams 0b6508379b v4.1.10 (#15359)
release.yml / release (push) Canceled after 0s
2024-06-06 18:25:42 +00:00
Peer Richelsen f6930df87d chore: removed next app dir banner (#15356)
* removed next app dir banner

* yarn lock
2024-06-06 16:55:32 +00:00
7d4e8e2210 feat: outlook 365 connect atom (#15318)
* custom for office 365 connect atom

* office 365 connect atom

* add office 365 atom to package exports

* fixup

* fixup

* fixup fixup

* refactors

* chore: refactor connect atoms

* fixup

* chore: refactor connect, enable custom redir

* fixup! Merge branch 'outlook-365-calendar-frontend' of github.com:calcom/cal.com into outlook-365-calendar-frontend

* fixup! fixup! Merge branch 'outlook-365-calendar-frontend' of github.com:calcom/cal.com into outlook-365-calendar-frontend

---------

Co-authored-by: Rajiv Sahal <rajivsahal@Rajivs-MacBook-Pro.local>
Co-authored-by: Morgan Vernay <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2024-06-06 15:08:38 +00:00
50eeb712e3 fix: Exclude location options for seated event (#15174)
Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
2024-06-06 13:24:00 +00:00
75edc4539c fix: [CAL-3578] [CAL-2733] Zoho calendar issues (#14905)
* fix zohocalender installation

* fix func name

* fix: [CAL-3578] [CAL-2733] check events in the calendar when checking availability

* fix: server location on credentials instead app keys

* refactor: remove console log

Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>

---------

Co-authored-by: pritam <pritam.pk36129@gmail.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
2024-06-06 11:49:57 +00:00
Hariom Balhara def87ea84a fix: Team and User Links (#15342)
* fix: Team and User Links

* Add tests
2024-06-06 11:40:29 +00:00
Peer Richelsen 4153e5b2d5 added apple verification (#15346) 2024-06-06 11:04:26 +00:00
Omar López 8c2f6ae145 Revert "fix: 404 collisions (#15249)" (#15339)
This reverts commit 5d01eb2f38.

Signed-off-by: zomars <zomars@me.com>
2024-06-05 20:33:19 +00:00
78ea4d2f68 chore: Remove deprecated logo/avatar/away fields (#14705)
* chore: Remove deprecated logo/avatar/away fields

* Use right variables for accounts-step-card

* Remove more deprecated logo/avatar usage

* Dont drop the fields until all usages are gone

* Remove the avatar/logo drops for staggered release

* fix: Typescript blindspot (unvalidated include fields)

* fix: Further updates (mostly to API) typescript missed

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: Bailey Pumfleet <bailey@pumfleet.co.uk>
Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-06-05 16:44:31 +00:00
Hariom Balhara e7c638c1e4 fix: Wrong error message when inviting (#15332)
* fix: Wrong message when inviting

* Fix num users invited
2024-06-05 13:23:47 +00:00
Amit Sharma c28fab4fe2 fix: install flow: wrong org team avatars (#15334) 2024-06-05 13:10:31 +00:00
Alex van Andel e8a02554b6 chore: Remove DeploySentinel (#15328) 2024-06-05 00:18:11 +00:00
Kartik Saini 4017c0e28f feat: org-wide webhooks (#15144)
* feat: include org in teams list

* feat: org-wide webhooks

* Move getOrgIdFromMemberOrTeamId to packages/lib
2024-06-04 20:16:46 +00:00
Keith Williams d72f7f8a42 v4.1.9 (#15321)
release.yml / release (push) Canceled after 0s
2024-06-04 16:32:54 +00:00
3a4ebadbf3 feat: track no-shows in bookings (#15307)
* added dropdown for no-shows in past bookings

* added layout

* nit

* todo comment: figure out how to close dropdown

* more todo comments

* Adds TRPC route among other WIP

* functional update

* fixes type err

* fix type err

* fix: styles

* strikethrough in email

* NITs

* removed stale comment

* add tests

* err comment

---------

Co-authored-by: Peer Richelsen <peer@cal.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: sean-brydon <sean@cal.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
2024-06-04 15:18:11 +00:00
Hariom BalharaandJoe Au-Yeung 765d601ff9 fix: Booking Error - cannot be booked at this time (#15288)
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
2024-06-04 15:09:57 +00:00
3a22fdb428 feat: API v2 subversioning (#15135)
* feat: API v2 subversioning

* Update app.ts

* Added multiple versions to existing controllers

* Updated the slots controller

* chore: version platform library package with npm package alias

* chore: use consts to version

* chore: use consts to version

* chore: version api for cal provider

* chore: remove timezone controller subversion poc

* fixup! Merge branch 'main' into feat/api-v2-subversioning

---------

Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Morgan Vernay <morgan@cal.com>
2024-06-04 15:05:39 +00:00
Rajiv SahalandRajiv Sahal 93580ac4bc fix: typo in Gcal atom prop and outlook service (#15319)
* fix typo in onCheckError prop

* pass in correct access token

---------

Co-authored-by: Rajiv Sahal <rajivsahal@Rajivs-MacBook-Pro.local>
2024-06-04 11:17:33 +00:00
Somay Chauhanandsean-brydon b15ad6f233 fix: inviting a team member dosent work when he login in via Google (#11312)
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
2024-06-04 07:54:26 +00:00
56e59ab3e1 fix: no rating submitted text fixed (#15007)
* no rating submitted text fixed

* Update packages/ui/components/empty-screen/EmptyScreen.tsx

* Update packages/ui/components/empty-screen/EmptyScreen.tsx

---------

Co-authored-by: Peer Richelsen <peer@cal.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2024-06-03 15:19:38 +00:00
Abhishek Gurav ee796933ee Updated CONTRIBUTING.md (#15102)
For AES256 CALENDSO_ENCRYPTION_KEY
2024-06-03 14:57:36 +00:00
Joe Au-Yeung d2f76edfd6 fix: Double encoding in addAppMutation (#15303)
* Remove double encoding

* Add test for OAuth page

* Add tests

* Remove test from integrations.e2e
2024-06-03 14:53:03 +00:00
Peer RichelsenandJoe Au-Yeung 822f0204a6 added admin API docs (#15297)
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
2024-06-03 14:41:13 +00:00
9770aff153 feat: outlook 365 calendar endpoints (#15077)
* init endpoints for office 365 syncing

* get web app url for oauth

* update typings

* nethods for office 365 calendar

* update office 365 connect endpoint

* update packages

* add calendar type and if office 365 calendar

* add SelectedCalendarsRepository and TokensModule

* add functions for getting oauth credentials, getting default calendars and redirect url for office 365 calendar

* update controllers

* e2e tests for office 365 calendar endpoints

* fixup! Merge branch 'main' into rajiv/cal-3544-outlookoffice365-integration-connect-atom

* fixup! fixup! Merge branch 'main' into rajiv/cal-3544-outlookoffice365-integration-connect-atom

* fix merge conflict

* update typings

* abstract microsoft outlook into its own module

* add one common interface for calendar apps

* make calendars dynamic

* abstract every calendar app into its own service

* cleanup

* make all calendar endpoints dynamic

* calendar app constants

* cleanup

* remove unused repositories

* rename microsoft calendar type

* fix typings

* add google and outlook calendar service to calendars module

* fixup

* some more e2e tests including  google calendar

* chore: small type change and apple calendar not implemented yet

---------

Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Morgan Vernay <morgan@cal.com>
Co-authored-by: Rajiv Sahal <rajivsahal@Rajivs-MacBook-Pro.local>
2024-06-03 11:47:57 +00:00
Hichem Fantar 723d0ddec2 fix: Kbar component styles and improve transitions (#15283)
* fix: Kbar component styles

Fix Kbar styles on active state

* refactor: Add transition to event type list item

The commit refactors the event type list item component by adding a transition effect to improve the user experience.
2024-06-01 21:34:25 +00:00
Amit SharmaandSomay Chauhan 60b61eb625 feat: ability to assign people to round robin from org members (#14199)
* feat: ability to assign people to round robin from org members

* fix: include schedulingtype in filter

* fix: type check

* rename to EventTypesList

* rename to teams, change icon to link, early return if no events or teamId

* filter scheduling type array, change filter name

* rename to bulkAddMembersToTeams and bulkAddMembersToEventTypes

* filter refactor

* remove bulk

* filter remove null return

* Revert "filter remove null return"

This reverts commit 8ae6296dac24e5081b5896bb9dfe0c000c0f7faf.

* show checked if user already host in event type

* check boxes if user is part of the team

* remove hosts on unchecking boxes

* fix isSelected condition

* remove selected members from teams

---------

Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com>
2024-06-01 21:30:52 +00:00
Omar López 5d2d99006b v4.1.8 (#15287)
release.yml / release (push) Canceled after 0s
2024-06-01 00:32:45 +00:00
Keith WilliamsandOmar López 5d01eb2f38 fix: 404 collisions (#15249)
* fix: 404 collisions

* Added E2E test

* Removed await

* Attempting to fix E2E

* fingers crossed

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

* fix: e2e tests

* fix: missing navigation to 404 page

* fix: don't interrupt post login navigation

* fix: Expect owner as possible host for RR events

---------

Signed-off-by: zomars <zomars@me.com>
Co-authored-by: Omar López <zomars@me.com>
2024-05-31 22:28:43 +00:00
Joe Au-Yeung ac3fb0a1cd fix: Typo in deleteCredential handler (#15281)
* Fix typo

* Added optional chaining
2024-05-31 16:57:20 +00:00
Hariom Balhara 1730ef7d5d feat: Add framework to send all events fired for embed to Analytics Apps (#15173)
* Send all events to analytics apps

* feat: Start sending all events fired for embed to Analytics Apps(GTM Support added)

* Add tests
2024-05-31 16:07:09 +00:00
Somay Chauhan 9e371ded90 add redirectUrl to /eventTypes page as well (#15274)
* During signup, if the account already exists, we redirect the user to /event-types instead of onboarding. Adding this redirection logic to /event-types page as well to ensure the user is redirected to the correct redirectUrl.
2024-05-31 15:06:11 +00:00
Keith Williams 15098bdd1e chore: v4.1.7 (#15277)
release.yml / release (push) Canceled after 0s
2024-05-31 14:30:41 +00:00
625a7ec180 refactor: Introduce crmManager (#14272)
* fix timezone display on booking page to reflect event availability timezone

* migrate fetching event owner's schedule to server side

* migrate fetching event owner's schedule to server side

* fix e2e test errors

* Add WEBAPP_URL_FOR_OAUTH to salesforce auth

* In event manager constructor include "_crm" credentials as calendar creds

* Change crm apps to type to end with `_crm`

* Move sendgrid out of CRM

* Add zoho bigin to CRM apps

* When getting apps, use slug

* Add `crm` variants

* Hubspot Oauth use `WEBAPP_URL_FOR_OAUTH`

* Refactor creating credentials

* Fix empty CRM page

* Use credentials with `_crm`

* Abstract getAppCategoryTitle

* Add integration.handler changes

* Init crmManager

* Change salesforce to CrmService

* Create crmManager

* Create contact on new event

* Create event

* Create new CRM reference

* - Fix create new contact for salesforce
- Add reschedule to crmManager

* Create deleteAllCRMEvents

* When searching for credential, look for current credentials in class

* On cancel, delete 3rd party events

* Add delete method

* Type fix

* Type fix

* Convert Close.com to CrmService

* Convert Close.com to CrmService

* Move hubspot to CrmService

* Convert Pipedrive to CrmService

* Rename classes to CrmService

* Move ZohoCrm to CrmService

* Move Bigin to CrmService

* Type return for CrmServices

* Fix type errors

* Close.com create leads and contacts

* Fix tests

* Type fix

* Zoho bug fixes

* Clean up

* Type fixes

* Remove apiDeletes

* Type fixes

* Specific typing

* Type fix

* Type fix

* Type fix

* Type fix

* Type fix

* feat: Enable CRM apps on a per event type basis (#14450)

* Add Salesforce to be an event type app

* Handle new booking, only get enabled CRM credentials

* Abstract generating search params

* Add close.com to event type

* Clean up

* Move hubspot to event type

* Add pipedrive to event type

* Add zoho bigin to event type

* Add zoho crm to event type

* Remove console.log

* Add deleting CRM apps from event type

* Delete event type apps

* Fix deleting credentials

* Add CRM app data to event type metadata

* Backwards compatibility: add CRM credential if doesn't exist on event type

* Don't include user CRM credentials for backwards comp

* Backwards compatibility show CRM app is enabled and dirty field

* Clean up

* Type fixes

* Type fixes

* Type fix

* Type fix

* Remove console.log

* Test fix

* Upgrade embed-react vite version - dev

* Change build can't find error message

* Add back omni install prop

* Clean up

* Refactor `writeAppDataToEventType`

* Use eventType repository in writeAppDataToEventType

* Clean up old comments

* Add error logging

* createCRMEvents pass event uid as created event uid

* Use `getUid`

* Clean up props in create crm event

* Small changes to `crmManager`

* Fix zoho CRM

* refactor crmManager

* Undo vite config change

* Fix teamId query

* Fix bigin error

* Remove need for `writeAppDataToEventType`

* Add `getAllCredentials` test

* Add crmManager tests

* Type fixes

* Fix type errors

* Fix getAllCredentials test

* Fix tests

* Skip CRM manager tests for now

* feat: Skip RR Assignment if Contact Exists In Salesforce (#14556)

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

* Update yarn.lock

* @zomars feedback - use new URL for state params

* fix: update hook to not produce enabled === undefined

* fix: update app card interfaces to use the new enabled from useIsAppEnabled

* fix: feedback for crm RR skip (#15160)

* code clean up

* fix type any

* test setup for RR lead skip

* code clean up

* simplify code

* type error

* finshed first test for RR lead skip

* add seconds test

* add test for handleNewBooking

* test if teamMember is set

* fix missing enabled key

* fix tests

* fix type error

* use setSystemTime instead of getDate

* remove nested if

---------

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

* fix type error

* fix: remove app metadata from all eventTypes on deleting the app

* fix: update hook to not produce enabled === undefined (default to false)

---------

Co-authored-by: Shaik-Sirajuddin <sirajuddinshaik30gmail.com>
Co-authored-by: Shaik-Sirajuddin <sirajudddinshaik30@gmail.com>
Co-authored-by: Shaik-Sirajuddin <89742297+Shaik-Sirajuddin@users.noreply.github.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
Co-authored-by: Omar López <zomars@me.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: sean-brydon <sean@cal.com>
Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com>
2024-05-31 13:54:52 +00:00
Omar López 5602f7bd95 chore: v4.1.6 (#15266)
release.yml / release (push) Canceled after 0s
2024-05-31 13:32:30 +00:00
Udit TakkarandKeith Williams 3e2caa9e1e fix: add blacklist email logic in backend (#15270)
* fix: add blacklist email logic in backedn

* chore: type err

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

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

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-05-31 12:47:36 +00:00
Lauris Skraucis b905de435d refactor: format v2 API managed user timeZone (#15273) 2024-05-31 12:06:29 +00:00
Amit Sharma 23bb06cc36 fix: Avatars not showing when using bookings filter (#15271) 2024-05-31 08:25:10 +00:00
Afrin NaharandKeith Williams dd24100035 fixes top right sections overflow on event page (#15109)
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-05-31 04:23:19 +00:00
Vinicius VieiraandKeith Williams 7434d91d48 Adjust on getAggregateWorkingHours (#15137)
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-05-31 04:01:11 +00:00
Keith WilliamsandUdit Takkar 3b1de34451 chore: Add guest email blacklist (#15255)
* chore: Add guest email blacklist

* types

* Added check to only log when we've removed one

* feat: add verification logic

* chore: use base exftract email

* Added toLowerCase for guest email checks

---------

Co-authored-by: Udit Takkar <udit222001@gmail.com>
2024-05-30 17:13:34 +00:00
4cf89d273e feat(i18n): complete Simplified Chinese translations (#14474)
* feat(i18n): complete Simplified Chinese translation

* chore: check for missing translation items

* fix: put the prevent merge conflict line at the end

* feat: put new translations at the beginning

* Rename translate-locales.ts to check-missing-translations.ts

* Update package.json to use check-missing-translations

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Omar López <zomars@me.com>
2024-05-30 15:06:58 +00:00
Dilpreet SinghandSio e58ce4af71 adds 45 min to dynamic events (#15248)
Co-authored-by: Sio <sio@Sios-MacBook-Air.local>
2024-05-30 14:01:45 +00:00
KaleemandAlex van Andel 15122dd5e9 fix: remove ts-ignore by converting to string[] (#14622)
* fix: remove ts-ignore by converting to string[]

* chore: remove extra space

* chore: make word lower case

* Possible fix for endpoints.ts

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-05-30 13:35:17 +00:00
sean-brydon 793c0c60e3 test: get upgradeable test (#15261)
* Add test for defaeult handler

* tests: add tests for getUsersTopbanner-getUpgradeable

* Import router to use userId
2024-05-30 12:28:40 +00:00
MorganandAlex van Andel 344454e574 chore: version platform libraries npm package (#15257)
* wip

* fix: watch mode and eslint slow

* update yarn lock

* Regenerated yarn.lock file for this branch

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2024-05-30 12:11:24 +00:00
sean-brydon 86342d103a Add test for defaeult handler (#15258) 2024-05-30 11:57:54 +00:00
Carina WollendorferandCarinaWolli d4f3726875 fix: missing date overrides in negative tz (#15251)
* fix check for past date overrides

* add test

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2024-05-29 23:35:43 +00:00
Hariom Balhara 817a3decb7 fix: Do subscription update even if team.members are less than 30 in case orgSeats allow it (#15209)
* Send all events to analytics apps

* fix: Handle subscription update when orgSeats are less than 30

* Add more tests
2024-05-29 21:19:32 +00:00
Keith Williams 5f082e11f8 fix: API booking issues (#15247)
* fix: API booking issues

* Put back the optional zod for user

* fixed the imports

* Using nullish

* typing errors

* missed one
2024-05-29 16:16:49 +00:00
Amit Sharma 5fb5081faa fix: removing the default app should remove the default badge from the appCard (#15243) 2024-05-29 15:10:45 +00:00
17f328fc5e chore: added help cards to platform dashboard (#15218)
* added cards to platform dashboard

* nit

* move help cards into its own component

* help cards component

* utils for platform

* fix icon type prop

* fix icon

---------

Co-authored-by: Rajiv Sahal <rajivsahal@Rajivs-MacBook-Pro.local>
Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
2024-05-29 13:58:18 +00:00
Udit Takkar d19034c2d5 fix: double icon on user event type (#15239)
* fix: double icon

* test: add test for user event type
2024-05-29 13:23:58 +00:00
Morgan 4cdcc85620 fix: useGetBookingForReschedule wait for calProvider init (#15236) 2024-05-29 13:02:44 +00:00
Somay Chauhan 3f51ae626c openIntercom="true" open intercom (#15235) 2024-05-29 12:22:44 +00:00
Somay ChauhanandPeer Richelsen 8499aebe88 fix: intercom has organisation (#15224)
* fix: intercom has organisation

* Apply suggestions from code review

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2024-05-29 12:22:25 +00:00
Udit Takkar 07f613050e fix: not able to click start recording button (#15244) 2024-05-29 12:18:51 +00:00
Keith Williams 2c8c8368a0 chore: Reducing E2E test sharding (#15192)
* chore: Removing E2E test sharding

* Added back 4 shards for main E2E

* Bump build machines to use 8vCPUs

* Downgrading builds to 2 vCPUs to see time difference

* Reduced shards to 2 to see if flakes are reduced

* Increased E2E vCPUs

* Put builds back to 4 vCPUs since they need it

* Updated E2E suite to use 16 vCPUs and no sharding

* Not running in parallel just to test

* Put back the parallelism

* Get rid of themeBasis warning in test suite

* Skipping another flaky test

* 2 shards

* Update e2e.yml
2024-05-28 20:50:39 +00:00
Alex van Andel 74d3a84e27 v4.1.5 (#15230)
release.yml / release (push) Canceled after 0s
2024-05-28 20:15:53 +00:00
Somay Chauhan 33c1d49c52 feat: jelly seamless signup (#15220)
* feat: jelly seamless signup

* fix: wrong import

* add credentialId id to defaultLocation

* add CredentialId and correct appType

* fix: type error
2024-05-28 17:54:59 +00:00
889ff177c1 feat: Add {first name} variable to Organizer & Scheduler custom event… (#14156)
* feat: Add {first name} variable to Organizer & Scheduler custom event name

* fix: use split name booking field

* remove unwanted translation changes

* Update packages/core/event.ts

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

* chore: improve code

* add scheduler last name

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: Udit Takkar <udit222001@gmail.com>
2024-05-28 14:32:12 +00:00
Morgan d8a6c375d0 chore: Platform Booker defaultFormValues for prefilling (#15219)
* chore: Platform Booker defaultFormValues for prefilling

* fixup! chore: Platform Booker defaultFormValues for prefilling
2024-05-28 11:36:54 +00:00
Lauris Skraucis 655127d155 fix: exclude atoms web wrappers from build (#15216)
* fix: exclude atoms web wrappers from build

* refactor: tsconfig web wrapper regex

* refactor: wrappers follow schema Component(Web|Platform)Wrapper.tsx

* fix: tsconfig regex for web wrapper
2024-05-28 10:09:03 +00:00
Morgan 17c4a10e33 fix: platform plan name is always uppercase (#15215) 2024-05-28 08:17:42 +00:00
Udit Takkar 30f9f19a9f fix: avatar on booking page (#15190)
* fix: avatar on booking page

* chore

* fix: type err

* fix: unpublished org
2024-05-27 19:31:08 +00:00
Anik Dhabal BabuandPeer Richelsen be7d45afe2 feat: autosave availability after making changes (#14849)
* feat: availability after making changes

* update

* update

* Update Schedule.tsx

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2024-05-27 14:25:29 +00:00
Amit SharmaandUdit Takkar d2bec46d89 fix: event duration missing translation (#14862)
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-05-27 14:12:00 +00:00
Sujit Ale MagarandUdit Takkar b90500778e fix: Event Type Toggle Shift (#15066)
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-05-27 14:10:53 +00:00
Rajiv SahalandMorgan Vernay bddc235c3c fix: platform booker icons and address property for type inPerson (#15207)
* fix: platform booker icons

* fix label not being shown for address

* fix type check

* PR feedback

---------

Co-authored-by: Morgan Vernay <morgan@cal.com>
2024-05-27 11:02:58 +00:00
360b729d08 chore: added event-types link to settings (#14274)
* added event-types link

* fix: add item in settings layout

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: Udit Takkar <udit222001@gmail.com>
2024-05-27 09:35:52 +00:00
Alex van Andel 5d325495a9 fix: Profile page crash due to invalid topLevelElement (#15198) 2024-05-24 16:12:15 +00:00
Amit Sharma dead2b843a fix: attendeeSeatId is not being returned on webhook response for events with seats (#15184) 2024-05-24 15:47:35 +00:00
Olga Stogova 1174cb0d8e fix(atoms): fix max-height bug for the Booker component (#15195) 2024-05-24 13:15:04 +00:00
Olga Stogova 58e6f18594 fix: styles for the schedule component, make it mobile-friendly (#15178)
* fix styles for the schedule component, make it mobile-friendly

* CR changes

* no need that condition
2024-05-24 11:06:40 +00:00
Udit Takkar ffe6a46e66 chore: return empty array if no transcription found (#15185) 2024-05-24 02:20:50 +00:00
Keith Williams 37c02572de chore: v4.1.4 (#15186)
release.yml / release (push) Canceled after 0s
2024-05-23 20:06:37 +00:00
b82b0a33a4 feat: events apps new install flow (#14616)
* feat(appStore): add isOAuth config

* refactor(appStore): EventTypeAppSettngsInterface

* refactor(qr_code): split EventTypeAppCardInterface and EventTypeAppSettingsInterface

* feat(appStore): redirect to onboarding for stripe and basecam

* fix(ui/ScrollableArea): overflow indicator not working

* feat(apps): new install app flow

* fix(configureStep): get disabled props for settings

* fix: getAppInstallsBySlug now use teamIds

* chore: Alby to AppSettingsInterface

* chore: Giphy to appsettings interface

* chore: GTM migration

* chore: GT4 - migration

* chore: fathom migration

* chore: paypal

* feat: basecamp migration

* feat: metapixel migration

* feat:plausable

* feat:stripe

* fix merge issues

* fix merge issues in new app install flow steps

* wip: callback to onboarding

* fix: imports

* fix: more imports

* feat: use redirect to onboarding on install flow

* fix: redirect to event-type after oauth flow

* When clicking on install new app button, only redirect to the new app install flow if it is an oAuth app or an app that extends the EventType feature in it's config

* code refactor, skip event-type step

* removed extra consoles

* so that no one can change the eventTypeId in url

* theme support enabled

* only pass eventTypeId instead of whole evetType obj to OmniInstallAppButton

* fix: clicking on event-type gives error and redirects to /apps

* saved appOnboardingRedirectUrl to OAuth State

* fix: a user having no team breaks the onboarding flow

* add optional chaining to appMetadata.extendsFeature and appMetadata.isOAuth;

* encode appOnboardingRedirectUrl

* fix: dark theme ui issues

* skip configure step if no-event types

if user/team does not have event-type then skip configure step and goto apps/installed/[category]

* exclude calendars from apps- onboarding flow

* Update getAppOnboardingRedirectUrl.ts

* fix: On configure step, inputs aren't showing errors

* change route from `apps/onboarding` to `apps/installation`

* fix: flow not correctly working for teams

* should only allow team ADMIN or OWER to install an app to team

* Prevent two payment apps to be enabled

* removed loading state

* Fix type error

* undo new-app-flow from OmniInstallAppButton

* remove OAuth Step, handle step numbering

* fix: redirect url

* getAppOnboardingRedirectUrl refactor

* for debugging

* Revert "for debugging"

This reverts commit b9362c1a8f47f2280e684c213d7ec08d04a8ac4c.

* fix: added toaster

* feat: added support to select multiple events (almost)

* hide button

* Move inner form outside outer form using portal

Due to limitations with nested forms in React Hook Form, moved the inner form outside the outer form using a portal to ensure proper form handling.

* submit buttons refs madness

* removed configure step

we had to use query params to manage selected event-types, between routes which was causing 2 issues:
* each time we selected or unselected an event the whole page was reloaded including getserversideprops being called again and again
* the form was reloaded causing more issues

* removed extra unwanted code

* small fix

* fix: type error

* fix: types

* implemented suggested changes

* removed step footer
* fixed error.message
* removed commented styles

* removed step footer

* fix: Display team event types instead of user's on event types step when team selected

* fix: typo

* removed shouldLockDisableProps

* refactor setUpdatedEventTypesStatus, fix type

* removed extra code

* can't delete while saving

* added translations

* fix: loading in select account step, fix handle onSelect params type

* Fix typo

* feat: add skip button to event-types step

* use set-up-later button in tests

* added skip button to configure step as well

* feat: add test for analytics apps using the new app install flow

* feat: add test for stripe 1

* feat: add test for stripe 2

* Fix: Redirect only those apps that extend 'EventType' to the new app install flow (#14527)

* fix: type errors

* fix: failing tests

* fix: tests

* fix test flakiness

* better naming and code refactor for analytics apps tests

* run tests parallelly

* removed network idle, giving error

* another shot at test flakiness

* Fix:  can't install apps without team selector dropdown on main app store page.

* fix: test flakiness

* fix: account select loading issue

* removed getPaymentCredential (unused)

* fix: only redirect after the app has been added to all the event-types

* remove overflowIndicatorStyles

* fixed failing test

* fix: exclude org team events

* undo some random merge changes

---------

Co-authored-by: Morgan Vernay <morgan@cal.com>
Co-authored-by: sean-brydon <sean@cal.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
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: Omar López <zomars@me.com>
2024-05-23 19:53:28 +00:00
Udit TakkarandKeith Williams b1bbbcee90 fix: signing_up_terms i18n (#15156)
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-05-23 19:06:30 +00:00
Hariom BalharaandKeith Williams 1a381695e5 fix: Org Seeder - to better represent production scenario and fix admin org delete cleanup (#15157)
* Fix seeder and update message to inform well about org deletion implication

* Cleanup tempOrgRedirect as well

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2024-05-23 18:01:25 +00:00
Keith WilliamsandOmar López 8831ff13c7 chore: Skip flaky tests that have been failing often (#15161)
* chore: Skip flaky tests that have been failing often

* Update basic.e2e.ts

* Skipped another test

* Only run on legacy routes as a test

* Removing future routes from build

* Updated the remove script

* Fixing command

* Bring back the future routes

* Skipped another

---------

Co-authored-by: Omar López <zomars@me.com>
2024-05-23 14:00:56 -04:00
Keith Williams 64845c670d fix: Required check for CI (#15181) 2024-05-23 13:26:17 -04:00
Keith Williams ba06c6c26a chore: Bring back merge queues (#15177)
* chore: Bring back merge queues

* Removed lint as pre-req for integration test

* Cleaned up warnings
2024-05-23 12:49:29 -04:00
Keith Williams 49df99cf92 chore: v4.1.3 (#15176)
release.yml / release (push) Canceled after 0s
2024-05-23 12:34:21 -04:00
Udit Takkar 0cb2e60d9b fix: broken url on booking page (#15028) 2024-05-23 16:17:44 +00:00
Amit SharmaandUdit Takkar b3485b07bf fix: mobile avatars not loading on event-types (#15167)
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2024-05-23 16:17:09 +00:00
Lauris Skraucis 01933e5c15 feat: v2 API enable updating event-type bookingFields (#15172) 2024-05-23 13:19:52 +00:00
Hariom Balhara 5f5cf92456 fix: Use origin as provided in HeadSeo. origin would be different for Domain cases (#14935)
* fix: Use origin as provided in HeadSeo. origin would be different for Domain cases

* Add a test

* add more test

* Add tests

* Cleanup tests

* Add an e2e as well

* fix-test

* Reset mocks
2024-05-23 11:47:46 +01:00
Amit SharmaandSomay Chauhan 29ccc58806 fix: if we go to event-types/[id]?tabName=apps after installing an app to an organisation it shows 2 apps (#15166)
Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com>
2024-05-23 08:37:10 +00:00
Omar López 26bd02bd94 chore: Moved legacy rewrites from afterFiles to beforeFiles (#15164) 2024-05-22 12:14:08 -07:00
Syed Ali Shahbaz 04bf23ed69 Make pagination optional (#15163) 2024-05-22 17:51:36 +00:00
616 changed files with 18860 additions and 3896 deletions
+8
View File
@@ -19,6 +19,11 @@
# instructions. This environment variable is deprecated although still supported for backward compatibility.
# @see https://console.cal.com
CALCOM_LICENSE_KEY=
# Signature token for the Cal.com License API (used for self-hosted integrations)
# We will give you a token when we provide you with a license key this ensure you and only you can communicate with the Cal.com License API for your license key
CAL_SIGNATURE_TOKEN=
# The route to the Cal.com License API
CALCOM_PRIVATE_API_ROUTE=
# ***********************************************************************************************************
# - DATABASE ************************************************************************************************
@@ -359,3 +364,6 @@ UNKEY_ROOT_KEY=
# Used for Cal.ai Enterprise Voice AI Agents
# https://retellai.com
RETELL_AI_KEY=
# Used to disallow emails as being added as guests on bookings
BLACKLISTED_GUEST_EMAILS=
+2
View File
@@ -1,4 +1,6 @@
node_modules
apps/api/v2/dist
packages/platform/**/dist/*
**/**/node_modules
**/**/.next
**/**/public
+85
View File
@@ -0,0 +1,85 @@
name: All checks
on:
merge_group:
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
type-check:
name: Type check
uses: ./.github/workflows/check-types.yml
secrets: inherit
lint:
name: Linters
uses: ./.github/workflows/lint.yml
secrets: inherit
unit-test:
name: Tests
uses: ./.github/workflows/unit-tests.yml
secrets: inherit
build-api-v1:
name: Production builds
uses: ./.github/workflows/api-v1-production-build.yml
secrets: inherit
build-api-v2:
name: Production builds
uses: ./.github/workflows/api-v2-production-build.yml
secrets: inherit
build:
name: Production builds
uses: ./.github/workflows/production-build-without-database.yml
secrets: inherit
integration-test:
name: Tests
needs: [lint, build, build-api-v1, build-api-v2]
uses: ./.github/workflows/integration-tests.yml
secrets: inherit
e2e:
name: Tests
needs: [lint, build, build-api-v1, build-api-v2]
uses: ./.github/workflows/e2e.yml
secrets: inherit
e2e-app-store:
name: Tests
needs: [lint, build, build-api-v1, build-api-v2]
uses: ./.github/workflows/e2e-app-store.yml
secrets: inherit
e2e-embed:
name: Tests
needs: [lint, build, build-api-v1, build-api-v2]
uses: ./.github/workflows/e2e-embed.yml
secrets: inherit
e2e-embed-react:
name: Tests
needs: [lint, build, build-api-v1, build-api-v2]
uses: ./.github/workflows/e2e-embed-react.yml
secrets: inherit
analyze:
name: Analyze Build
needs: [build]
uses: ./.github/workflows/nextjs-bundle-analysis.yml
secrets: inherit
required:
needs: [lint, type-check, unit-test, integration-test, build, build-api-v1, build-api-v2, e2e, e2e-embed, e2e-embed-react, e2e-app-store]
if: always()
runs-on: buildjet-2vcpu-ubuntu-2204
steps:
- name: fail if conditional jobs failed
if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'skipped') || contains(needs.*.result, 'cancelled')
run: exit 1
+3 -6
View File
@@ -41,7 +41,7 @@ env:
jobs:
e2e-app-store:
timeout-minutes: 20
name: E2E App Store (${{ matrix.shard }}/${{ strategy.job-total }})
name: E2E App Store
runs-on: buildjet-4vcpu-ubuntu-2204
services:
postgres:
@@ -70,9 +70,6 @@ jobs:
- 1025:1025
strategy:
fail-fast: false
matrix:
## There aren't many tests for AppStore. So, just start with 2 shards. Increase if needed.
shard: [1, 2]
steps:
- uses: docker/login-action@v3
@@ -93,10 +90,10 @@ jobs:
E2E_TEST_CALCOM_GCAL_KEYS: ${{ secrets.E2E_TEST_CALCOM_GCAL_KEYS }}
- uses: ./.github/actions/cache-build
- name: Run Tests
run: yarn e2e:app-store --shard=${{ matrix.shard }}/${{ strategy.job-total }}
run: yarn e2e:app-store
- name: Upload Test Results
if: ${{ always() }}
uses: actions/upload-artifact@v4
with:
name: app-store-results-${{ matrix.shard }}_${{ strategy.job-total }}
name: app-store-results
path: test-results
+3 -6
View File
@@ -41,7 +41,7 @@ env:
jobs:
e2e-embed:
timeout-minutes: 20
name: E2E Embed React (${{ matrix.shard }}/${{ strategy.job-total }})
name: E2E Embed React
runs-on: buildjet-4vcpu-ubuntu-2204
services:
postgres:
@@ -62,9 +62,6 @@ jobs:
- 5432:5432
strategy:
fail-fast: false
matrix:
## There aren't many tests for embed-react. So, just start with 2 shards. Increase if needed.
shard: [1, 2]
steps:
- uses: docker/login-action@v3
@@ -79,11 +76,11 @@ jobs:
- uses: ./.github/actions/cache-build
- name: Run Tests
run: |
yarn e2e:embed-react --shard=${{ matrix.shard }}/${{ strategy.job-total }}
yarn e2e:embed-react
yarn workspace @calcom/embed-react packaged:tests
- name: Upload Test Results
if: ${{ always() }}
uses: actions/upload-artifact@v4
with:
name: embed-react-results-${{ matrix.shard }}_${{ strategy.job-total }}
name: embed-react-results
path: test-results
+3 -6
View File
@@ -41,7 +41,7 @@ env:
jobs:
e2e-embed:
timeout-minutes: 20
name: E2E Embed Core (${{ matrix.shard }}/${{ strategy.job-total }})
name: E2E Embed Core
runs-on: buildjet-4vcpu-ubuntu-2204
services:
postgres:
@@ -70,9 +70,6 @@ jobs:
- 1025:1025
strategy:
fail-fast: false
matrix:
## There aren't many tests for embed-core. So, just start with 2 shards. Increase if needed.
shard: [1, 2]
steps:
- uses: docker/login-action@v3
@@ -86,10 +83,10 @@ jobs:
- uses: ./.github/actions/cache-db
- uses: ./.github/actions/cache-build
- name: Run Tests
run: yarn e2e:embed --shard=${{ matrix.shard }}/${{ strategy.job-total }}
run: yarn e2e:embed
- name: Upload Test Results
if: ${{ always() }}
uses: actions/upload-artifact@v4
with:
name: embed-core-results-${{ matrix.shard }}_${{ strategy.job-total }}
name: embed-core-results
path: test-results
+2 -2
View File
@@ -42,7 +42,7 @@ jobs:
e2e:
timeout-minutes: 20
name: E2E (${{ matrix.shard }}/${{ strategy.job-total }})
runs-on: buildjet-4vcpu-ubuntu-2204
runs-on: buildjet-8vcpu-ubuntu-2204
services:
postgres:
image: postgres:13
@@ -71,7 +71,7 @@ jobs:
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4, 5, 6, 7]
shard: [1, 2, 3, 4]
steps:
- uses: docker/login-action@v3
with:
+8 -7
View File
@@ -75,15 +75,16 @@ jobs:
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: ./.github/actions/dangerous-git-checkout
- uses: ./.github/actions/yarn-install
- uses: ./.github/actions/cache-db
- name: Run Tests
run: yarn test -- --integrationTestsOnly
- name: Upload Test Results
if: ${{ always() }}
uses: actions/upload-artifact@v4
with:
name: test-results
path: test-results
# TODO: Generate test results so we can upload them
# - name: Upload Test Results
# if: ${{ always() }}
# uses: actions/upload-artifact@v4
# with:
# name: test-results
# path: test-results
+5 -62
View File
@@ -4,7 +4,6 @@ on:
pull_request_target:
branches:
- main
merge_group:
workflow_dispatch:
concurrency:
@@ -35,13 +34,6 @@ jobs:
uses: ./.github/workflows/check-types.yml
secrets: inherit
unit-test:
name: Tests
needs: [changes]
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
uses: ./.github/workflows/unit-tests.yml
secrets: inherit
lint:
name: Linters
needs: [changes]
@@ -49,71 +41,22 @@ jobs:
uses: ./.github/workflows/lint.yml
secrets: inherit
build-api-v1:
name: Production builds
unit-test:
name: Tests
needs: [changes]
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
uses: ./.github/workflows/api-v1-production-build.yml
secrets: inherit
build-api-v2:
name: Production builds
needs: [changes]
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
uses: ./.github/workflows/api-v2-production-build.yml
secrets: inherit
build:
name: Production builds
needs: [changes]
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
uses: ./.github/workflows/production-build-without-database.yml
uses: ./.github/workflows/unit-tests.yml
secrets: inherit
integration-test:
name: Tests
needs: [changes, lint, build, build-api-v1, build-api-v2]
needs: [changes]
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
uses: ./.github/workflows/integration-tests.yml
secrets: inherit
e2e:
name: Tests
needs: [changes, lint, build, build-api-v1, build-api-v2]
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
uses: ./.github/workflows/e2e.yml
secrets: inherit
e2e-app-store:
name: Tests
needs: [changes, lint, build, build-api-v1, build-api-v2]
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
uses: ./.github/workflows/e2e-app-store.yml
secrets: inherit
e2e-embed:
name: Tests
needs: [changes, lint, build, build-api-v1, build-api-v2]
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
uses: ./.github/workflows/e2e-embed.yml
secrets: inherit
e2e-embed-react:
name: Tests
needs: [changes, lint, build, build-api-v1, build-api-v2]
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
uses: ./.github/workflows/e2e-embed-react.yml
secrets: inherit
analyze:
name: Analyze Build
needs: [changes, build]
if: ${{ needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
uses: ./.github/workflows/nextjs-bundle-analysis.yml
secrets: inherit
required:
needs: [changes, lint, type-check, unit-test, integration-test, build, build-api-v1, build-api-v2, e2e, e2e-embed, e2e-embed-react, e2e-app-store]
needs: [changes, lint, type-check, unit-test, integration-test]
if: always()
runs-on: buildjet-2vcpu-ubuntu-2204
steps:
@@ -37,12 +37,3 @@ jobs:
```
${{ steps.lint_pr_title.outputs.error_message }}
```
# Delete a previous comment when the issue has been resolved
- if: ${{ steps.lint_pr_title.outputs.error_message == null }}
uses: marocchino/sticky-pull-request-comment@v2
with:
header: pr-title-lint-error
message: |
Thank you for following the naming conventions! 🙏 Feel free to join our [discord](https://go.cal.com/discord) and post your PR link.
+1 -1
View File
@@ -99,7 +99,7 @@ To develop locally:
- Duplicate `.env.example` to `.env`.
- Use `openssl rand -base64 32` to generate a key and add it under `NEXTAUTH_SECRET` in the `.env` file.
- Use `openssl rand -base64 24` to generate a key and add it under `CALENDSO_ENCRYPTION_KEY` in the `.env` file.
- Use `openssl rand -base64 32` to generate a key and add it under `CALENDSO_ENCRYPTION_KEY` in the `.env` file.
6. Setup Node
If your Node version does not meet the project's requirements as instructed by the docs, "nvm" (Node Version Manager) allows using Node at the version required by the project:
+17
View File
@@ -0,0 +1,17 @@
import * as Sentry from "@sentry/nextjs";
export function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
// reduce sample rate to 10% on production
tracesSampleRate: process.env.NODE_ENV !== "production" ? 1.0 : 0.1,
});
}
if (process.env.NEXT_RUNTIME === "edge") {
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
});
}
}
+1 -1
View File
@@ -55,7 +55,7 @@ export const schemaBookingReadPublic = Booking.extend({
timeZone: true,
locale: true,
})
.optional(),
.nullish(),
payment: z
.array(
_PaymentModel.pick({
@@ -14,3 +14,7 @@ export const withValidQueryIdTransformParseInt = withValidation({
type: "Zod",
mode: "query",
});
export const getTranscriptFromRecordingId = schemaQueryIdParseInt.extend({
recordingId: z.string(),
});
+11 -6
View File
@@ -2,7 +2,12 @@ const { withAxiom } = require("next-axiom");
const { withSentryConfig } = require("@sentry/nextjs");
const plugins = [withAxiom];
/** @type {import("next").NextConfig} */
const nextConfig = {
experimental: {
instrumentationHook: true,
},
transpilePackages: [
"@calcom/app-store",
"@calcom/core",
@@ -87,12 +92,12 @@ const nextConfig = {
};
if (!!process.env.NEXT_PUBLIC_SENTRY_DSN) {
nextConfig["sentry"] = {
autoInstrumentServerFunctions: true,
hideSourceMaps: true,
};
plugins.push(withSentryConfig);
plugins.push((nextConfig) =>
withSentryConfig(nextConfig, {
autoInstrumentServerFunctions: true,
hideSourceMaps: true,
})
);
}
module.exports = () => plugins.reduce((acc, next) => next(acc), nextConfig);
+1 -1
View File
@@ -30,7 +30,7 @@
"@calcom/lib": "*",
"@calcom/prisma": "*",
"@calcom/trpc": "*",
"@sentry/nextjs": "^7.73.0",
"@sentry/nextjs": "^8.8.0",
"bcryptjs": "^2.4.3",
"memory-cache": "^0.2.0",
"next": "^13.5.4",
@@ -0,0 +1,94 @@
import type { NextApiRequest } from "next";
import {
getTranscriptsAccessLinkFromRecordingId,
checkIfRoomNameMatchesInRecording,
} from "@calcom/core/videoClient";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import type { PartialReference } from "@calcom/types/EventManager";
import { getTranscriptFromRecordingId } from "~/lib/validations/shared/queryIdTransformParseInt";
/**
* @swagger
* /bookings/{id}/transcripts/{recordingId}:
* get:
* summary: Find all Cal video transcripts of that recording
* operationId: getTranscriptsByRecordingId
* parameters:
* - in: path
* name: id
* schema:
* type: integer
* required: true
* description: ID of the booking for which transcripts need to be fetched.
* - in: path
* name: recordingId
* schema:
* type: string
* required: true
* description: ID of the recording(daily.co recording id) for which transcripts need to be fetched.
* - in: query
* name: apiKey
* required: true
* schema:
* type: string
* description: Your API key
* tags:
* - bookings
* responses:
* 200:
* description: OK
* content:
* application/json:
* 401:
* description: Authorization information is missing or invalid.
* 404:
* description: Booking was not found
*/
export async function getHandler(req: NextApiRequest) {
const { query } = req;
const { id, recordingId } = getTranscriptFromRecordingId.parse(query);
await checkIfRecordingBelongsToBooking(id, recordingId);
const transcriptsAccessLinks = await getTranscriptsAccessLinkFromRecordingId(recordingId);
return transcriptsAccessLinks;
}
const checkIfRecordingBelongsToBooking = async (bookingId: number, recordingId: string) => {
const booking = await prisma.booking.findUnique({
where: { id: bookingId },
include: { references: true },
});
if (!booking)
throw new HttpError({
statusCode: 404,
message: `No Booking found with booking id ${bookingId}`,
});
const roomName =
booking?.references?.find((reference: PartialReference) => reference.type === "daily_video")?.meetingId ??
undefined;
if (!roomName)
throw new HttpError({
statusCode: 404,
message: `No Booking Reference with Daily Video found with booking id ${bookingId}`,
});
const canUserAccessRecordingId = await checkIfRoomNameMatchesInRecording(roomName, recordingId);
if (!canUserAccessRecordingId) {
throw new HttpError({
statusCode: 403,
message: `This Recording Id ${recordingId} does not belong to booking ${bookingId}`,
});
}
};
export default defaultResponder(getHandler);
@@ -0,0 +1,16 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
import { withMiddleware } from "~/lib/helpers/withMiddleware";
import authMiddleware from "../../_auth-middleware";
export default withMiddleware()(
defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {
await authMiddleware(req);
return defaultHandler({
GET: import("./_get"),
})(req, res);
})
);
+4 -2
View File
@@ -180,8 +180,10 @@ export async function handler(req: NextApiRequest) {
const { dateFrom, dateTo } = schemaBookingGetParams.parse(req.query);
const args: Prisma.BookingFindManyArgs = {};
args.take = take;
args.skip = skip;
if (req.query.take && req.query.page) {
args.take = take;
args.skip = skip;
}
args.include = {
attendees: true,
user: true,
+12 -1
View File
@@ -2,6 +2,8 @@ import type { NextApiRequest } from "next";
import getBookingDataSchemaForApi from "@calcom/features/bookings/lib/getBookingDataSchemaForApi";
import handleNewBooking from "@calcom/features/bookings/lib/handleNewBooking";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers";
@@ -218,7 +220,16 @@ async function handler(req: NextApiRequest) {
req.userId = requestedUserId || userId;
}
return await handleNewBooking(req, getBookingDataSchemaForApi);
try {
return await handleNewBooking(req, getBookingDataSchemaForApi);
} catch (error: unknown) {
const knownError = error as Error;
if (knownError?.message === ErrorCode.NoAvailableUsersFound) {
throw new HttpError({ statusCode: 400, message: knownError.message });
}
throw error;
}
}
export default defaultResponder(handler);
+6 -1
View File
@@ -7,7 +7,12 @@ import { schemaUserReadPublic } from "~/lib/validations/user";
async function handler({ userId }: NextApiRequest) {
const data = await prisma.user.findUniqueOrThrow({ where: { id: userId } });
return { user: schemaUserReadPublic.parse(data) };
return {
user: schemaUserReadPublic.parse({
...data,
avatar: data.avatarUrl,
}),
};
}
export default defaultResponder(handler);
+4 -1
View File
@@ -45,7 +45,10 @@ export async function getHandler(req: NextApiRequest) {
if (!isSystemWideAdmin && query.userId !== req.userId)
throw new HttpError({ statusCode: 403, message: "Forbidden" });
const data = await prisma.user.findUnique({ where: { id: query.userId } });
const user = schemaUserReadPublic.parse(data);
const user = schemaUserReadPublic.parse({
...data,
avatar: data?.avatarUrl,
});
return { user };
}
+12 -1
View File
@@ -2,7 +2,9 @@ import type { NextApiRequest } from "next";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
import { uploadAvatar } from "@calcom/lib/server/avatar";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { schemaQueryUserId } from "~/lib/validations/shared/queryUserId";
import { schemaUserEditBodyParams, schemaUserReadPublic } from "~/lib/validations/user";
@@ -101,7 +103,8 @@ export async function patchHandler(req: NextApiRequest) {
if (!isSystemWideAdmin && query.userId !== req.userId)
throw new HttpError({ statusCode: 403, message: "Forbidden" });
const body = await schemaUserEditBodyParams.parseAsync(req.body);
const { avatar, ...body }: { avatar?: string | undefined } & Prisma.UserUpdateInput =
await schemaUserEditBodyParams.parseAsync(req.body);
// disable role or branding changes unless admin.
if (!isSystemWideAdmin) {
if (body.role) body.role = undefined;
@@ -119,6 +122,14 @@ export async function patchHandler(req: NextApiRequest) {
message: "Bad request: Invalid default schedule id",
});
}
if (avatar) {
body.avatarUrl = await uploadAvatar({
userId: query.userId,
avatar: await (await import("@calcom/lib/server/resizeBase64Image")).resizeBase64Image(avatar),
});
}
const data = await prisma.user.update({
where: { id: query.userId },
data: body,
-5
View File
@@ -1,5 +0,0 @@
import { init as SentryInit } from "@sentry/nextjs";
SentryInit({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
});
-6
View File
@@ -1,6 +0,0 @@
import { init as SentryInit } from "@sentry/nextjs";
SentryInit({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
tracesSampleRate: 1.0,
});
@@ -0,0 +1,129 @@
import prismaMock from "../../../../../../../../../tests/libs/__mocks__/prismaMock";
import type { Request, Response } from "express";
import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http";
import { describe, expect, test, vi, afterEach } from "vitest";
import {
getTranscriptsAccessLinkFromRecordingId,
checkIfRoomNameMatchesInRecording,
} from "@calcom/core/videoClient";
import { buildBooking } from "@calcom/lib/test/builder";
import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers";
import authMiddleware from "../../../../../../pages/api/bookings/[id]/_auth-middleware";
import handler from "../../../../../../pages/api/bookings/[id]/transcripts/[recordingId]/_get";
type CustomNextApiRequest = NextApiRequest & Request;
type CustomNextApiResponse = NextApiResponse & Response;
vi.mock("@calcom/core/videoClient", () => {
return {
getTranscriptsAccessLinkFromRecordingId: vi.fn(),
checkIfRoomNameMatchesInRecording: vi.fn(),
};
});
vi.mock("~/lib/utils/retrieveScopedAccessibleUsers", () => {
return {
getAccessibleUsers: vi.fn(),
};
});
afterEach(() => {
vi.resetAllMocks();
});
const mockGetTranscripts = () => {
const downloadLinks = [{ format: "json", link: "https://URL1" }];
vi.mocked(getTranscriptsAccessLinkFromRecordingId).mockResolvedValue(downloadLinks);
vi.mocked(checkIfRoomNameMatchesInRecording).mockResolvedValue(true);
return downloadLinks;
};
const recordingId = "abc-xyz";
describe("GET /api/bookings/[id]/transcripts/[recordingId]", () => {
test("Returns transcripts if user is system-wide admin", async () => {
const adminUserId = 1;
const userId = 2;
const bookingId = 1111;
prismaMock.booking.findUnique.mockResolvedValue(
buildBooking({
id: bookingId,
userId,
references: [
{
id: 1,
type: "daily_video",
uid: "17OHkCH53pBa03FhxMbw",
meetingId: "17OHkCH53pBa03FhxMbw",
meetingPassword: "password",
meetingUrl: "https://URL",
},
],
})
);
const mockedTranscripts = mockGetTranscripts();
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "GET",
body: {},
query: {
id: bookingId,
recordingId,
},
});
req.isSystemWideAdmin = true;
req.userId = adminUserId;
await authMiddleware(req);
await handler(req, res);
expect(res.statusCode).toBe(200);
expect(JSON.parse(res._getData())).toEqual(mockedTranscripts);
});
test("Allows GET transcripts when user is org-wide admin", async () => {
const adminUserId = 1;
const memberUserId = 10;
const bookingId = 3333;
prismaMock.booking.findUnique.mockResolvedValue(
buildBooking({
id: bookingId,
userId: memberUserId,
references: [
{ id: 1, type: "daily_video", uid: "17OHkCH53pBa03FhxMbw", meetingId: "17OHkCH53pBa03FhxMbw" },
],
})
);
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "GET",
body: {},
query: {
id: bookingId,
recordingId,
},
});
req.userId = adminUserId;
req.isOrganizationOwnerOrAdmin = true;
mockGetTranscripts();
vi.mocked(getAccessibleUsers).mockResolvedValue([memberUserId]);
await authMiddleware(req);
await handler(req, res);
expect(res.statusCode).toBe(200);
});
});
+1
View File
@@ -2,5 +2,6 @@ const rootConfig = require("../../../packages/config/prettier-preset");
module.exports = {
...rootConfig,
importOrder: ["^./instrument", ...rootConfig.importOrder],
importOrderParserPlugins: ["typescript", "decorators-legacy"],
};
+7 -5
View File
@@ -9,8 +9,8 @@
"build": "yarn dev:build && nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"dev:build:watch": "yarn workspace @calcom/platform-constants build:watch & yarn workspace @calcom/platform-utils build:watch & yarn workspace @calcom/platform-types build:watch & yarn workspace @calcom/platform-libraries build:watch",
"dev:build": "yarn workspace @calcom/platform-constants build && yarn workspace @calcom/platform-utils build && yarn workspace @calcom/platform-types build && yarn workspace @calcom/platform-libraries build",
"dev:build:watch": "yarn workspace @calcom/platform-constants build:watch & yarn workspace @calcom/platform-utils build:watch & yarn workspace @calcom/platform-types build:watch",
"dev:build": "yarn workspace @calcom/platform-constants build && yarn workspace @calcom/platform-utils build && yarn workspace @calcom/platform-types build",
"dev": "yarn dev:build && docker-compose up -d && yarn copy-swagger-module && yarn start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node ./dist/apps/api/v2/src/main.js",
@@ -25,11 +25,13 @@
},
"dependencies": {
"@calcom/platform-constants": "*",
"@calcom/platform-libraries": "*",
"@calcom/platform-libraries-0.0.2": "npm:@calcom/platform-libraries@0.0.2",
"@calcom/platform-libraries-0.0.4": "npm:@calcom/platform-libraries@0.0.4",
"@calcom/platform-types": "*",
"@calcom/platform-utils": "*",
"@calcom/prisma": "*",
"@golevelup/ts-jest": "^0.4.0",
"@microsoft/microsoft-graph-types-beta": "^0.42.0-preview",
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.1.1",
"@nestjs/core": "^10.0.0",
@@ -38,8 +40,7 @@
"@nestjs/platform-express": "^10.0.0",
"@nestjs/swagger": "^7.3.0",
"@nestjs/throttler": "^5.1.2",
"@sentry/node": "^7.86.0",
"@sentry/tracing": "^7.86.0",
"@sentry/node": "^8.8.0",
"body-parser": "^1.20.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
@@ -55,6 +56,7 @@
"next-auth": "^4.22.1",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"querystring": "^0.2.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1",
"stripe": "^15.3.0",
-2
View File
@@ -50,8 +50,6 @@ import { AppController } from "./app.controller";
EndpointsModule,
AuthModule,
JwtModule,
//register prefix for all routes in EndpointsModule
RouterModule.register([{ path: "/v2", module: EndpointsModule }]),
],
controllers: [AppController],
providers: [
+36 -15
View File
@@ -1,26 +1,43 @@
import { getEnv } from "@/env";
import "./instrument";
import { HttpExceptionFilter } from "@/filters/http-exception.filter";
import { PrismaExceptionFilter } from "@/filters/prisma-exception.filter";
import { SentryFilter } from "@/filters/sentry-exception.filter";
import { ZodExceptionFilter } from "@/filters/zod-exception.filter";
import type { ValidationError } from "@nestjs/common";
import { BadRequestException, ValidationPipe, VersioningType } from "@nestjs/common";
import { HttpAdapterHost } from "@nestjs/core";
import { BaseExceptionFilter, HttpAdapterHost } from "@nestjs/core";
import type { NestExpressApplication } from "@nestjs/platform-express";
import * as Sentry from "@sentry/node";
import * as cookieParser from "cookie-parser";
import { Request } from "express";
import helmet from "helmet";
import { X_CAL_CLIENT_ID, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
import {
API_VERSIONS,
VERSION_2024_04_15,
API_VERSIONS_ENUM,
CAL_API_VERSION_HEADER,
X_CAL_CLIENT_ID,
X_CAL_SECRET_KEY,
} from "@calcom/platform-constants";
import { TRPCExceptionFilter } from "./filters/trpc-exception.filter";
export const bootstrap = (app: NestExpressApplication): NestExpressApplication => {
app.enableShutdownHooks();
app.enableVersioning({
type: VersioningType.URI,
prefix: "v",
defaultVersion: "1",
type: VersioningType.CUSTOM,
extractor: (request: unknown) => {
const headerVersion = (request as Request)?.headers[CAL_API_VERSION_HEADER] as string | undefined;
console.log("asap header headerVersion", headerVersion);
if (headerVersion && API_VERSIONS.includes(headerVersion as API_VERSIONS_ENUM)) {
console.log("asap return header headerVersion", headerVersion);
return headerVersion;
}
return VERSION_2024_04_15;
},
defaultVersion: VERSION_2024_04_15,
});
app.use(helmet());
@@ -28,7 +45,15 @@ export const bootstrap = (app: NestExpressApplication): NestExpressApplication =
app.enableCors({
origin: "*",
methods: ["GET", "PATCH", "DELETE", "HEAD", "POST", "PUT", "OPTIONS"],
allowedHeaders: [X_CAL_CLIENT_ID, X_CAL_SECRET_KEY, "Accept", "Authorization", "Content-Type", "Origin"],
allowedHeaders: [
X_CAL_CLIENT_ID,
X_CAL_SECRET_KEY,
CAL_API_VERSION_HEADER,
"Accept",
"Authorization",
"Content-Type",
"Origin",
],
maxAge: 86_400,
});
@@ -46,15 +71,11 @@ export const bootstrap = (app: NestExpressApplication): NestExpressApplication =
})
);
if (process.env.SENTRY_DSN) {
Sentry.init({
dsn: getEnv("SENTRY_DSN"),
});
}
// Exception filters, new filters go at the bottom, keep the order
const { httpAdapter } = app.get(HttpAdapterHost);
app.useGlobalFilters(new SentryFilter(httpAdapter));
if (process.env.SENTRY_DSN) {
Sentry.setupNestErrorHandler(app, new BaseExceptionFilter(httpAdapter));
}
app.useGlobalFilters(new PrismaExceptionFilter());
app.useGlobalFilters(new ZodExceptionFilter());
app.useGlobalFilters(new HttpExceptionFilter());
@@ -2,11 +2,10 @@ import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { GetBookingOutput } from "@/ee/bookings/outputs/get-booking.output";
import { GetBookingsOutput } from "@/ee/bookings/outputs/get-bookings.output";
import { CreateScheduleInput } from "@/ee/schedules/inputs/create-schedule.input";
import { SchedulesModule } from "@/ee/schedules/schedules.module";
import { SchedulesService } from "@/ee/schedules/services/schedules.service";
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";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { AvailabilitiesModule } from "@/modules/availabilities/availabilities.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { UsersModule } from "@/modules/users/users.module";
import { INestApplication } from "@nestjs/common";
@@ -20,7 +19,7 @@ import { UserRepositoryFixture } from "test/fixtures/repository/users.repository
import { withAccessTokenAuth } from "test/utils/withAccessTokenAuth";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
import { handleNewBooking } from "@calcom/platform-libraries";
import { handleNewBooking } from "@calcom/platform-libraries-0.0.2";
import { ApiSuccessResponse, ApiResponse } from "@calcom/platform-types";
describe("Bookings Endpoints", () => {
@@ -29,7 +28,7 @@ describe("Bookings Endpoints", () => {
let userRepositoryFixture: UserRepositoryFixture;
let bookingsRepositoryFixture: BookingsRepositoryFixture;
let schedulesService: SchedulesService;
let schedulesService: SchedulesService_2024_04_15;
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
const userEmail = "bookings-controller-e2e@api.com";
@@ -43,7 +42,7 @@ describe("Bookings Endpoints", () => {
const moduleRef = await withAccessTokenAuth(
userEmail,
Test.createTestingModule({
imports: [AppModule, PrismaModule, AvailabilitiesModule, UsersModule, SchedulesModule],
imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15],
})
)
.overrideGuard(PermissionsGuard)
@@ -55,13 +54,13 @@ describe("Bookings Endpoints", () => {
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef);
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
schedulesService = moduleRef.get<SchedulesService>(SchedulesService);
schedulesService = moduleRef.get<SchedulesService_2024_04_15>(SchedulesService_2024_04_15);
user = await userRepositoryFixture.create({
email: userEmail,
});
const userSchedule: CreateScheduleInput = {
const userSchedule: CreateScheduleInput_2024_04_15 = {
name: "working time",
timeZone: "Europe/Rome",
isDefault: true,
@@ -2,6 +2,7 @@ import { CreateBookingInput } from "@/ee/bookings/inputs/create-booking.input";
import { CreateRecurringBookingInput } from "@/ee/bookings/inputs/create-recurring-booking.input";
import { GetBookingOutput } from "@/ee/bookings/outputs/get-booking.output";
import { GetBookingsOutput } from "@/ee/bookings/outputs/get-bookings.output";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
import { AccessTokenGuard } from "@/modules/auth/guards/access-token/access-token.guard";
@@ -37,14 +38,14 @@ import {
getBookingInfo,
handleCancelBooking,
getBookingForReschedule,
} from "@calcom/platform-libraries";
} from "@calcom/platform-libraries-0.0.2";
import {
handleNewBooking,
BookingResponse,
HttpError,
handleNewRecurringBooking,
handleInstantMeeting,
} from "@calcom/platform-libraries";
} from "@calcom/platform-libraries-0.0.2";
import { GetBookingsInput, CancelBookingInput, Status } from "@calcom/platform-types";
import { ApiResponse } from "@calcom/platform-types";
import { PrismaClient } from "@calcom/prisma";
@@ -72,8 +73,8 @@ const DEFAULT_PLATFORM_PARAMS = {
};
@Controller({
path: "/bookings",
version: "2",
path: "/v2/bookings",
version: API_VERSIONS_VALUES,
})
@UseGuards(PermissionsGuard)
@DocsTags("Bookings")
@@ -1,7 +1,7 @@
import { CreateBookingInput } from "@/ee/bookings/inputs/create-booking.input";
import { IsBoolean, IsNumber, IsOptional } from "class-validator";
import type { AppsStatus } from "@calcom/platform-libraries";
import type { AppsStatus } from "@calcom/platform-libraries-0.0.2";
export class CreateRecurringBookingInput extends CreateBookingInput {
@IsBoolean()
@@ -0,0 +1,211 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
import { HttpExceptionFilter } from "@/filters/http-exception.filter";
import { PrismaExceptionFilter } from "@/filters/prisma-exception.filter";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
import { INestApplication } from "@nestjs/common";
import { NestExpressApplication } from "@nestjs/platform-express";
import { Test } from "@nestjs/testing";
import { PlatformOAuthClient, Team, User, Credential } from "@prisma/client";
import * as request from "supertest";
import { CredentialsRepositoryFixture } from "test/fixtures/repository/credentials.repository.fixture";
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
import { TokensRepositoryFixture } from "test/fixtures/repository/tokens.repository.fixture";
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
import {
GOOGLE_CALENDAR,
OFFICE_365_CALENDAR,
GOOGLE_CALENDAR_TYPE,
GOOGLE_CALENDAR_ID,
} from "@calcom/platform-constants";
import { OFFICE_365_CALENDAR_ID, OFFICE_365_CALENDAR_TYPE } from "@calcom/platform-constants";
const CLIENT_REDIRECT_URI = "http://localhost:5555";
class CalendarsServiceMock {
async getCalendars() {
return {
connectedCalendars: [
{
integration: {
type: "google_calendar",
},
},
],
};
}
}
describe("Platform Calendars Endpoints", () => {
let app: INestApplication;
let oAuthClient: PlatformOAuthClient;
let organization: Team;
let userRepositoryFixture: UserRepositoryFixture;
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
let teamRepositoryFixture: TeamRepositoryFixture;
let tokensRepositoryFixture: TokensRepositoryFixture;
let credentialsRepositoryFixture: CredentialsRepositoryFixture;
let user: User;
let office365Credentials: Credential;
let googleCalendarCredentials: Credential;
let accessTokenSecret: string;
let refreshTokenSecret: string;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
providers: [PrismaExceptionFilter, HttpExceptionFilter],
imports: [AppModule, UsersModule, TokensModule],
})
.overrideGuard(PermissionsGuard)
.useValue({
canActivate: () => true,
})
.overrideProvider(CalendarsService)
.useClass(CalendarsServiceMock)
.compile();
app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication);
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
tokensRepositoryFixture = new TokensRepositoryFixture(moduleRef);
credentialsRepositoryFixture = new CredentialsRepositoryFixture(moduleRef);
organization = await teamRepositoryFixture.create({ name: "organization" });
oAuthClient = await createOAuthClient(organization.id);
user = await userRepositoryFixture.createOAuthManagedUser("office365-connect@gmail.com", oAuthClient.id);
const tokens = await tokensRepositoryFixture.createTokens(user.id, oAuthClient.id);
accessTokenSecret = tokens.accessToken;
refreshTokenSecret = tokens.refreshToken;
await app.init();
});
async function createOAuthClient(organizationId: number) {
const data = {
logo: "logo-url",
name: "name",
redirectUris: [CLIENT_REDIRECT_URI],
permissions: 32,
};
const secret = "secret";
const client = await oauthClientRepositoryFixture.create(organizationId, data, secret);
return client;
}
it("should be defined", () => {
expect(oauthClientRepositoryFixture).toBeDefined();
expect(userRepositoryFixture).toBeDefined();
expect(oAuthClient).toBeDefined();
expect(accessTokenSecret).toBeDefined();
expect(refreshTokenSecret).toBeDefined();
expect(user).toBeDefined();
});
it(`/GET/v2/calendars/${OFFICE_365_CALENDAR}/connect: it should respond 401 with invalid access token`, async () => {
await request(app.getHttpServer())
.get(`/v2/calendars/${OFFICE_365_CALENDAR}/connect`)
.set("Authorization", `Bearer invalid_access_token`)
.expect(401);
});
it(`/GET/v2/calendars/${OFFICE_365_CALENDAR}/connect: it should redirect to auth-url for office 365 calendar oauth with valid access token `, async () => {
const response = await request(app.getHttpServer())
.get(`/v2/calendars/${OFFICE_365_CALENDAR}/connect`)
.set("Authorization", `Bearer ${accessTokenSecret}`)
.set("Origin", CLIENT_REDIRECT_URI)
.expect(200);
const data = response.body.data;
expect(data.authUrl).toBeDefined();
});
it(`/GET/v2/calendars/${GOOGLE_CALENDAR}/connect: it should redirect to auth-url for google calendar oauth with valid access token `, async () => {
const response = await request(app.getHttpServer())
.get(`/v2/calendars/${GOOGLE_CALENDAR}/connect`)
.set("Authorization", `Bearer ${accessTokenSecret}`)
.set("Origin", CLIENT_REDIRECT_URI)
.expect(200);
const data = response.body.data;
expect(data.authUrl).toBeDefined();
});
it(`/GET/v2/calendars/random-calendar/connect: it should respond 400 with a message saying the calendar type is invalid`, async () => {
await request(app.getHttpServer())
.get(`/v2/calendars/random-calendar/connect`)
.set("Authorization", `Bearer ${accessTokenSecret}`)
.set("Origin", CLIENT_REDIRECT_URI)
.expect(400);
});
it(`/GET/v2/calendars/${OFFICE_365_CALENDAR}/save: without access token`, async () => {
await request(app.getHttpServer())
.get(
`/v2/calendars/${OFFICE_365_CALENDAR}/save?state=accessToken=${accessTokenSecret}&code=4/0AfJohXmBuT7QVrEPlAJLBu4ZcSnyj5jtDoJqSW_riPUhPXQ70RPGkOEbVO3xs-OzQwpPQw&scope=User.Read%20Calendars.Read%20Calendars.ReadWrite%20offline_access`
)
.expect(400);
});
it(`/GET/v2/calendars/${OFFICE_365_CALENDAR}/save: without origin`, async () => {
await request(app.getHttpServer())
.get(
`/v2/calendars/${OFFICE_365_CALENDAR}/save?state=accessToken=${accessTokenSecret}&code=4/0AfJohXmBuT7QVrEPlAJLBu4ZcSnyj5jtDoJqSW_riPUhPXQ70RPGkOEbVO3xs-OzQwpPQw&scope=User.Read%20Calendars.Read%20Calendars.ReadWrite%20offline_access`
)
.expect(400);
});
it(`/GET/v2/calendars/${OFFICE_365_CALENDAR}/check without access token`, async () => {
await request(app.getHttpServer()).get(`/v2/calendars/${OFFICE_365_CALENDAR}/check`).expect(401);
});
it(`/GET/v2/calendars/${OFFICE_365_CALENDAR}/check with no credentials`, async () => {
await request(app.getHttpServer())
.get(`/v2/calendars/${OFFICE_365_CALENDAR}/check`)
.set("Authorization", `Bearer ${accessTokenSecret}`)
.set("Origin", CLIENT_REDIRECT_URI)
.expect(400);
});
it(`/GET/v2/calendars/${OFFICE_365_CALENDAR}/check with access token, origin and office365 credentials`, async () => {
office365Credentials = await credentialsRepositoryFixture.create(
OFFICE_365_CALENDAR_TYPE,
{},
user.id,
OFFICE_365_CALENDAR_ID
);
await request(app.getHttpServer())
.get(`/v2/calendars/${OFFICE_365_CALENDAR}/check`)
.set("Authorization", `Bearer ${accessTokenSecret}`)
.set("Origin", CLIENT_REDIRECT_URI)
.expect(200);
});
it(`/GET/v2/calendars/${GOOGLE_CALENDAR}/check with access token, origin and google calendar credentials`, async () => {
googleCalendarCredentials = await credentialsRepositoryFixture.create(
GOOGLE_CALENDAR_TYPE,
{},
user.id,
GOOGLE_CALENDAR_ID
);
await request(app.getHttpServer())
.get(`/v2/calendars/${GOOGLE_CALENDAR}/check`)
.set("Authorization", `Bearer ${accessTokenSecret}`)
.set("Origin", CLIENT_REDIRECT_URI)
.expect(200);
});
afterAll(async () => {
await oauthClientRepositoryFixture.delete(oAuthClient.id);
await teamRepositoryFixture.delete(organization.id);
await credentialsRepositoryFixture.delete(office365Credentials.id);
await credentialsRepositoryFixture.delete(googleCalendarCredentials.id);
await userRepositoryFixture.deleteByEmail(user.email);
await app.close();
});
});
@@ -0,0 +1,12 @@
import { Request } from "express";
import { ApiResponse } from "@calcom/platform-types";
export interface CalendarApp {
save(state: string, code: string, origin: string): Promise<{ url: string }>;
check(userId: number): Promise<ApiResponse>;
}
export interface OAuthCalendarApp extends CalendarApp {
connect(authorization: string, req: Request): Promise<ApiResponse<{ authUrl: string }>>;
}
@@ -1,13 +1,25 @@
import { CalendarsController } from "@/ee/calendars/controllers/calendars.controller";
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
import { GoogleCalendarService } from "@/ee/calendars/services/gcal.service";
import { OutlookService } from "@/ee/calendars/services/outlook.service";
import { AppsRepository } from "@/modules/apps/apps.repository";
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { SelectedCalendarsRepository } from "@/modules/selected-calendars/selected-calendars.repository";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule, UsersModule],
providers: [CredentialsRepository, CalendarsService],
imports: [PrismaModule, UsersModule, TokensModule],
providers: [
CredentialsRepository,
CalendarsService,
OutlookService,
GoogleCalendarService,
SelectedCalendarsRepository,
AppsRepository,
],
controllers: [CalendarsController],
exports: [CalendarsService],
})
@@ -1,24 +1,48 @@
import { GetBusyTimesOutput } from "@/ee/calendars/outputs/busy-times.output";
import { ConnectedCalendarsOutput } from "@/ee/calendars/outputs/connected-calendars.output";
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
import { GoogleCalendarService } from "@/ee/calendars/services/gcal.service";
import { OutlookService } from "@/ee/calendars/services/outlook.service";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
import { AccessTokenGuard } from "@/modules/auth/guards/access-token/access-token.guard";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { UserWithProfile } from "@/modules/users/users.repository";
import { Controller, Get, UseGuards, Query } from "@nestjs/common";
import {
Controller,
Get,
UseGuards,
Query,
HttpStatus,
HttpCode,
Req,
Param,
Headers,
Redirect,
BadRequestException,
} from "@nestjs/common";
import { ApiTags as DocsTags } from "@nestjs/swagger";
import { Request } from "express";
import { z } from "zod";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { CalendarBusyTimesInput } from "@calcom/platform-types";
import { APPS_READ } from "@calcom/platform-constants";
import { SUCCESS_STATUS, CALENDARS, GOOGLE_CALENDAR, OFFICE_365_CALENDAR } from "@calcom/platform-constants";
import { ApiResponse, CalendarBusyTimesInput } from "@calcom/platform-types";
@Controller({
path: "/calendars",
version: "2",
path: "/v2/calendars",
version: API_VERSIONS_VALUES,
})
@UseGuards(AccessTokenGuard)
@DocsTags("Calendars")
export class CalendarsController {
constructor(private readonly calendarsService: CalendarsService) {}
constructor(
private readonly calendarsService: CalendarsService,
private readonly outlookService: OutlookService,
private readonly googleCalendarService: GoogleCalendarService
) {}
@UseGuards(AccessTokenGuard)
@Get("/busy-times")
async getBusyTimes(
@Query() queryParams: CalendarBusyTimesInput,
@@ -47,6 +71,7 @@ export class CalendarsController {
}
@Get("/")
@UseGuards(AccessTokenGuard)
async getCalendars(@GetUser("id") userId: number): Promise<ConnectedCalendarsOutput> {
const calendars = await this.calendarsService.getCalendars(userId);
@@ -55,4 +80,74 @@ export class CalendarsController {
data: calendars,
};
}
@UseGuards(AccessTokenGuard)
@Get("/:calendar/connect")
@HttpCode(HttpStatus.OK)
async redirect(
@Req() req: Request,
@Headers("Authorization") authorization: string,
@Param("calendar") calendar: string,
@Query("redir") redir?: string | null
): Promise<ApiResponse<{ authUrl: string }>> {
switch (calendar) {
case OFFICE_365_CALENDAR:
return await this.outlookService.connect(authorization, req, redir ?? "");
case GOOGLE_CALENDAR:
return await this.googleCalendarService.connect(authorization, req, redir ?? "");
default:
throw new BadRequestException(
"Invalid calendar type, available calendars are: ",
CALENDARS.join(", ")
);
}
}
@Get("/:calendar/save")
@HttpCode(HttpStatus.OK)
@Redirect(undefined, 301)
async save(
@Query("state") state: string,
@Query("code") code: string,
@Param("calendar") calendar: string
): Promise<{ url: string }> {
// state params contains our user access token
const stateParams = new URLSearchParams(state);
const { accessToken, origin, redir } = z
.object({ accessToken: z.string(), origin: z.string(), redir: z.string().nullish().optional() })
.parse({
accessToken: stateParams.get("accessToken"),
origin: stateParams.get("origin"),
redir: stateParams.get("redir"),
});
switch (calendar) {
case OFFICE_365_CALENDAR:
return await this.outlookService.save(code, accessToken, origin, redir ?? "");
case GOOGLE_CALENDAR:
return await this.googleCalendarService.save(code, accessToken, origin, redir ?? "");
default:
throw new BadRequestException(
"Invalid calendar type, available calendars are: ",
CALENDARS.join(", ")
);
}
}
@Get("/:calendar/check")
@HttpCode(HttpStatus.OK)
@UseGuards(AccessTokenGuard, PermissionsGuard)
@Permissions([APPS_READ])
async check(@GetUser("id") userId: number, @Param("calendar") calendar: string): Promise<ApiResponse> {
switch (calendar) {
case OFFICE_365_CALENDAR:
return await this.outlookService.check(userId);
case GOOGLE_CALENDAR:
return await this.googleCalendarService.check(userId);
default:
throw new BadRequestException(
"Invalid calendar type, available calendars are: ",
CALENDARS.join(", ")
);
}
}
}
@@ -1,3 +1,4 @@
import { AppsRepository } from "@/modules/apps/apps.repository";
import {
CredentialsRepository,
CredentialsWithUserEmail,
@@ -11,21 +12,27 @@ import {
UnauthorizedException,
NotFoundException,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { User } from "@prisma/client";
import { DateTime } from "luxon";
import { z } from "zod";
import { getConnectedDestinationCalendars } from "@calcom/platform-libraries";
import { getBusyCalendarTimes } from "@calcom/platform-libraries";
import { getConnectedDestinationCalendars } from "@calcom/platform-libraries-0.0.2";
import { getBusyCalendarTimes } from "@calcom/platform-libraries-0.0.2";
import { Calendar } from "@calcom/platform-types";
import { PrismaClient } from "@calcom/prisma";
@Injectable()
export class CalendarsService {
private oAuthCalendarResponseSchema = z.object({ client_id: z.string(), client_secret: z.string() });
constructor(
private readonly usersRepository: UsersRepository,
private readonly credentialsRepository: CredentialsRepository,
private readonly appsRepository: AppsRepository,
private readonly dbRead: PrismaReadService,
private readonly dbWrite: PrismaWriteService
private readonly dbWrite: PrismaWriteService,
private readonly config: ConfigService
) {}
async getCalendars(userId: number) {
@@ -110,4 +117,24 @@ export class CalendarsService {
});
return composedSelectedCalendars;
}
async getAppKeys(appName: string) {
const app = await this.appsRepository.getAppBySlug(appName);
if (!app) {
throw new NotFoundException();
}
const { client_id, client_secret } = this.oAuthCalendarResponseSchema.parse(app.keys);
if (!client_id) {
throw new NotFoundException();
}
if (!client_secret) {
throw new NotFoundException();
}
return { client_id, client_secret };
}
}
@@ -0,0 +1,162 @@
import { OAuthCalendarApp } from "@/ee/calendars/calendars.interface";
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
import { AppsRepository } from "@/modules/apps/apps.repository";
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
import { SelectedCalendarsRepository } from "@/modules/selected-calendars/selected-calendars.repository";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { Logger, NotFoundException } from "@nestjs/common";
import { BadRequestException, UnauthorizedException } from "@nestjs/common";
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Prisma } from "@prisma/client";
import { Request } from "express";
import { google } from "googleapis";
import { z } from "zod";
import { SUCCESS_STATUS, GOOGLE_CALENDAR_TYPE } from "@calcom/platform-constants";
const CALENDAR_SCOPES = [
"https://www.googleapis.com/auth/calendar.readonly",
"https://www.googleapis.com/auth/calendar.events",
];
@Injectable()
export class GoogleCalendarService implements OAuthCalendarApp {
private redirectUri = `${this.config.get("api.url")}/gcal/oauth/save`;
private gcalResponseSchema = z.object({ client_id: z.string(), client_secret: z.string() });
private logger = new Logger("GcalService");
constructor(
private readonly config: ConfigService,
private readonly appsRepository: AppsRepository,
private readonly credentialRepository: CredentialsRepository,
private readonly calendarsService: CalendarsService,
private readonly tokensRepository: TokensRepository,
private readonly selectedCalendarsRepository: SelectedCalendarsRepository
) {}
async connect(
authorization: string,
req: Request,
redir?: string
): Promise<{ status: typeof SUCCESS_STATUS; data: { authUrl: string } }> {
const accessToken = authorization.replace("Bearer ", "");
const origin = req.get("origin") ?? req.get("host");
const redirectUrl = await await this.getCalendarRedirectUrl(accessToken, origin ?? "", redir);
return { status: SUCCESS_STATUS, data: { authUrl: redirectUrl } };
}
async save(code: string, accessToken: string, origin: string, redir?: string): Promise<{ url: string }> {
return await this.saveCalendarCredentialsAndRedirect(code, accessToken, origin, redir);
}
async check(userId: number): Promise<{ status: typeof SUCCESS_STATUS }> {
return await this.checkIfCalendarConnected(userId);
}
async getCalendarRedirectUrl(accessToken: string, origin: string, redir?: string) {
const oAuth2Client = await this.getOAuthClient(this.redirectUri);
const authUrl = oAuth2Client.generateAuthUrl({
access_type: "offline",
scope: CALENDAR_SCOPES,
prompt: "consent",
state: `accessToken=${accessToken}&origin=${origin}&redir=${redir ?? ""}`,
});
return authUrl;
}
async getOAuthClient(redirectUri: string) {
this.logger.log("Getting Google Calendar OAuth Client");
const app = await this.appsRepository.getAppBySlug("google-calendar");
if (!app) {
throw new NotFoundException();
}
const { client_id, client_secret } = this.gcalResponseSchema.parse(app.keys);
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirectUri);
return oAuth2Client;
}
async checkIfCalendarConnected(userId: number): Promise<{ status: typeof SUCCESS_STATUS }> {
const gcalCredentials = await this.credentialRepository.getByTypeAndUserId("google_calendar", userId);
if (!gcalCredentials) {
throw new BadRequestException("Credentials for google_calendar not found.");
}
if (gcalCredentials.invalid) {
throw new BadRequestException("Invalid google oauth credentials.");
}
const { connectedCalendars } = await this.calendarsService.getCalendars(userId);
const googleCalendar = connectedCalendars.find(
(cal: { integration: { type: string } }) => cal.integration.type === GOOGLE_CALENDAR_TYPE
);
if (!googleCalendar) {
throw new UnauthorizedException("Google Calendar not connected.");
}
if (googleCalendar.error?.message) {
throw new UnauthorizedException(googleCalendar.error?.message);
}
return { status: SUCCESS_STATUS };
}
async saveCalendarCredentialsAndRedirect(
code: string,
accessToken: string,
origin: string,
redir?: string
) {
// User chose not to authorize your app or didn't authorize your app
// redirect directly without oauth code
if (!code) {
return { url: redir || origin };
}
const parsedCode = z.string().parse(code);
const ownerId = await this.tokensRepository.getAccessTokenOwnerId(accessToken);
if (!ownerId) {
throw new UnauthorizedException("Invalid Access token.");
}
const oAuth2Client = await this.getOAuthClient(this.redirectUri);
const token = await oAuth2Client.getToken(parsedCode);
// Google oAuth Credentials are stored in token.tokens
const key = token.tokens;
const credential = await this.credentialRepository.createAppCredential(
GOOGLE_CALENDAR_TYPE,
key as Prisma.InputJsonValue,
ownerId
);
oAuth2Client.setCredentials(key);
const calendar = google.calendar({
version: "v3",
auth: oAuth2Client,
});
const cals = await calendar.calendarList.list({ fields: "items(id,summary,primary,accessRole)" });
const primaryCal = cals.data.items?.find((cal) => cal.primary);
if (primaryCal?.id) {
await this.selectedCalendarsRepository.createSelectedCalendar(
primaryCal.id,
credential.id,
ownerId,
GOOGLE_CALENDAR_TYPE
);
}
return { url: redir || origin };
}
}
@@ -0,0 +1,189 @@
import { OAuthCalendarApp } from "@/ee/calendars/calendars.interface";
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
import { SelectedCalendarsRepository } from "@/modules/selected-calendars/selected-calendars.repository";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import type { Calendar as OfficeCalendar } from "@microsoft/microsoft-graph-types-beta";
import { BadRequestException, UnauthorizedException } from "@nestjs/common";
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Request } from "express";
import { stringify } from "querystring";
import { z } from "zod";
import {
SUCCESS_STATUS,
OFFICE_365_CALENDAR,
OFFICE_365_CALENDAR_ID,
OFFICE_365_CALENDAR_TYPE,
} from "@calcom/platform-constants";
@Injectable()
export class OutlookService implements OAuthCalendarApp {
private redirectUri = `${this.config.get("api.url")}/calendars/${OFFICE_365_CALENDAR}/save`;
constructor(
private readonly config: ConfigService,
private readonly calendarsService: CalendarsService,
private readonly credentialRepository: CredentialsRepository,
private readonly tokensRepository: TokensRepository,
private readonly selectedCalendarsRepository: SelectedCalendarsRepository
) {}
async connect(
authorization: string,
req: Request,
redir?: string
): Promise<{ status: typeof SUCCESS_STATUS; data: { authUrl: string } }> {
const accessToken = authorization.replace("Bearer ", "");
const origin = req.get("origin") ?? req.get("host");
const redirectUrl = await await this.getCalendarRedirectUrl(accessToken, origin ?? "", redir);
return { status: SUCCESS_STATUS, data: { authUrl: redirectUrl } };
}
async save(code: string, accessToken: string, origin: string, redir?: string): Promise<{ url: string }> {
return await this.saveCalendarCredentialsAndRedirect(code, accessToken, origin, redir);
}
async check(userId: number): Promise<{ status: typeof SUCCESS_STATUS }> {
return await this.checkIfCalendarConnected(userId);
}
async getCalendarRedirectUrl(accessToken: string, origin: string, redir?: string) {
const { client_id } = await this.calendarsService.getAppKeys(OFFICE_365_CALENDAR_ID);
const scopes = ["User.Read", "Calendars.Read", "Calendars.ReadWrite", "offline_access"];
const params = {
response_type: "code",
scope: scopes.join(" "),
client_id,
prompt: "select_account",
redirect_uri: this.redirectUri,
state: `accessToken=${accessToken}&origin=${origin}&redir=${redir ?? ""}`,
};
const query = stringify(params);
const url = `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?${query}`;
return url;
}
async checkIfCalendarConnected(userId: number): Promise<{ status: typeof SUCCESS_STATUS }> {
const office365CalendarCredentials = await this.credentialRepository.getByTypeAndUserId(
"office365_calendar",
userId
);
if (!office365CalendarCredentials) {
throw new BadRequestException("Credentials for office_365_calendar not found.");
}
if (office365CalendarCredentials.invalid) {
throw new BadRequestException("Invalid office 365 calendar credentials.");
}
const { connectedCalendars } = await this.calendarsService.getCalendars(userId);
const office365Calendar = connectedCalendars.find(
(cal: { integration: { type: string } }) => cal.integration.type === OFFICE_365_CALENDAR_TYPE
);
if (!office365Calendar) {
throw new UnauthorizedException("Office 365 calendar not connected.");
}
if (office365Calendar.error?.message) {
throw new UnauthorizedException(office365Calendar.error?.message);
}
return {
status: SUCCESS_STATUS,
};
}
async getOAuthCredentials(code: string) {
const scopes = ["offline_access", "Calendars.Read", "Calendars.ReadWrite"];
const { client_id, client_secret } = await this.calendarsService.getAppKeys(OFFICE_365_CALENDAR_ID);
const toUrlEncoded = (payload: Record<string, string>) =>
Object.keys(payload)
.map((key) => `${key}=${encodeURIComponent(payload[key])}`)
.join("&");
const body = toUrlEncoded({
client_id,
grant_type: "authorization_code",
code,
scope: scopes.join(" "),
redirect_uri: this.redirectUri,
client_secret,
});
const response = await fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
},
body,
});
const responseBody = await response.json();
return responseBody;
}
async getDefaultCalendar(accessToken: string): Promise<OfficeCalendar> {
const response = await fetch("https://graph.microsoft.com/v1.0/me/calendar", {
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
});
const responseBody = await response.json();
return responseBody as OfficeCalendar;
}
async saveCalendarCredentialsAndRedirect(
code: string,
accessToken: string,
origin: string,
redir?: string
) {
// if code is not defined, user denied to authorize office 365 app, just redirect straight away
if (!code) {
return { url: redir || origin };
}
const parsedCode = z.string().parse(code);
const ownerId = await this.tokensRepository.getAccessTokenOwnerId(accessToken);
if (!ownerId) {
throw new UnauthorizedException("Invalid Access token.");
}
const office365OAuthCredentials = await this.getOAuthCredentials(parsedCode);
const defaultCalendar = await this.getDefaultCalendar(office365OAuthCredentials.access_token);
if (defaultCalendar?.id) {
const credential = await this.credentialRepository.createAppCredential(
OFFICE_365_CALENDAR_TYPE,
office365OAuthCredentials,
ownerId
);
await this.selectedCalendarsRepository.createSelectedCalendar(
defaultCalendar.id,
credential.id,
ownerId,
OFFICE_365_CALENDAR_TYPE
);
}
return {
url: redir || origin,
};
}
}
@@ -2,6 +2,8 @@ import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { EventTypesModule } from "@/ee/event-types/event-types.module";
import { CreateEventTypeInput } from "@/ee/event-types/inputs/create-event-type.input";
import { Editable } from "@/ee/event-types/inputs/enums/editable";
import { BaseField } from "@/ee/event-types/inputs/enums/field-type";
import { UpdateEventTypeInput } from "@/ee/event-types/inputs/update-event-type.input";
import { GetEventTypePublicOutput } from "@/ee/event-types/outputs/get-event-type-public.output";
import { GetEventTypeOutput } from "@/ee/event-types/outputs/get-event-type.output";
@@ -23,7 +25,12 @@ import { UserRepositoryFixture } from "test/fixtures/repository/users.repository
import { withAccessTokenAuth } from "test/utils/withAccessTokenAuth";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { EventTypesByViewer, EventTypesPublic } from "@calcom/platform-libraries";
import {
EventTypesByViewer,
EventTypesPublic,
eventTypeBookingFields,
eventTypeLocations,
} from "@calcom/platform-libraries-0.0.2";
import { ApiSuccessResponse } from "@calcom/platform-types";
describe("Event types Endpoints", () => {
@@ -197,6 +204,87 @@ describe("Event types Endpoints", () => {
});
});
it("should return 400 if param event type id is null", async () => {
const locations = [{ type: "inPerson", address: "123 Main St" }];
const body: UpdateEventTypeInput = {
locations,
};
return request(app.getHttpServer()).patch(`/api/v2/event-types/null`).send(body).expect(400);
});
it("should update event type locations", async () => {
const locations = [{ type: "inPerson", address: "123 Main St" }];
const body: UpdateEventTypeInput = {
locations,
};
return request(app.getHttpServer())
.patch(`/api/v2/event-types/${eventType.id}`)
.send(body)
.expect(200)
.then(async (response) => {
const responseBody: ApiSuccessResponse<EventType> = response.body;
const responseLocations = eventTypeLocations.parse(responseBody.data.locations);
expect(responseLocations).toBeDefined();
expect(responseLocations.length).toEqual(locations.length);
expect(responseLocations).toEqual(locations);
eventType.locations = responseLocations;
});
});
it("should update event type bookingFields", async () => {
const bookingFieldName = "location-name";
const bookingFields = [
{
name: bookingFieldName,
type: BaseField.radio,
label: "Location",
options: [
{
label: "Via Bari 10, Roma, 90119, Italy",
value: "Via Bari 10, Roma, 90119, Italy",
},
{
label: "Via Reale 28, Roma, 9001, Italy",
value: "Via Reale 28, Roma, 9001, Italy",
},
],
sources: [
{
id: "user",
type: "user",
label: "User",
fieldRequired: true,
},
],
editable: Editable.user,
required: true,
placeholder: "",
},
];
const body: UpdateEventTypeInput = {
bookingFields,
};
return request(app.getHttpServer())
.patch(`/api/v2/event-types/${eventType.id}`)
.send(body)
.expect(200)
.then(async (response) => {
const responseBody: ApiSuccessResponse<EventType> = response.body;
const responseBookingFields = eventTypeBookingFields.parse(responseBody.data.bookingFields);
expect(responseBookingFields).toBeDefined();
// note(Lauris): response bookingFields are already existing default bookingFields + the new one
const responseBookingField = responseBookingFields.find((field) => field.name === bookingFieldName);
expect(responseBookingField).toEqual(bookingFields[0]);
eventType.bookingFields = responseBookingFields;
});
});
it(`/GET/:id`, async () => {
const response = await request(app.getHttpServer())
.get(`/api/v2/event-types/${eventType.id}`)
@@ -1,4 +1,5 @@
import { CreateEventTypeInput } from "@/ee/event-types/inputs/create-event-type.input";
import { EventTypeIdParams } from "@/ee/event-types/inputs/event-type-id.input";
import { GetPublicEventTypeQueryParams } from "@/ee/event-types/inputs/get-public-event-type-query-params.input";
import { UpdateEventTypeInput } from "@/ee/event-types/inputs/update-event-type.input";
import { CreateEventTypeOutput } from "@/ee/event-types/outputs/create-event-type.output";
@@ -9,6 +10,7 @@ import { GetEventTypesPublicOutput } from "@/ee/event-types/outputs/get-event-ty
import { GetEventTypesData, GetEventTypesOutput } from "@/ee/event-types/outputs/get-event-types.output";
import { UpdateEventTypeOutput } from "@/ee/event-types/outputs/update-event-type.output";
import { EventTypesService } from "@/ee/event-types/services/event-types.service";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
import { AccessTokenGuard } from "@/modules/auth/guards/access-token/access-token.guard";
@@ -29,17 +31,18 @@ import {
Delete,
Query,
InternalServerErrorException,
ParseIntPipe,
} from "@nestjs/common";
import { ApiTags as DocsTags } from "@nestjs/swagger";
import { EVENT_TYPE_READ, EVENT_TYPE_WRITE, SUCCESS_STATUS } from "@calcom/platform-constants";
import { getPublicEvent } from "@calcom/platform-libraries";
import { getEventTypesByViewer } from "@calcom/platform-libraries";
import { getPublicEvent } from "@calcom/platform-libraries-0.0.2";
import { getEventTypesByViewer } from "@calcom/platform-libraries-0.0.2";
import { PrismaClient } from "@calcom/prisma";
@Controller({
path: "event-types",
version: "2",
path: "/v2/event-types",
version: API_VERSIONS_VALUES,
})
@UseGuards(PermissionsGuard)
@DocsTags("Event types")
@@ -68,7 +71,9 @@ export class EventTypesController {
@Permissions([EVENT_TYPE_READ])
@UseGuards(AccessTokenGuard)
async getEventType(
@Param("eventTypeId") eventTypeId: string,
@Param() params: EventTypeIdParams,
@Param("eventTypeId", ParseIntPipe) eventTypeId: number,
@GetUser() user: UserWithProfile
): Promise<GetEventTypeOutput> {
const eventType = await this.eventTypesService.getUserEventTypeForAtom(user, Number(eventTypeId));
@@ -144,7 +149,8 @@ export class EventTypesController {
@UseGuards(AccessTokenGuard)
@HttpCode(HttpStatus.OK)
async updateEventType(
@Param("eventTypeId") eventTypeId: number,
@Param() params: EventTypeIdParams,
@Param("eventTypeId", ParseIntPipe) eventTypeId: number,
@Body() body: UpdateEventTypeInput,
@GetUser() user: UserWithProfile
): Promise<UpdateEventTypeOutput> {
@@ -160,7 +166,8 @@ export class EventTypesController {
@Permissions([EVENT_TYPE_WRITE])
@UseGuards(AccessTokenGuard)
async deleteEventType(
@Param("eventTypeId") eventTypeId: number,
@Param() params: EventTypeIdParams,
@Param("eventTypeId", ParseIntPipe) eventTypeId: number,
@GetUser("id") userId: number
): Promise<DeleteEventTypeOutput> {
const eventType = await this.eventTypesService.deleteEventType(eventTypeId, userId);
@@ -4,7 +4,7 @@ import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { UserWithProfile } from "@/modules/users/users.repository";
import { Injectable } from "@nestjs/common";
import { getEventTypeById } from "@calcom/platform-libraries";
import { getEventTypeById } from "@calcom/platform-libraries-0.0.2";
import type { PrismaClient } from "@calcom/prisma";
@Injectable()
@@ -0,0 +1,6 @@
import { IsNumberString } from "class-validator";
export class EventTypeIdParams {
@IsNumberString()
eventTypeId!: number;
}
@@ -275,11 +275,11 @@ export class UpdateEventTypeInput {
// @IsOptional()
// parentId?: number;
// @IsOptional()
// @IsArray()
// @ValidateNested({ each: true })
// @Type(() => BookingField)
// bookingFields?: BookingField[];
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => BookingField)
bookingFields?: BookingField[];
// @IsString()
// @IsOptional()
@@ -9,8 +9,8 @@ import { SelectedCalendarsRepository } from "@/modules/selected-calendars/select
import { UserWithProfile, UsersRepository } from "@/modules/users/users.repository";
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
import { createEventType, updateEventType } from "@calcom/platform-libraries";
import { getEventTypesPublic, EventTypesPublic } from "@calcom/platform-libraries";
import { createEventType, updateEventType } from "@calcom/platform-libraries-0.0.2";
import { getEventTypesPublic, EventTypesPublic } from "@calcom/platform-libraries-0.0.2";
import { EventType } from "@calcom/prisma/client";
@Injectable()
+7 -52
View File
@@ -2,6 +2,7 @@ import { CalendarsService } from "@/ee/calendars/services/calendars.service";
import { GcalAuthUrlOutput } from "@/ee/gcal/outputs/auth-url.output";
import { GcalCheckOutput } from "@/ee/gcal/outputs/check.output";
import { GcalSaveRedirectOutput } from "@/ee/gcal/outputs/save-redirect.output";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { GCalService } from "@/modules/apps/services/gcal.service";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
@@ -40,8 +41,8 @@ const CALENDAR_SCOPES = [
// Controller for the GCalConnect Atom
@Controller({
path: "/gcal",
version: "2",
path: "/v2/gcal",
version: API_VERSIONS_VALUES,
})
@DocsTags("Google Calendar")
export class GcalController {
@@ -81,56 +82,10 @@ export class GcalController {
@Redirect(undefined, 301)
@HttpCode(HttpStatus.OK)
async save(@Query("state") state: string, @Query("code") code: string): Promise<GcalSaveRedirectOutput> {
const stateParams = new URLSearchParams(state);
const { accessToken, origin } = z
.object({ accessToken: z.string(), origin: z.string() })
.parse({ accessToken: stateParams.get("accessToken"), origin: stateParams.get("origin") });
// User chose not to authorize your app or didn't authorize your app
// redirect directly without oauth code
if (!code) {
return { url: origin };
}
const parsedCode = z.string().parse(code);
const ownerId = await this.tokensRepository.getAccessTokenOwnerId(accessToken);
if (!ownerId) {
throw new UnauthorizedException("Invalid Access token.");
}
const oAuth2Client = await this.gcalService.getOAuthClient(this.redirectUri);
const token = await oAuth2Client.getToken(parsedCode);
// Google oAuth Credentials are stored in token.tokens
const key = token.tokens;
const credential = await this.credentialRepository.createAppCredential(
GOOGLE_CALENDAR_TYPE,
key as Prisma.InputJsonValue,
ownerId
);
oAuth2Client.setCredentials(key);
const calendar = google.calendar({
version: "v3",
auth: oAuth2Client,
});
const cals = await calendar.calendarList.list({ fields: "items(id,summary,primary,accessRole)" });
const primaryCal = cals.data.items?.find((cal) => cal.primary);
if (primaryCal?.id) {
await this.selectedCalendarsRepository.createSelectedCalendar(
primaryCal.id,
credential.id,
ownerId,
GOOGLE_CALENDAR_TYPE
);
}
return { url: origin };
const url = new URL(this.config.get("api.url") + "/calendars/google/save");
url.searchParams.append("code", code);
url.searchParams.append("state", state);
return { url: url.href };
}
@Get("/check")
@@ -1,8 +1,7 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { SchedulesModule } from "@/ee/schedules/schedules.module";
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { AvailabilitiesModule } from "@/modules/availabilities/availabilities.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UpdateManagedUserInput } from "@/modules/users/inputs/update-managed-user.input";
@@ -34,14 +33,7 @@ describe("Me Endpoints", () => {
const moduleRef = await withAccessTokenAuth(
userEmail,
Test.createTestingModule({
imports: [
AppModule,
PrismaModule,
AvailabilitiesModule,
UsersModule,
TokensModule,
SchedulesModule,
],
imports: [AppModule, PrismaModule, UsersModule, TokensModule, SchedulesModule_2024_04_15],
})
)
.overrideGuard(PermissionsGuard)
@@ -118,13 +110,13 @@ describe("Me Endpoints", () => {
});
it("should not update user associated with access token given invalid time format", async () => {
const bodyWithIncorrectTimeFormat: UpdateManagedUserInput = { timeFormat: 100 };
const bodyWithIncorrectTimeFormat: UpdateManagedUserInput = { timeFormat: 100 as any };
return request(app.getHttpServer()).patch("/v2/me").send(bodyWithIncorrectTimeFormat).expect(400);
});
it("should not update user associated with access token given invalid week start", async () => {
const bodyWithIncorrectWeekStart: UpdateManagedUserInput = { weekStart: "waba luba dub dub" };
const bodyWithIncorrectWeekStart: UpdateManagedUserInput = { weekStart: "waba luba dub dub" as any };
return request(app.getHttpServer()).patch("/v2/me").send(bodyWithIncorrectWeekStart).expect(400);
});
+5 -4
View File
@@ -1,6 +1,7 @@
import { GetMeOutput } from "@/ee/me/outputs/get-me.output";
import { UpdateMeOutput } from "@/ee/me/outputs/update-me.output";
import { SchedulesService } from "@/ee/schedules/services/schedules.service";
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
import { AccessTokenGuard } from "@/modules/auth/guards/access-token/access-token.guard";
@@ -14,15 +15,15 @@ import { PROFILE_READ, PROFILE_WRITE, SUCCESS_STATUS } from "@calcom/platform-co
import { userSchemaResponse } from "@calcom/platform-types";
@Controller({
path: "/me",
version: "2",
path: "/v2/me",
version: API_VERSIONS_VALUES,
})
@UseGuards(AccessTokenGuard, PermissionsGuard)
@DocsTags("Me")
export class MeController {
constructor(
private readonly usersRepository: UsersRepository,
private readonly schedulesRepository: SchedulesService
private readonly schedulesRepository: SchedulesService_2024_04_15
) {}
@Get("/")
+2 -2
View File
@@ -1,11 +1,11 @@
import { MeController } from "@/ee/me/me.controller";
import { SchedulesModule } from "@/ee/schedules/schedules.module";
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
import { Module } from "@nestjs/common";
@Module({
imports: [UsersModule, SchedulesModule, TokensModule],
imports: [UsersModule, SchedulesModule_2024_04_15, TokensModule],
controllers: [MeController],
})
export class MeModule {}
@@ -4,7 +4,8 @@ import { EventTypesModule } from "@/ee/event-types/event-types.module";
import { GcalModule } from "@/ee/gcal/gcal.module";
import { MeModule } from "@/ee/me/me.module";
import { ProviderModule } from "@/ee/provider/provider.module";
import { SchedulesModule } from "@/ee/schedules/schedules.module";
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
import { SchedulesModule_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/schedules.module";
import { SlotsModule } from "@/modules/slots/slots.module";
import type { MiddlewareConsumer, NestModule } from "@nestjs/common";
import { Module } from "@nestjs/common";
@@ -13,7 +14,8 @@ import { Module } from "@nestjs/common";
imports: [
GcalModule,
ProviderModule,
SchedulesModule,
SchedulesModule_2024_04_15,
SchedulesModule_2024_06_11,
MeModule,
EventTypesModule,
CalendarsModule,
@@ -1,5 +1,6 @@
import { ProviderVerifyAccessTokenOutput } from "@/ee/provider/outputs/verify-access-token.output";
import { ProviderVerifyClientOutput } from "@/ee/provider/outputs/verify-client.output";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { AccessTokenGuard } from "@/modules/auth/guards/access-token/access-token.guard";
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
@@ -20,8 +21,8 @@ import { ApiTags as DocsTags } from "@nestjs/swagger";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
@Controller({
path: "/provider",
version: "2",
path: "/v2/provider",
version: API_VERSIONS_VALUES,
})
@DocsTags("Cal provider")
export class CalProviderController {
@@ -1,16 +0,0 @@
import { SchedulesController } from "@/ee/schedules/controllers/schedules.controller";
import { SchedulesRepository } from "@/ee/schedules/schedules.repository";
import { SchedulesService } from "@/ee/schedules/services/schedules.service";
import { AvailabilitiesModule } from "@/modules/availabilities/availabilities.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule, AvailabilitiesModule, UsersModule, TokensModule],
providers: [SchedulesRepository, SchedulesService],
controllers: [SchedulesController],
exports: [SchedulesService, SchedulesRepository],
})
export class SchedulesModule {}
@@ -1,12 +1,11 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { CreateScheduleInput } from "@/ee/schedules/inputs/create-schedule.input";
import { CreateScheduleOutput } from "@/ee/schedules/outputs/create-schedule.output";
import { GetSchedulesOutput } from "@/ee/schedules/outputs/get-schedules.output";
import { UpdateScheduleOutput } from "@/ee/schedules/outputs/update-schedule.output";
import { SchedulesModule } from "@/ee/schedules/schedules.module";
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
import { CreateScheduleOutput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/outputs/create-schedule.output";
import { GetSchedulesOutput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/outputs/get-schedules.output";
import { UpdateScheduleOutput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/outputs/update-schedule.output";
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { AvailabilitiesModule } from "@/modules/availabilities/availabilities.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
@@ -19,8 +18,8 @@ import { SchedulesRepositoryFixture } from "test/fixtures/repository/schedules.r
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
import { withAccessTokenAuth } from "test/utils/withAccessTokenAuth";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { UpdateScheduleInput } from "@calcom/platform-types";
import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_04_15 } from "@calcom/platform-constants";
import { UpdateScheduleInput_2024_04_15 } from "@calcom/platform-types";
describe("Schedules Endpoints", () => {
describe("User Authentication", () => {
@@ -32,7 +31,7 @@ describe("Schedules Endpoints", () => {
const userEmail = "schedules-controller-e2e@api.com";
let user: User;
let createdSchedule: CreateScheduleOutput["data"];
let createdSchedule: CreateScheduleOutput_2024_04_15["data"];
const defaultAvailabilityDays = [1, 2, 3, 4, 5];
const defaultAvailabilityStartTime = "1970-01-01T09:00:00.000Z";
const defaultAvailabilityEndTime = "1970-01-01T17:00:00.000Z";
@@ -41,14 +40,7 @@ describe("Schedules Endpoints", () => {
const moduleRef = await withAccessTokenAuth(
userEmail,
Test.createTestingModule({
imports: [
AppModule,
PrismaModule,
AvailabilitiesModule,
UsersModule,
TokensModule,
SchedulesModule,
],
imports: [AppModule, PrismaModule, UsersModule, TokensModule, SchedulesModule_2024_04_15],
})
)
.overrideGuard(PermissionsGuard)
@@ -79,7 +71,7 @@ describe("Schedules Endpoints", () => {
const scheduleTimeZone = "Europe/Rome";
const isDefault = true;
const body: CreateScheduleInput = {
const body: CreateScheduleInput_2024_04_15 = {
name: scheduleName,
timeZone: scheduleTimeZone,
isDefault,
@@ -87,10 +79,11 @@ describe("Schedules Endpoints", () => {
return request(app.getHttpServer())
.post("/api/v2/schedules")
.set(CAL_API_VERSION_HEADER, VERSION_2024_04_15)
.send(body)
.expect(201)
.then(async (response) => {
const responseData: CreateScheduleOutput = response.body;
const responseData: CreateScheduleOutput_2024_04_15 = response.body;
expect(responseData.status).toEqual(SUCCESS_STATUS);
expect(responseData.data).toBeDefined();
expect(responseData.data.isDefault).toEqual(isDefault);
@@ -117,7 +110,7 @@ describe("Schedules Endpoints", () => {
.get("/api/v2/schedules/default")
.expect(200)
.then(async (response) => {
const responseData: CreateScheduleOutput = response.body;
const responseData: CreateScheduleOutput_2024_04_15 = response.body;
expect(responseData.status).toEqual(SUCCESS_STATUS);
expect(responseData.data).toBeDefined();
expect(responseData.data.id).toEqual(createdSchedule.id);
@@ -137,7 +130,7 @@ describe("Schedules Endpoints", () => {
.get(`/api/v2/schedules`)
.expect(200)
.then((response) => {
const responseData: GetSchedulesOutput = response.body;
const responseData: GetSchedulesOutput_2024_04_15 = response.body;
expect(responseData.status).toEqual(SUCCESS_STATUS);
expect(responseData.data).toBeDefined();
expect(responseData.data?.[0].id).toEqual(createdSchedule.id);
@@ -155,16 +148,17 @@ describe("Schedules Endpoints", () => {
it("should update schedule name", async () => {
const newScheduleName = "new-schedule-name";
const body: UpdateScheduleInput = {
const body: UpdateScheduleInput_2024_04_15 = {
name: newScheduleName,
};
return request(app.getHttpServer())
.patch(`/api/v2/schedules/${createdSchedule.id}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_04_15)
.send(body)
.expect(200)
.then((response: any) => {
const responseData: UpdateScheduleOutput = response.body;
const responseData: UpdateScheduleOutput_2024_04_15 = response.body;
expect(responseData.status).toEqual(SUCCESS_STATUS);
expect(responseData.data).toBeDefined();
expect(responseData.data.schedule.name).toEqual(newScheduleName);
@@ -1,10 +1,11 @@
import { CreateScheduleOutput } from "@/ee/schedules/outputs/create-schedule.output";
import { DeleteScheduleOutput } from "@/ee/schedules/outputs/delete-schedule.output";
import { GetDefaultScheduleOutput } from "@/ee/schedules/outputs/get-default-schedule.output";
import { GetScheduleOutput } from "@/ee/schedules/outputs/get-schedule.output";
import { GetSchedulesOutput } from "@/ee/schedules/outputs/get-schedules.output";
import { UpdateScheduleOutput } from "@/ee/schedules/outputs/update-schedule.output";
import { SchedulesService } from "@/ee/schedules/services/schedules.service";
import { CreateScheduleOutput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/outputs/create-schedule.output";
import { DeleteScheduleOutput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/outputs/delete-schedule.output";
import { GetDefaultScheduleOutput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/outputs/get-default-schedule.output";
import { GetScheduleOutput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/outputs/get-schedule.output";
import { GetSchedulesOutput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/outputs/get-schedules.output";
import { UpdateScheduleOutput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/outputs/update-schedule.output";
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
import { VERSION_2024_04_15_VALUE } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
import { AccessTokenGuard } from "@/modules/auth/guards/access-token/access-token.guard";
@@ -26,25 +27,25 @@ import { ApiResponse, ApiTags as DocsTags } from "@nestjs/swagger";
import { Throttle } from "@nestjs/throttler";
import { SCHEDULE_READ, SCHEDULE_WRITE, SUCCESS_STATUS } from "@calcom/platform-constants";
import { UpdateScheduleInput } from "@calcom/platform-types";
import { UpdateScheduleInput_2024_04_15 } from "@calcom/platform-types";
import { CreateScheduleInput } from "../inputs/create-schedule.input";
import { CreateScheduleInput_2024_04_15 } from "../inputs/create-schedule.input";
@Controller({
path: "schedules",
version: "2",
path: "/v2/schedules",
version: VERSION_2024_04_15_VALUE,
})
@UseGuards(AccessTokenGuard, PermissionsGuard)
@DocsTags("Schedules")
export class SchedulesController {
constructor(private readonly schedulesService: SchedulesService) {}
export class SchedulesController_2024_04_15 {
constructor(private readonly schedulesService: SchedulesService_2024_04_15) {}
@Post("/")
@Permissions([SCHEDULE_WRITE])
async createSchedule(
@GetUser() user: UserWithProfile,
@Body() bodySchedule: CreateScheduleInput
): Promise<CreateScheduleOutput> {
@Body() bodySchedule: CreateScheduleInput_2024_04_15
): Promise<CreateScheduleOutput_2024_04_15> {
const schedule = await this.schedulesService.createUserSchedule(user.id, bodySchedule);
const scheduleFormatted = await this.schedulesService.formatScheduleForAtom(user, schedule);
@@ -56,8 +57,14 @@ export class SchedulesController {
@Get("/default")
@Permissions([SCHEDULE_READ])
@ApiResponse({ status: 200, description: "Returns the default schedule", type: GetDefaultScheduleOutput })
async getDefaultSchedule(@GetUser() user: UserWithProfile): Promise<GetDefaultScheduleOutput | null> {
@ApiResponse({
status: 200,
description: "Returns the default schedule",
type: GetDefaultScheduleOutput_2024_04_15,
})
async getDefaultSchedule(
@GetUser() user: UserWithProfile
): Promise<GetDefaultScheduleOutput_2024_04_15 | null> {
const schedule = await this.schedulesService.getUserScheduleDefault(user.id);
const scheduleFormatted = schedule
? await this.schedulesService.formatScheduleForAtom(user, schedule)
@@ -75,7 +82,7 @@ export class SchedulesController {
async getSchedule(
@GetUser() user: UserWithProfile,
@Param("scheduleId") scheduleId: number
): Promise<GetScheduleOutput> {
): Promise<GetScheduleOutput_2024_04_15> {
const schedule = await this.schedulesService.getUserSchedule(user.id, scheduleId);
const scheduleFormatted = await this.schedulesService.formatScheduleForAtom(user, schedule);
@@ -87,7 +94,7 @@ export class SchedulesController {
@Get("/")
@Permissions([SCHEDULE_READ])
async getSchedules(@GetUser() user: UserWithProfile): Promise<GetSchedulesOutput> {
async getSchedules(@GetUser() user: UserWithProfile): Promise<GetSchedulesOutput_2024_04_15> {
const schedules = await this.schedulesService.getUserSchedules(user.id);
const schedulesFormatted = await this.schedulesService.formatSchedulesForAtom(user, schedules);
@@ -102,9 +109,9 @@ export class SchedulesController {
@Permissions([SCHEDULE_WRITE])
async updateSchedule(
@GetUser() user: UserWithProfile,
@Body() bodySchedule: UpdateScheduleInput,
@Body() bodySchedule: UpdateScheduleInput_2024_04_15,
@Param("scheduleId") scheduleId: string
): Promise<UpdateScheduleOutput> {
): Promise<UpdateScheduleOutput_2024_04_15> {
const updatedSchedule = await this.schedulesService.updateUserSchedule(
user,
Number(scheduleId),
@@ -123,7 +130,7 @@ export class SchedulesController {
async deleteSchedule(
@GetUser("id") userId: number,
@Param("scheduleId") scheduleId: number
): Promise<DeleteScheduleOutput> {
): Promise<DeleteScheduleOutput_2024_04_15> {
await this.schedulesService.deleteUserSchedule(userId, scheduleId);
return {
@@ -3,7 +3,7 @@ import { ApiProperty } from "@nestjs/swagger";
import { Transform, TransformFnParams } from "class-transformer";
import { IsArray, IsDate, IsNumber } from "class-validator";
export class CreateAvailabilityInput {
export class CreateAvailabilityInput_2024_04_15 {
@IsArray()
@IsNumber({}, { each: true })
@ApiProperty({ example: [1, 2] })
@@ -1,8 +1,8 @@
import { CreateAvailabilityInput } from "@/modules/availabilities/inputs/create-availability.input";
import { CreateAvailabilityInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-availability.input";
import { Type } from "class-transformer";
import { IsArray, IsBoolean, IsTimeZone, IsOptional, IsString, ValidateNested } from "class-validator";
export class CreateScheduleInput {
export class CreateScheduleInput_2024_04_15 {
@IsString()
name!: string;
@@ -11,9 +11,9 @@ export class CreateScheduleInput {
@IsArray()
@ValidateNested({ each: true })
@Type(() => CreateAvailabilityInput)
@Type(() => CreateAvailabilityInput_2024_04_15)
@IsOptional()
availabilities?: CreateAvailabilityInput[];
availabilities?: CreateAvailabilityInput_2024_04_15[];
@IsBoolean()
isDefault!: boolean;
@@ -1,11 +1,11 @@
import { ScheduleOutput } from "@/ee/schedules/outputs/schedule.output";
import { ScheduleOutput } from "@/ee/schedules/schedules_2024_04_15/outputs/schedule.output";
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class CreateScheduleOutput {
export class CreateScheduleOutput_2024_04_15 {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@@ -3,7 +3,7 @@ import { IsEnum } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class DeleteScheduleOutput {
export class DeleteScheduleOutput_2024_04_15 {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@@ -1,11 +1,11 @@
import { ScheduleOutput } from "@/ee/schedules/outputs/schedule.output";
import { ScheduleOutput } from "@/ee/schedules/schedules_2024_04_15/outputs/schedule.output";
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class GetDefaultScheduleOutput {
export class GetDefaultScheduleOutput_2024_04_15 {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@@ -1,11 +1,11 @@
import { ScheduleOutput } from "@/ee/schedules/outputs/schedule.output";
import { ScheduleOutput } from "@/ee/schedules/schedules_2024_04_15/outputs/schedule.output";
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class GetScheduleOutput {
export class GetScheduleOutput_2024_04_15 {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@@ -1,11 +1,11 @@
import { ScheduleOutput } from "@/ee/schedules/outputs/schedule.output";
import { ScheduleOutput } from "@/ee/schedules/schedules_2024_04_15/outputs/schedule.output";
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsArray, IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class GetSchedulesOutput {
export class GetSchedulesOutput_2024_04_15 {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@@ -1,7 +1,7 @@
import { Type } from "class-transformer";
import { IsBoolean, IsInt, IsOptional, IsString, ValidateNested, IsArray } from "class-validator";
class EventTypeModel {
class EventTypeModel_2024_04_15 {
@IsInt()
id!: number;
@@ -10,7 +10,7 @@ class EventTypeModel {
eventName?: string | null;
}
class AvailabilityModel {
class AvailabilityModel_2024_04_15 {
@IsInt()
id!: number;
@@ -46,7 +46,7 @@ class AvailabilityModel {
date?: Date | null;
}
class ScheduleModel {
class ScheduleModel_2024_04_15 {
@IsInt()
id!: number;
@@ -62,21 +62,21 @@ class ScheduleModel {
@IsOptional()
@ValidateNested({ each: true })
@Type(() => EventTypeModel)
@Type(() => EventTypeModel_2024_04_15)
@IsArray()
eventType?: EventTypeModel[];
eventType?: EventTypeModel_2024_04_15[];
@IsOptional()
@ValidateNested({ each: true })
@Type(() => AvailabilityModel)
@Type(() => AvailabilityModel_2024_04_15)
@IsArray()
availability?: AvailabilityModel[];
availability?: AvailabilityModel_2024_04_15[];
}
export class UpdatedScheduleOutput {
export class UpdatedScheduleOutput_2024_04_15 {
@ValidateNested()
@Type(() => ScheduleModel)
schedule!: ScheduleModel;
@Type(() => ScheduleModel_2024_04_15)
schedule!: ScheduleModel_2024_04_15;
@IsBoolean()
isDefault!: boolean;
@@ -0,0 +1,20 @@
import { UpdatedScheduleOutput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/outputs/schedule-updated.output";
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class UpdateScheduleOutput_2024_04_15 {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({
type: UpdatedScheduleOutput_2024_04_15,
})
@IsNotEmptyObject()
@ValidateNested()
@Type(() => UpdatedScheduleOutput_2024_04_15)
data!: UpdatedScheduleOutput_2024_04_15;
}
@@ -0,0 +1,15 @@
import { SchedulesController_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/controllers/schedules.controller";
import { SchedulesRepository_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.repository";
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule, UsersModule, TokensModule],
providers: [SchedulesRepository_2024_04_15, SchedulesService_2024_04_15],
controllers: [SchedulesController_2024_04_15],
exports: [SchedulesService_2024_04_15, SchedulesRepository_2024_04_15],
})
export class SchedulesModule_2024_04_15 {}
@@ -1,18 +1,18 @@
import { CreateScheduleInput } from "@/ee/schedules/inputs/create-schedule.input";
import { CreateAvailabilityInput } from "@/modules/availabilities/inputs/create-availability.input";
import { CreateAvailabilityInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-availability.input";
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
@Injectable()
export class SchedulesRepository {
export class SchedulesRepository_2024_04_15 {
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
async createScheduleWithAvailabilities(
userId: number,
schedule: CreateScheduleInput,
availabilities: CreateAvailabilityInput[]
schedule: CreateScheduleInput_2024_04_15,
availabilities: CreateAvailabilityInput_2024_04_15[]
) {
const createScheduleData: Prisma.ScheduleCreateInput = {
user: {
@@ -1,26 +1,25 @@
import { CreateScheduleInput } from "@/ee/schedules/inputs/create-schedule.input";
import { ScheduleOutput } from "@/ee/schedules/outputs/schedule.output";
import { SchedulesRepository } from "@/ee/schedules/schedules.repository";
import { AvailabilitiesService } from "@/modules/availabilities/availabilities.service";
import { CreateAvailabilityInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-availability.input";
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
import { ScheduleOutput } from "@/ee/schedules/schedules_2024_04_15/outputs/schedule.output";
import { SchedulesRepository_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.repository";
import { UserWithProfile, UsersRepository } from "@/modules/users/users.repository";
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
import { Schedule } from "@prisma/client";
import { User } from "@prisma/client";
import type { ScheduleWithAvailabilities } from "@calcom/platform-libraries";
import { updateScheduleHandler } from "@calcom/platform-libraries";
import type { ScheduleWithAvailabilities } from "@calcom/platform-libraries-0.0.2";
import { updateScheduleHandler } from "@calcom/platform-libraries-0.0.2";
import {
transformWorkingHoursForClient,
transformAvailabilityForClient,
transformDateOverridesForClient,
} from "@calcom/platform-libraries";
import { UpdateScheduleInput } from "@calcom/platform-types";
} from "@calcom/platform-libraries-0.0.2";
import { UpdateScheduleInput_2024_04_15 } from "@calcom/platform-types";
@Injectable()
export class SchedulesService {
export class SchedulesService_2024_04_15 {
constructor(
private readonly schedulesRepository: SchedulesRepository,
private readonly availabilitiesService: AvailabilitiesService,
private readonly schedulesRepository: SchedulesRepository_2024_04_15,
private readonly usersRepository: UsersRepository
) {}
@@ -34,10 +33,10 @@ export class SchedulesService {
return this.createUserSchedule(userId, schedule);
}
async createUserSchedule(userId: number, schedule: CreateScheduleInput) {
async createUserSchedule(userId: number, schedule: CreateScheduleInput_2024_04_15) {
const availabilities = schedule.availabilities?.length
? schedule.availabilities
: [this.availabilitiesService.getDefaultAvailabilityInput()];
: [this.getDefaultAvailabilityInput()];
const createdSchedule = await this.schedulesRepository.createScheduleWithAvailabilities(
userId,
@@ -76,7 +75,11 @@ export class SchedulesService {
return this.schedulesRepository.getSchedulesByUserId(userId);
}
async updateUserSchedule(user: UserWithProfile, scheduleId: number, bodySchedule: UpdateScheduleInput) {
async updateUserSchedule(
user: UserWithProfile,
scheduleId: number,
bodySchedule: UpdateScheduleInput_2024_04_15
) {
const existingSchedule = await this.schedulesRepository.getScheduleById(scheduleId);
if (!existingSchedule) {
@@ -158,4 +161,15 @@ export class SchedulesService {
throw new ForbiddenException(`User with ID=${userId} does not own schedule with ID=${schedule.id}`);
}
}
getDefaultAvailabilityInput(): CreateAvailabilityInput_2024_04_15 {
const startTime = new Date(new Date().setUTCHours(9, 0, 0, 0));
const endTime = new Date(new Date().setUTCHours(17, 0, 0, 0));
return {
days: [1, 2, 3, 4, 5],
startTime,
endTime,
};
}
}
@@ -0,0 +1,238 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { SchedulesModule_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/schedules.module";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.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 { NestExpressApplication } from "@nestjs/platform-express";
import { Test } from "@nestjs/testing";
import { User } from "@prisma/client";
import * as request from "supertest";
import { SchedulesRepositoryFixture } from "test/fixtures/repository/schedules.repository.fixture";
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
import { withAccessTokenAuth } from "test/utils/withAccessTokenAuth";
import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_06_11 } from "@calcom/platform-constants";
import {
CreateScheduleInput_2024_06_11,
CreateScheduleOutput_2024_06_11,
GetScheduleOutput_2024_06_11,
GetSchedulesOutput_2024_06_11,
ScheduleOutput_2024_06_11,
UpdateScheduleOutput_2024_06_11,
} from "@calcom/platform-types";
import { UpdateScheduleInput_2024_06_11 } from "@calcom/platform-types";
describe("Schedules Endpoints", () => {
describe("User Authentication", () => {
let app: INestApplication;
let userRepositoryFixture: UserRepositoryFixture;
let scheduleRepositoryFixture: SchedulesRepositoryFixture;
const userEmail = "schedules-controller-e2e@api.com";
let user: User;
const createScheduleInput: CreateScheduleInput_2024_06_11 = {
name: "work",
timeZone: "Europe/Rome",
isDefault: true,
};
const defaultAvailability: CreateScheduleInput_2024_06_11["availability"] = [
{
days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
startTime: "09:00",
endTime: "17:00",
},
];
let createdSchedule: CreateScheduleOutput_2024_06_11["data"];
beforeAll(async () => {
const moduleRef = await withAccessTokenAuth(
userEmail,
Test.createTestingModule({
imports: [AppModule, PrismaModule, UsersModule, TokensModule, SchedulesModule_2024_06_11],
})
)
.overrideGuard(PermissionsGuard)
.useValue({
canActivate: () => true,
})
.compile();
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
scheduleRepositoryFixture = new SchedulesRepositoryFixture(moduleRef);
user = await userRepositoryFixture.create({
email: userEmail,
});
app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication);
await app.init();
});
it("should be defined", () => {
expect(userRepositoryFixture).toBeDefined();
expect(user).toBeDefined();
});
it("should create a default schedule", async () => {
return request(app.getHttpServer())
.post("/api/v2/schedules")
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_11)
.send(createScheduleInput)
.expect(201)
.then(async (response) => {
const responseBody: CreateScheduleOutput_2024_06_11 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
createdSchedule = response.body.data;
const expectedSchedule = {
...createScheduleInput,
availability: defaultAvailability,
overrides: [],
};
outputScheduleMatchesExpected(createdSchedule, expectedSchedule, 1);
const scheduleOwner = createdSchedule.ownerId
? await userRepositoryFixture.get(createdSchedule.ownerId)
: null;
expect(scheduleOwner?.defaultScheduleId).toEqual(createdSchedule.id);
});
});
function outputScheduleMatchesExpected(
outputSchedule: ScheduleOutput_2024_06_11 | null,
expected: CreateScheduleInput_2024_06_11 & {
availability: CreateScheduleInput_2024_06_11["availability"];
} & {
overrides: CreateScheduleInput_2024_06_11["overrides"];
},
expectedAvailabilityLength: number
) {
expect(outputSchedule).toBeTruthy();
expect(outputSchedule?.name).toEqual(expected.name);
expect(outputSchedule?.timeZone).toEqual(expected.timeZone);
expect(outputSchedule?.isDefault).toEqual(expected.isDefault);
expect(outputSchedule?.availability.length).toEqual(expectedAvailabilityLength);
const outputScheduleAvailability = outputSchedule?.availability[0];
expect(outputScheduleAvailability).toBeDefined();
expect(outputScheduleAvailability?.days).toEqual(expected.availability?.[0].days);
expect(outputScheduleAvailability?.startTime).toEqual(expected.availability?.[0].startTime);
expect(outputScheduleAvailability?.endTime).toEqual(expected.availability?.[0].endTime);
expect(JSON.stringify(outputSchedule?.overrides)).toEqual(JSON.stringify(expected.overrides));
}
it("should get default schedule", async () => {
return request(app.getHttpServer())
.get("/api/v2/schedules/default")
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_11)
.expect(200)
.then(async (response) => {
const responseBody: GetScheduleOutput_2024_06_11 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const outputSchedule = responseBody.data;
const expectedSchedule = {
...createScheduleInput,
availability: defaultAvailability,
overrides: [],
};
outputScheduleMatchesExpected(outputSchedule, expectedSchedule, 1);
});
});
it("should get schedules", async () => {
return request(app.getHttpServer())
.get(`/api/v2/schedules`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_11)
.expect(200)
.then((response) => {
const responseBody: GetSchedulesOutput_2024_06_11 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const outputSchedule = responseBody.data[0];
const expectedSchedule = {
...createScheduleInput,
availability: defaultAvailability,
overrides: [],
};
outputScheduleMatchesExpected(outputSchedule, expectedSchedule, 1);
});
});
it("should update schedule name", async () => {
const newScheduleName = "updated-schedule-name";
const body: UpdateScheduleInput_2024_06_11 = {
name: newScheduleName,
};
return request(app.getHttpServer())
.patch(`/api/v2/schedules/${createdSchedule.id}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_11)
.send(body)
.expect(200)
.then((response: any) => {
const responseData: UpdateScheduleOutput_2024_06_11 = response.body;
expect(responseData.status).toEqual(SUCCESS_STATUS);
const responseSchedule = responseData.data;
const expectedSchedule = { ...createdSchedule, name: newScheduleName };
outputScheduleMatchesExpected(responseSchedule, expectedSchedule, 1);
createdSchedule = responseSchedule;
});
});
it("should add overrides", async () => {
const overrides = [
{
date: "2026-05-05",
startTime: "10:00",
endTime: "12:00",
},
];
const body: UpdateScheduleInput_2024_06_11 = {
overrides,
};
return request(app.getHttpServer())
.patch(`/api/v2/schedules/${createdSchedule.id}`)
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_11)
.send(body)
.expect(200)
.then((response: any) => {
const responseData: UpdateScheduleOutput_2024_06_11 = response.body;
expect(responseData.status).toEqual(SUCCESS_STATUS);
const responseSchedule = responseData.data;
const expectedSchedule = { ...createdSchedule, overrides };
outputScheduleMatchesExpected(responseSchedule, expectedSchedule, 1);
createdSchedule = responseSchedule;
});
});
it("should delete schedule", async () => {
return request(app.getHttpServer()).delete(`/api/v2/schedules/${createdSchedule.id}`).expect(200);
});
afterAll(async () => {
await userRepositoryFixture.deleteByEmail(user.email);
try {
await scheduleRepositoryFixture.deleteById(createdSchedule.id);
} catch (e) {}
await app.close();
});
});
});
@@ -0,0 +1,132 @@
import { SchedulesService_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/services/schedules.service";
import { VERSION_2024_06_11_VALUE } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
import { AccessTokenGuard } from "@/modules/auth/guards/access-token/access-token.guard";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { UserWithProfile } from "@/modules/users/users.repository";
import {
Body,
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
Param,
Post,
Patch,
UseGuards,
} from "@nestjs/common";
import { ApiResponse, ApiTags as DocsTags } from "@nestjs/swagger";
import { Throttle } from "@nestjs/throttler";
import { SCHEDULE_READ, SCHEDULE_WRITE, SUCCESS_STATUS } from "@calcom/platform-constants";
import {
CreateScheduleOutput_2024_06_11,
CreateScheduleInput_2024_06_11,
UpdateScheduleInput_2024_06_11,
GetScheduleOutput_2024_06_11,
UpdateScheduleOutput_2024_06_11,
GetDefaultScheduleOutput_2024_06_11,
DeleteScheduleOutput_2024_06_11,
GetSchedulesOutput_2024_06_11,
} from "@calcom/platform-types";
@Controller({
path: "/v2/schedules",
version: VERSION_2024_06_11_VALUE,
})
@UseGuards(AccessTokenGuard, PermissionsGuard)
@DocsTags("Schedules")
export class SchedulesController_2024_06_11 {
constructor(private readonly schedulesService: SchedulesService_2024_06_11) {}
@Post("/")
@Permissions([SCHEDULE_WRITE])
async createSchedule(
@GetUser() user: UserWithProfile,
@Body() bodySchedule: CreateScheduleInput_2024_06_11
): Promise<CreateScheduleOutput_2024_06_11> {
const schedule = await this.schedulesService.createUserSchedule(user.id, bodySchedule);
return {
status: SUCCESS_STATUS,
data: schedule,
};
}
@Get("/default")
@Permissions([SCHEDULE_READ])
@ApiResponse({
status: 200,
description: "Returns the default schedule",
type: GetDefaultScheduleOutput_2024_06_11,
})
async getDefaultSchedule(@GetUser() user: UserWithProfile): Promise<GetScheduleOutput_2024_06_11> {
const schedule = await this.schedulesService.getUserScheduleDefault(user.id);
return {
status: SUCCESS_STATUS,
data: schedule,
};
}
@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
): Promise<GetScheduleOutput_2024_06_11> {
const schedule = await this.schedulesService.getUserSchedule(user.id, scheduleId);
return {
status: SUCCESS_STATUS,
data: schedule,
};
}
@Get("/")
@Permissions([SCHEDULE_READ])
async getSchedules(@GetUser() user: UserWithProfile): Promise<GetSchedulesOutput_2024_06_11> {
const schedules = await this.schedulesService.getUserSchedules(user.id);
return {
status: SUCCESS_STATUS,
data: schedules,
};
}
@Patch("/:scheduleId")
@Permissions([SCHEDULE_WRITE])
async updateSchedule(
@GetUser() user: UserWithProfile,
@Body() bodySchedule: UpdateScheduleInput_2024_06_11,
@Param("scheduleId") scheduleId: string
): Promise<UpdateScheduleOutput_2024_06_11> {
const updatedSchedule = await this.schedulesService.updateUserSchedule(
user.id,
Number(scheduleId),
bodySchedule
);
return {
status: SUCCESS_STATUS,
data: updatedSchedule,
};
}
@Delete("/:scheduleId")
@HttpCode(HttpStatus.OK)
@Permissions([SCHEDULE_WRITE])
async deleteSchedule(
@GetUser("id") userId: number,
@Param("scheduleId") scheduleId: number
): Promise<DeleteScheduleOutput_2024_06_11> {
await this.schedulesService.deleteUserSchedule(userId, scheduleId);
return {
status: SUCCESS_STATUS,
};
}
}
@@ -0,0 +1,22 @@
import { SchedulesController_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/controllers/schedules.controller";
import { SchedulesRepository_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/schedules.repository";
import { InputSchedulesService_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/services/input-schedules.service";
import { OutputSchedulesService_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/services/output-schedules.service";
import { SchedulesService_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/services/schedules.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule, UsersModule, TokensModule],
providers: [
SchedulesRepository_2024_06_11,
SchedulesService_2024_06_11,
InputSchedulesService_2024_06_11,
OutputSchedulesService_2024_06_11,
],
controllers: [SchedulesController_2024_06_11],
exports: [SchedulesService_2024_06_11, SchedulesRepository_2024_06_11],
})
export class SchedulesModule_2024_06_11 {}
@@ -0,0 +1,208 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import type { CreateScheduleInput_2024_06_11 } from "@calcom/platform-types";
type InputScheduleAvailabilityTransformed = {
days: number[];
startTime: Date;
endTime: Date;
};
type InputScheduleOverrideTransformed = {
date: Date;
startTime: Date;
endTime: Date;
};
type InputScheduleTransformed = Omit<CreateScheduleInput_2024_06_11, "availability" | "overrides"> & {
availability: InputScheduleAvailabilityTransformed[];
overrides: InputScheduleOverrideTransformed[];
};
@Injectable()
export class SchedulesRepository_2024_06_11 {
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
async createSchedule(userId: number, schedule: Omit<InputScheduleTransformed, "isDefault">) {
const { availability, overrides } = schedule;
const createScheduleData: Prisma.ScheduleCreateInput = {
user: {
connect: {
id: userId,
},
},
name: schedule.name,
timeZone: schedule.timeZone,
};
const availabilitiesAndOverrides: Prisma.AvailabilityCreateManyInput[] = [];
if (availability && availability.length > 0) {
availability.forEach((availability) => {
availabilitiesAndOverrides.push({
days: availability.days,
startTime: availability.startTime,
endTime: availability.endTime,
userId,
});
});
}
if (overrides && overrides.length > 0) {
overrides.forEach((override) => {
availabilitiesAndOverrides.push({
date: override.date,
startTime: override.startTime,
endTime: override.endTime,
userId,
});
});
}
if (availabilitiesAndOverrides.length > 0) {
createScheduleData.availability = {
createMany: {
data: availabilitiesAndOverrides,
},
};
}
const createdSchedule = await this.dbWrite.prisma.schedule.create({
data: {
...createScheduleData,
},
include: {
availability: true,
},
});
return createdSchedule;
}
async getScheduleById(scheduleId: number) {
const schedule = await this.dbRead.prisma.schedule.findUnique({
where: {
id: scheduleId,
},
include: {
availability: true,
},
});
return schedule;
}
async updateSchedule(
userId: number,
scheduleId: number,
schedule: Partial<Omit<InputScheduleTransformed, "isDefault">>
) {
const { availability, overrides } = schedule;
const updateScheduleData: Prisma.ScheduleUpdateInput = {
name: schedule.name,
timeZone: schedule.timeZone,
};
const availabilitiesAndOverrides: Prisma.AvailabilityCreateManyInput[] = [];
const deleteConditions = [];
if (availability) {
// note(Lauris): availabilities and overrides are stored in the same "Availability" table,
// but availabilities have "date" field as null, while overrides have it as not null, so delete
// condition below results in deleting only rows from Availability table that are availabilities.
deleteConditions.push({
scheduleId: { equals: scheduleId },
date: null,
});
}
if (overrides) {
// note(Lauris): availabilities and overrides are stored in the same "Availability" table,
// but overrides have "date" field as not-null, while availabilities have it as null, so delete
// condition below results in deleting only rows from Availability table that are overrides.
deleteConditions.push({
scheduleId: { equals: scheduleId },
NOT: { date: null },
});
}
if (availability && availability.length > 0) {
availability.forEach((availability) => {
availabilitiesAndOverrides.push({
days: availability.days,
startTime: availability.startTime,
endTime: availability.endTime,
userId,
});
});
}
if (overrides && overrides.length > 0) {
overrides.forEach((override) => {
availabilitiesAndOverrides.push({
date: override.date,
startTime: override.startTime,
endTime: override.endTime,
userId,
});
});
}
if (availabilitiesAndOverrides.length > 0) {
updateScheduleData.availability = {
deleteMany: deleteConditions,
createMany: {
data: availabilitiesAndOverrides,
},
};
}
const updatedSchedule = await this.dbWrite.prisma.schedule.update({
where: {
id: scheduleId,
},
data: {
...updateScheduleData,
},
include: {
availability: true,
},
});
return updatedSchedule;
}
async getSchedulesByUserId(userId: number) {
const schedules = await this.dbRead.prisma.schedule.findMany({
where: {
userId,
},
include: {
availability: true,
},
});
return schedules;
}
async deleteScheduleById(scheduleId: number) {
return this.dbWrite.prisma.schedule.delete({
where: {
id: scheduleId,
},
});
}
async getUserSchedulesCount(userId: number) {
return this.dbRead.prisma.schedule.count({
where: {
userId,
},
});
}
}
@@ -0,0 +1,43 @@
import { Injectable } from "@nestjs/common";
import {
transformApiScheduleOverrides,
transformApiScheduleAvailability,
} from "@calcom/platform-libraries-0.0.4";
import { CreateScheduleInput_2024_06_11, ScheduleAvailabilityInput_2024_06_11 } from "@calcom/platform-types";
import { ScheduleOverrideInput_2024_06_11 } from "@calcom/platform-types";
@Injectable()
export class InputSchedulesService_2024_06_11 {
transformInputCreateSchedule(inputSchedule: CreateScheduleInput_2024_06_11) {
const defaultAvailability: ScheduleAvailabilityInput_2024_06_11[] = [
{
days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
startTime: "09:00",
endTime: "17:00",
},
];
const defaultOverrides: ScheduleOverrideInput_2024_06_11[] = [];
const availability = this.transformInputScheduleAvailability(
inputSchedule.availability || defaultAvailability
);
const overrides = this.transformInputOverrides(inputSchedule.overrides || defaultOverrides);
const internalCreateSchedule = {
...inputSchedule,
availability,
overrides,
};
return internalCreateSchedule;
}
transformInputScheduleAvailability(inputAvailability: ScheduleAvailabilityInput_2024_06_11[]) {
return transformApiScheduleAvailability(inputAvailability);
}
transformInputOverrides(inputOverrides: ScheduleOverrideInput_2024_06_11[]) {
return transformApiScheduleOverrides(inputOverrides);
}
}
@@ -0,0 +1,78 @@
import { UsersRepository } from "@/modules/users/users.repository";
import { Injectable } from "@nestjs/common";
import type { Availability, Schedule } from "@prisma/client";
import { WeekDay } from "@calcom/platform-types";
@Injectable()
export class OutputSchedulesService_2024_06_11 {
constructor(private readonly usersRepository: UsersRepository) {}
async getResponseSchedule(databaseSchedule: Schedule & { availability: Availability[] }) {
if (!databaseSchedule.timeZone) {
throw new Error("Failed to create schedule because its timezone is not set.");
}
const ownerDefaultScheduleId = await this.usersRepository.getUserScheduleDefaultId(
databaseSchedule.userId
);
const createdScheduleAvailabilities = databaseSchedule.availability.filter(
(availability) => !!availability.days.length
);
const createdScheduleOverrides = databaseSchedule.availability.filter((override) => !!override.date);
return {
id: databaseSchedule.id,
ownerId: databaseSchedule.userId,
name: databaseSchedule.name,
timeZone: databaseSchedule.timeZone,
availability: createdScheduleAvailabilities.map((availability) => ({
days: availability.days.map(transformNumberToDay),
startTime: this.padHoursMinutesWithZeros(
availability.startTime.getUTCHours() + ":" + availability.startTime.getUTCMinutes()
),
endTime: this.padHoursMinutesWithZeros(
availability.endTime.getUTCHours() + ":" + availability.endTime.getUTCMinutes()
),
})),
isDefault: databaseSchedule.id === ownerDefaultScheduleId,
overrides: createdScheduleOverrides.map((override) => ({
date:
override.date?.getUTCFullYear() +
"-" +
(override.date ? override.date.getUTCMonth() + 1 : "").toString().padStart(2, "0") +
"-" +
override.date?.getUTCDate().toString().padStart(2, "0"),
startTime: this.padHoursMinutesWithZeros(
override.startTime.getUTCHours() + ":" + override.startTime.getUTCMinutes()
),
endTime: this.padHoursMinutesWithZeros(
override.endTime.getUTCHours() + ":" + override.endTime.getUTCMinutes()
),
})),
};
}
padHoursMinutesWithZeros(hhMM: string) {
const [hours, minutes] = hhMM.split(":");
const formattedHours = hours.padStart(2, "0");
const formattedMinutes = minutes.padStart(2, "0");
return `${formattedHours}:${formattedMinutes}`;
}
}
function transformNumberToDay(day: number): WeekDay {
const weekMap: { [key: number]: WeekDay } = {
0: "Sunday",
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
};
return weekMap[day];
}
@@ -0,0 +1,123 @@
import { SchedulesRepository_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/schedules.repository";
import { InputSchedulesService_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/services/input-schedules.service";
import { OutputSchedulesService_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/services/output-schedules.service";
import { UsersRepository } from "@/modules/users/users.repository";
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
import { Schedule } from "@prisma/client";
import { CreateScheduleInput_2024_06_11, ScheduleOutput_2024_06_11 } from "@calcom/platform-types";
import { UpdateScheduleInput_2024_06_11 } from "@calcom/platform-types";
@Injectable()
export class SchedulesService_2024_06_11 {
constructor(
private readonly schedulesRepository: SchedulesRepository_2024_06_11,
private readonly inputSchedulesService: InputSchedulesService_2024_06_11,
private readonly outputSchedulesService: OutputSchedulesService_2024_06_11,
private readonly usersRepository: UsersRepository
) {}
async createUserDefaultSchedule(userId: number, timeZone: string) {
const defaultSchedule = {
isDefault: true,
name: "Default schedule",
timeZone,
};
return this.createUserSchedule(userId, defaultSchedule);
}
async createUserSchedule(
userId: number,
scheduleInput: CreateScheduleInput_2024_06_11
): Promise<ScheduleOutput_2024_06_11> {
const schedule = this.inputSchedulesService.transformInputCreateSchedule(scheduleInput);
const createdSchedule = await this.schedulesRepository.createSchedule(userId, schedule);
if (schedule.isDefault) {
await this.usersRepository.setDefaultSchedule(userId, createdSchedule.id);
}
return this.outputSchedulesService.getResponseSchedule(createdSchedule);
}
async getUserScheduleDefault(userId: number) {
const user = await this.usersRepository.findById(userId);
if (!user?.defaultScheduleId) return null;
const defaultSchedule = await this.schedulesRepository.getScheduleById(user.defaultScheduleId);
if (!defaultSchedule) return null;
return this.outputSchedulesService.getResponseSchedule(defaultSchedule);
}
async getUserSchedule(userId: number, scheduleId: number) {
const existingSchedule = await this.schedulesRepository.getScheduleById(scheduleId);
if (!existingSchedule) {
throw new NotFoundException(`Schedule with ID=${scheduleId} does not exist.`);
}
this.checkUserOwnsSchedule(userId, existingSchedule);
return this.outputSchedulesService.getResponseSchedule(existingSchedule);
}
async getUserSchedules(userId: number) {
const schedules = await this.schedulesRepository.getSchedulesByUserId(userId);
return Promise.all(
schedules.map(async (schedule) => {
return this.outputSchedulesService.getResponseSchedule(schedule);
})
);
}
async updateUserSchedule(userId: number, scheduleId: number, bodySchedule: UpdateScheduleInput_2024_06_11) {
const existingSchedule = await this.schedulesRepository.getScheduleById(scheduleId);
if (!existingSchedule) {
throw new NotFoundException(`Schedule with ID=${scheduleId} does not exist.`);
}
this.checkUserOwnsSchedule(userId, existingSchedule);
const availability = bodySchedule.availability
? this.inputSchedulesService.transformInputScheduleAvailability(bodySchedule.availability)
: undefined;
const overrides = bodySchedule.overrides
? this.inputSchedulesService.transformInputOverrides(bodySchedule.overrides)
: undefined;
if (bodySchedule.isDefault) {
await this.usersRepository.setDefaultSchedule(userId, scheduleId);
}
const updatedSchedule = await this.schedulesRepository.updateSchedule(userId, scheduleId, {
...bodySchedule,
availability,
overrides,
});
return this.outputSchedulesService.getResponseSchedule(updatedSchedule);
}
async deleteUserSchedule(userId: number, scheduleId: number) {
const existingSchedule = await this.schedulesRepository.getScheduleById(scheduleId);
if (!existingSchedule) {
throw new BadRequestException(`Schedule with ID=${scheduleId} does not exist.`);
}
this.checkUserOwnsSchedule(userId, existingSchedule);
return this.schedulesRepository.deleteScheduleById(scheduleId);
}
checkUserOwnsSchedule(userId: number, schedule: Pick<Schedule, "id" | "userId">) {
if (userId !== schedule.userId) {
throw new ForbiddenException(`User with ID=${userId} does not own schedule with ID=${schedule.id}`);
}
}
}
@@ -1,39 +0,0 @@
import { ArgumentsHost, Catch, Logger, HttpStatus } from "@nestjs/common";
import { BaseExceptionFilter } from "@nestjs/core";
import * as Sentry from "@sentry/node";
import { Request } from "express";
import { ERROR_STATUS, INTERNAL_SERVER_ERROR } from "@calcom/platform-constants";
import { Response } from "@calcom/platform-types";
@Catch()
export class SentryFilter extends BaseExceptionFilter {
private readonly logger = new Logger("SentryExceptionFilter");
handleUnknownError(exception: any, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const requestId = request.headers["X-Request-Id"];
this.logger.error(`Sentry Exception Filter: ${exception?.message}`, {
exception,
body: request.body,
headers: request.headers,
url: request.url,
method: request.method,
requestId,
});
// capture if client has been init
if (Boolean(Sentry.getCurrentHub().getClient())) {
Sentry.captureException(exception);
}
response.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
status: ERROR_STATUS,
timestamp: new Date().toISOString(),
path: request.url,
error: { code: INTERNAL_SERVER_ERROR, message: "Internal server error." },
});
}
}
@@ -2,7 +2,7 @@ import { ArgumentsHost, Catch, ExceptionFilter, Logger } from "@nestjs/common";
import { Request } from "express";
import { ERROR_STATUS } from "@calcom/platform-constants";
import { TRPCError } from "@calcom/platform-libraries";
import { TRPCError } from "@calcom/platform-libraries-0.0.2";
import { Response } from "@calcom/platform-types";
@Catch(TRPCError)
+12
View File
@@ -0,0 +1,12 @@
import { getEnv } from "@/env";
import * as Sentry from "@sentry/node";
if (process.env.SENTRY_DSN) {
// Ensure to call this before requiring any other modules!
Sentry.init({
dsn: getEnv("SENTRY_DSN"),
// Add Performance Monitoring by setting tracesSampleRate
// We recommend adjusting this value in production
// todo: Evaluate? tracesSampleRate: 1.0
});
}
+13
View File
@@ -0,0 +1,13 @@
import { VersionValue } from "@nestjs/common/interfaces";
import {
API_VERSIONS,
VERSION_2024_04_15,
VERSION_2024_05_21,
VERSION_2024_06_11,
} from "@calcom/platform-constants";
export const API_VERSIONS_VALUES: VersionValue = API_VERSIONS as unknown as VersionValue;
export const VERSION_2024_06_11_VALUE: VersionValue = VERSION_2024_06_11 as unknown as VersionValue;
export const VERSION_2024_05_21_VALUE: VersionValue = VERSION_2024_05_21 as unknown as VersionValue;
export const VERSION_2024_04_15_VALUE: VersionValue = VERSION_2024_04_15 as unknown as VersionValue;
@@ -0,0 +1,61 @@
import { plainToClass } from "class-transformer";
import { IsOptional, IsString } from "class-validator";
import { CapitalizeTimeZone } from "./capitalize-timezone";
class TestDto {
@IsOptional()
@IsString()
@CapitalizeTimeZone()
timeZone?: string;
}
describe("CapitalizeTimeZone", () => {
it("should capitalize single part time zone correctly", () => {
const input = { timeZone: "egypt" };
const output = plainToClass(TestDto, input);
expect(output.timeZone).toBe("Egypt");
});
it("should capitalize one-part time zone correctly", () => {
const input = { timeZone: "europe/rome" };
const output = plainToClass(TestDto, input);
expect(output.timeZone).toBe("Europe/Rome");
});
it("should capitalize multi-part time zone correctly", () => {
const input = { timeZone: "america/new_york" };
const output = plainToClass(TestDto, input);
expect(output.timeZone).toBe("America/New_York");
});
it("should capitalize complex time zone correctly", () => {
const input = { timeZone: "europe/isle_of_man" };
const output = plainToClass(TestDto, input);
expect(output.timeZone).toBe("Europe/Isle_Of_Man");
});
it("should handle already capitalized time zones correctly", () => {
const input = { timeZone: "Asia/Tokyo" };
const output = plainToClass(TestDto, input);
expect(output.timeZone).toBe("Asia/Tokyo");
});
it("should handle missing time zone correctly", () => {
const input = {};
const output = plainToClass(TestDto, input);
expect(output.timeZone).toBeUndefined();
});
it("should capitalize EST at the end of the string", () => {
const input = { email: "test@example.com", timeZone: "utc/est" };
const output = plainToClass(TestDto, input);
expect(output.timeZone).toBe("UTC/EST");
});
it("should capitalize UTC when surrounded by non-alphabetical characters", () => {
const input = { email: "test@example.com", timeZone: "utc/gmt+3_est" };
const output = plainToClass(TestDto, input);
expect(output.timeZone).toBe("UTC/GMT+3_EST");
});
});
@@ -0,0 +1,28 @@
import { Transform } from "class-transformer";
export function CapitalizeTimeZone(): PropertyDecorator {
return Transform(({ value }) => {
if (typeof value === "string") {
const parts = value.split("/");
const normalizedParts = parts.map((part) =>
part
.split("_")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join("_")
);
let normalizedTimeZone = normalizedParts.join("/");
// note(Lauris): regex matching GMT, EST, UTC at the start, end, or surrounded by non-letters and capitalizing them
const specialCases = ["GMT", "EST", "UTC"];
specialCases.forEach((specialCase) => {
const regex = new RegExp(`(^|[^a-zA-Z])(${specialCase})([^a-zA-Z]|$)`, "gi");
normalizedTimeZone = normalizedTimeZone.replace(regex, (match, p1, p2, p3) => {
return `${p1}${specialCase}${p3}`;
});
});
return normalizedTimeZone;
}
return value;
});
}
@@ -1,10 +0,0 @@
import { AvailabilitiesService } from "@/modules/availabilities/availabilities.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule],
providers: [AvailabilitiesService],
exports: [AvailabilitiesService],
})
export class AvailabilitiesModule {}
@@ -1,16 +0,0 @@
import { CreateAvailabilityInput } from "@/modules/availabilities/inputs/create-availability.input";
import { Injectable } from "@nestjs/common";
@Injectable()
export class AvailabilitiesService {
getDefaultAvailabilityInput(): CreateAvailabilityInput {
const startTime = new Date(new Date().setUTCHours(9, 0, 0, 0));
const endTime = new Date(new Date().setUTCHours(17, 0, 0, 0));
return {
days: [1, 2, 3, 4, 5],
startTime,
endTime,
};
}
}
@@ -1,4 +1,5 @@
import { AppConfig } from "@/config/type";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { Roles } from "@/modules/auth/decorators/roles/roles.decorator";
import { NextAuthGuard } from "@/modules/auth/guards/next-auth/next-auth.guard";
import { OrganizationRolesGuard } from "@/modules/auth/guards/organization-roles/organization-roles.guard";
@@ -29,8 +30,8 @@ import { Stripe } from "stripe";
import { ApiResponse } from "@calcom/platform-types";
@Controller({
path: "/billing",
version: "2",
path: "/v2/billing",
version: API_VERSIONS_VALUES,
})
@ApiExcludeController(true)
export class BillingController {
@@ -122,7 +123,7 @@ export class BillingController {
await this.billingService.setSubscriptionForTeam(
teamId,
subscription,
PlatformPlan[plan as keyof typeof PlatformPlan]
PlatformPlan[plan.toUpperCase() as keyof typeof PlatformPlan]
);
return {
@@ -11,7 +11,7 @@ export class BillingConfigService {
const planKeys = Object.keys(PlatformPlan).filter((key) => isNaN(Number(key)));
for (const key of planKeys) {
this.config.set(
PlatformPlan[key as keyof typeof PlatformPlan],
PlatformPlan[key.toUpperCase() as keyof typeof PlatformPlan],
process.env[`STRIPE_PRICE_ID_${key}`] ?? ""
);
}
@@ -1,3 +1,4 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { CreateManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/create-managed-user.output";
import { GetManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/get-managed-user.output";
import { GetManagedUsersOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/get-managed-users.output";
@@ -21,7 +22,6 @@ import {
HttpStatus,
Param,
Patch,
BadRequestException,
Delete,
Query,
NotFoundException,
@@ -33,8 +33,8 @@ import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { Pagination } from "@calcom/platform-types";
@Controller({
path: "oauth-clients/:clientId/users",
version: "2",
path: "/v2/oauth-clients/:clientId/users",
version: API_VERSIONS_VALUES,
})
@UseGuards(OAuthClientCredentialsGuard)
@DocsTags("Managed users")
@@ -91,6 +91,7 @@ export class OAuthClientUsersController {
data: {
user: this.getResponseUser(user),
accessToken: tokens.accessToken,
accessTokenExpiresAt: tokens.accessTokenExpiresAt.valueOf(),
refreshToken: tokens.refreshToken,
},
};
@@ -155,7 +156,7 @@ export class OAuthClientUsersController {
const { id } = await this.validateManagedUserOwnership(oAuthClientId, userId);
const { accessToken, refreshToken } = await this.tokensRepository.createOAuthTokens(
const { accessToken, refreshToken, accessTokenExpiresAt } = await this.tokensRepository.createOAuthTokens(
oAuthClientId,
id,
true
@@ -166,6 +167,7 @@ export class OAuthClientUsersController {
data: {
accessToken,
refreshToken,
accessTokenExpiresAt: accessTokenExpiresAt.valueOf(),
},
};
}
@@ -1,7 +1,7 @@
import { ManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/managed-user.output";
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsEnum, IsString, ValidateNested } from "class-validator";
import { IsEnum, IsNumber, IsString, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
@@ -18,6 +18,9 @@ class CreateManagedUserData {
@IsString()
refreshToken!: string;
@IsNumber()
accessTokenExpiresAt!: number;
}
export class CreateManagedUserOutput {
@@ -1,4 +1,5 @@
import { getEnv } from "@/env";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Roles } from "@/modules/auth/decorators/roles/roles.decorator";
import { NextAuthGuard } from "@/modules/auth/guards/next-auth/next-auth.guard";
@@ -46,8 +47,8 @@ const AUTH_DOCUMENTATION = `⚠️ First, this endpoint requires \`Cookie: next-
Second, make sure that the logged in user has organizationId set to pass the OrganizationRolesGuard guard.`;
@Controller({
path: "oauth-clients",
version: "2",
path: "/v2/oauth-clients",
version: API_VERSIONS_VALUES,
})
@UseGuards(NextAuthGuard, OrganizationRolesGuard)
@DocsExcludeController(getEnv("NODE_ENV") === "production")
@@ -1,4 +1,5 @@
import { getEnv } from "@/env";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { NextAuthGuard } from "@/modules/auth/guards/next-auth/next-auth.guard";
import { KeysResponseDto } from "@/modules/oauth-clients/controllers/oauth-flow/responses/KeysResponse.dto";
@@ -33,8 +34,8 @@ import { Response as ExpressResponse } from "express";
import { SUCCESS_STATUS, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
@Controller({
path: "oauth/:clientId",
version: "2",
path: "/v2/oauth/:clientId",
version: API_VERSIONS_VALUES,
})
@DocsExcludeController(getEnv("NODE_ENV") === "production")
@DocsTags("OAuth - development only")
@@ -117,16 +118,18 @@ export class OAuthFlowController {
throw new BadRequestException("Missing 'Bearer' Authorization header.");
}
const { accessToken, refreshToken } = await this.oAuthFlowService.exchangeAuthorizationToken(
authorizeEndpointCode,
clientId,
body.clientSecret
);
const { accessToken, refreshToken, accessTokenExpiresAt } =
await this.oAuthFlowService.exchangeAuthorizationToken(
authorizeEndpointCode,
clientId,
body.clientSecret
);
return {
status: SUCCESS_STATUS,
data: {
accessToken,
accessTokenExpiresAt: accessTokenExpiresAt.valueOf(),
refreshToken,
},
};
@@ -140,7 +143,7 @@ export class OAuthFlowController {
@Headers(X_CAL_SECRET_KEY) secretKey: string,
@Body() body: RefreshTokenInput
): Promise<KeysResponseDto> {
const { accessToken, refreshToken } = await this.oAuthFlowService.refreshToken(
const { accessToken, refreshToken, accessTokenExpiresAt } = await this.oAuthFlowService.refreshToken(
clientId,
secretKey,
body.refreshToken
@@ -150,6 +153,7 @@ export class OAuthFlowController {
status: SUCCESS_STATUS,
data: {
accessToken: accessToken,
accessTokenExpiresAt: accessTokenExpiresAt.valueOf(),
refreshToken: refreshToken,
},
};
@@ -1,6 +1,6 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { ValidateNested, IsEnum, IsString, IsNotEmptyObject } from "class-validator";
import { ValidateNested, IsEnum, IsString, IsNotEmptyObject, IsNumber } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
@@ -16,6 +16,9 @@ class KeysDto {
})
@IsString()
refreshToken!: string;
@IsNumber()
accessTokenExpiresAt!: number;
}
export class KeysResponseDto {
@@ -1,5 +1,5 @@
import { EventTypesModule } from "@/ee/event-types/event-types.module";
import { SchedulesModule } from "@/ee/schedules/schedules.module";
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
import { AuthModule } from "@/modules/auth/auth.module";
import { BillingModule } from "@/modules/billing/billing.module";
import { MembershipsModule } from "@/modules/memberships/memberships.module";
@@ -32,7 +32,7 @@ import { Global, Module } from "@nestjs/common";
OrganizationsModule,
StripeModule,
BillingModule,
SchedulesModule,
SchedulesModule_2024_04_15,
],
providers: [
OAuthClientRepository,
@@ -1,5 +1,5 @@
import { EventTypesService } from "@/ee/event-types/services/event-types.service";
import { SchedulesService } from "@/ee/schedules/services/schedules.service";
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { CreateManagedUserInput } from "@/modules/users/inputs/create-managed-user.input";
import { UpdateManagedUserInput } from "@/modules/users/inputs/update-managed-user.input";
@@ -7,7 +7,7 @@ import { UsersRepository } from "@/modules/users/users.repository";
import { BadRequestException, Injectable } from "@nestjs/common";
import { User } from "@prisma/client";
import { createNewUsersConnectToOrgIfExists, slugify } from "@calcom/platform-libraries";
import { createNewUsersConnectToOrgIfExists, slugify } from "@calcom/platform-libraries-0.0.2";
@Injectable()
export class OAuthClientUsersService {
@@ -15,7 +15,7 @@ export class OAuthClientUsersService {
private readonly userRepository: UsersRepository,
private readonly tokensRepository: TokensRepository,
private readonly eventTypesService: EventTypesService,
private readonly schedulesService: SchedulesService
private readonly schedulesService: SchedulesService_2024_04_15
) {}
async createOauthClientUser(
@@ -62,7 +62,7 @@ export class OAuthClientUsersService {
await this.userRepository.update(user.id, { name: body.name ?? user.username ?? undefined });
}
const { accessToken, refreshToken } = await this.tokensRepository.createOAuthTokens(
const { accessToken, refreshToken, accessTokenExpiresAt } = await this.tokensRepository.createOAuthTokens(
oAuthClientId,
user.id
);
@@ -78,6 +78,7 @@ export class OAuthClientUsersService {
user,
tokens: {
accessToken,
accessTokenExpiresAt,
refreshToken,
},
};
@@ -103,7 +103,7 @@ export class OAuthFlowService {
tokenId: string,
clientId: string,
clientSecret: string
): Promise<{ accessToken: string; refreshToken: string }> {
): Promise<{ accessToken: string; refreshToken: string; accessTokenExpiresAt: Date }> {
const oauthClient = await this.oAuthClientRepository.getOAuthClientWithAuthTokens(
tokenId,
clientId,
@@ -120,7 +120,7 @@ export class OAuthFlowService {
throw new BadRequestException("Invalid Authorization Token.");
}
const { accessToken, refreshToken } = await this.tokensRepository.createOAuthTokens(
const { accessToken, refreshToken, accessTokenExpiresAt } = await this.tokensRepository.createOAuthTokens(
clientId,
authorizationToken.owner.id
);
@@ -129,6 +129,7 @@ export class OAuthFlowService {
return {
accessToken,
accessTokenExpiresAt,
refreshToken,
};
}
@@ -158,6 +159,7 @@ export class OAuthFlowService {
return {
accessToken: accessToken.secret,
accessTokenExpiresAt: accessToken.expiresAt,
refreshToken: refreshToken.secret,
};
}
@@ -1,3 +1,4 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { AccessTokenGuard } from "@/modules/auth/guards/access-token/access-token.guard";
import { SlotsService } from "@/modules/slots/services/slots.service";
import { Query, Body, Controller, Get, Delete, Post, Req, Res, UseGuards } from "@nestjs/common";
@@ -5,14 +6,14 @@ import { ApiTags as DocsTags } from "@nestjs/swagger";
import { Response as ExpressResponse, Request as ExpressRequest } from "express";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { getAvailableSlots } from "@calcom/platform-libraries";
import type { AvailableSlotsType } from "@calcom/platform-libraries";
import { getAvailableSlots } from "@calcom/platform-libraries-0.0.2";
import type { AvailableSlotsType } from "@calcom/platform-libraries-0.0.2";
import { RemoveSelectedSlotInput, ReserveSlotInput } from "@calcom/platform-types";
import { ApiResponse, GetAvailableSlotsInput } from "@calcom/platform-types";
@Controller({
path: "slots",
version: "2",
path: "/v2/slots",
version: API_VERSIONS_VALUES,
})
@DocsTags("Slots")
export class SlotsController {
@@ -3,7 +3,7 @@ import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { DateTime } from "luxon";
import { MINUTES_TO_BOOK } from "@calcom/platform-libraries";
import { MINUTES_TO_BOOK } from "@calcom/platform-libraries-0.0.2";
import { ReserveSlotInput } from "@calcom/platform-types";
@Injectable()
@@ -1,14 +1,15 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { TimezonesService } from "@/modules/timezones/services/timezones.service";
import { Controller, Get } from "@nestjs/common";
import { ApiTags as DocsTags } from "@nestjs/swagger";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import type { CityTimezones } from "@calcom/platform-libraries";
import type { CityTimezones } from "@calcom/platform-libraries-0.0.2";
import { ApiResponse } from "@calcom/platform-types";
@Controller({
path: "timezones",
version: "2",
path: "/v2/timezones",
version: API_VERSIONS_VALUES,
})
@DocsTags("Timezones")
export class TimezonesController {
@@ -1,8 +1,8 @@
import { RedisService } from "@/modules/redis/redis.service";
import { Injectable } from "@nestjs/common";
import { cityTimezonesHandler } from "@calcom/platform-libraries";
import type { CityTimezones } from "@calcom/platform-libraries";
import { cityTimezonesHandler } from "@calcom/platform-libraries-0.0.2";
import type { CityTimezones } from "@calcom/platform-libraries-0.0.2";
@Injectable()
export class TimezonesService {
@@ -89,6 +89,7 @@ export class TokensRepository {
return {
accessToken: accessToken.secret,
accessTokenExpiresAt: accessToken.expiresAt,
refreshToken: refreshToken.secret,
};
}
@@ -1,3 +1,4 @@
import { CapitalizeTimeZone } from "@/lib/inputs/capitalize-timezone";
import { ApiProperty } from "@nestjs/swagger";
import { IsOptional, IsTimeZone, IsString } from "class-validator";
@@ -26,6 +27,7 @@ export class CreateManagedUserInput {
@IsTimeZone()
@IsOptional()
@CapitalizeTimeZone()
@ApiProperty({ example: "America/New_York" })
timeZone?: string;
}
@@ -173,6 +173,14 @@ export class UsersRepository {
},
});
}
async getUserScheduleDefaultId(userId: number) {
const user = await this.findById(userId);
if (!user?.defaultScheduleId) return null;
return user?.defaultScheduleId;
}
}
function capitalizeTimezone(timezone: string) {

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