Compare commits

...
226 Commits
Author SHA1 Message Date
Alex van Andel 8d04a23bce chore: release v6.0.3
Post release / release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
2025-12-20 01:00:01 +00:00
dd8477c0bf fix(typo): correct spelling of organization in error message (#26035)
Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
Co-authored-by: Dhairyashil Shinde <93669429+dhairyashiil@users.noreply.github.com>
2025-12-20 00:16:18 +00:00
BetoandDhairyashil aebfd4919b feat(companion): Update availability screen to use liquid glass (#26041)
* Use previous header for android

* use activity instead of ternary statements

* update layout to use header buttons in availability screen

* fix styles and add context menu

* add set as default action

---------

Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>
2025-12-19 19:05:26 +00:00
Dhairyashil Shinde 69a857ad98 feat(companion): Multi-browser extension support (Chrome, Firefox, Safari, Edge, Brave) and fix text node errors (#26063)
* feat(companion): add multi-browser OAuth support for extension

- Add browser-specific OAuth client ID and redirect URI configuration
- Support Chrome, Firefox, Safari, Edge, and Brave browsers
- Add build scripts for each browser target (ext:build-{browser})
- Fix Brave Shields compatibility for production builds
- Add EXTENSION_SETUP.md documentation

BREAKING CHANGE: None - backward compatible with existing Chrome config

* fix(companion): replace && conditional rendering with ternary operators

Replace all `{condition && (<Component />)}` patterns with explicit
`{condition ? (<Component />) : null}` syntax across the companion app.

This fixes "Unexpected text node: . A text node cannot be a child of
a <View>" errors that occur with react-native-css-interop when using
&& conditional rendering in React Native web builds.

Files updated:
- app/event-type-detail.tsx (16)
- app/booking-detail.tsx (10)
- app/(tabs)/bookings.tsx (8)
- app/(tabs)/availability.tsx (6)
- app/availability-detail.tsx (5)
- app/(tabs)/(event-types)/index.tsx (4)
- components/event-type-detail/tabs/LimitsTab.tsx (9)
- components/event-type-detail/tabs/BasicsTab.tsx (3)
- components/event-type-detail/tabs/AdvancedTab.tsx (3)
- components/event-type-detail/tabs/RecurringTab.tsx (1)
- components/event-type-detail/tabs/AvailabilityTab.tsx (1)
- components/event-type-list-item/EventTypeListItem.ios.tsx (3)
- components/BookingActionsModal.tsx (2)
- components/Tooltip.tsx (1)
- components/LocationsList.tsx (1)
- components/Header.tsx (1)
- components/EmptyScreen.tsx (1)

* correct command for edge

* dont break ci

* deslop ai
2025-12-19 23:50:20 +05:30
Pedro Castro af4a10c008 fix(seo): prevent booking confirmation pages from being indexed (#26058)
Booking confirmation pages contain PII (names, emails, phone numbers)
and should not be indexed by search engines

- Add robots noindex to /booking/[uid]/page.tsx
- Add robots noindex to /booking/[uid]/embed/page.tsx

Follows same pattern as not-found.tsx
2025-12-19 13:34:49 -03:00
Pedro Castro 90a83a611c docs: add ListEventTypes atom documentation (#25775)
- Add list-event-types.mdx with Quick start, Props, Demo video, and Combining with EventTypeSettings sections
- Add list_event_types_light.png screenshot
- Update mint.json navigation to include new page
2025-12-19 13:23:07 -03:00
sean-brydon b33d8c64df add turbo repo (#26051) 2025-12-19 14:27:19 +00:00
Carina WollendorferandCarinaWolli 73b276015c fix: remove pkce check for refreshToken endpoint (#26050)
* remove pkce check for refreshToken endpoint

* adjust e2e tests

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2025-12-19 15:18:49 +01:00
Abhishek 9c223fc718 fix: settings icon at app setup - event types (#26048)
* fix/setting-icon-app-card

* fix: settings icon app card
2025-12-19 14:13:58 +00:00
Eesh MidhaandRajiv Sahal 6910b85301 refactor(dialog): standardize icon container styling (#26036)
Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
2025-12-19 19:22:04 +05:30
125ed4f6f7 feat: update favicons with new Cal design (#25392)
* feat: add environment-based favicons (prod vs dev)

- Add cal-prod.png (dark/gray) favicon for production environments
- Add cal-dev.png (red) favicon for development/localhost environments
- Update FAVICON_16 and FAVICON_32 constants to switch based on IS_PRODUCTION

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

* feat: add higher resolution icons for all icon types (apple-touch, android-chrome, mstile)

- Add 180x180 apple-touch-icon for prod and dev
- Add 150x150 mstile icons for prod and dev
- Add 192x192 and 256x256 android-chrome icons for prod and dev
- Update all icon constants to use IS_PRODUCTION switching

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

* refactor: simplify favicon to single new design

- Remove environment-based favicon switching
- Update all icon files with new Cal favicon design
- Remove dev/prod icon variants
- Update constants to use static icon paths

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

* feat: add favicon.ico with new Cal favicon design

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

* chore: update favicon icons with final design

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

* chore: update favicon icons with final design v3

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-19 13:12:14 +00:00
Kartik Labhshetwar 2cab5475ce fix: improve CustomEmailTextField styling and focus behavior (#26024) 2025-12-19 13:08:28 +00:00
Syed Ali Shahbaz 5032d2716d fix: Add email to user select in credential to ensure consistent type (#26020)
* Add email to user select

* type fix
2025-12-19 13:03:04 +00:00
3ccf001e1d fix: add name property to delegation credentials for type compatibility (#26022)
* fix: add name property to delegation credentials for type compatibility

The MultiDisconnectIntegration component expects credentials with user.name property,
but delegation credentials only had user.email. This caused a type mismatch when
spreading both credential types together in appCredentialsByType handler.

Added name: null to the delegation credentials user object to ensure type compatibility.

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* fix: update getUserDisplayName to check value instead of just property existence

The narrowing logic was causing TypeScript to infer 'never' type because
after adding name property to delegation credentials, the 'name in user'
check always passes. Now we check if name has a truthy value before using it.

Also fixed lint warning by using optional chaining for onSuccess callback.

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* fix: add explicit return type and typeof checks to getUserDisplayName

The function now has an explicit return type of string | null and uses
typeof checks to ensure proper type narrowing. This prevents TypeScript
from inferring a wider return type that includes {} when the user object
has properties with non-string types.

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* test: update delegation credential test to include name property

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-19 12:21:48 +00:00
4c282ea9ca feat: add promotion codes support to SMS credit purchases (#23774)
Co-authored-by: peer@cal.com <peer@cal.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-12-19 08:57:13 -03:00
Anik Dhabal Babu 1135e47338 fix: render markdown in custom page redirect messages (#25987)
Before:-
<img width="1986" height="762" alt="image (26)" src="https://github.com/user-attachments/assets/90e16a5c-a8f1-4269-8873-8854a82c012e" />
<img width="3456" height="2068" alt="image (27)" src="https://github.com/user-attachments/assets/6714a1d5-454d-4fe7-b6ce-84120353a10a" />
After:-
<img width="977" height="456" alt="Screenshot 2025-12-17 at 9 09 22 PM" src="https://github.com/user-attachments/assets/449611ab-8d84-41e2-a342-0e334562cec5" />
2025-12-19 16:44:06 +05:30
Udit TakkarandAnik Dhabal Babu 68e670ae06 fix: hide OOO slots across timezones (#25966)
* fix: use organizer timezone

* fix: use organizer timezone

* fix: use organizer timezone

* fix type error

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-12-19 08:12:39 -03:00
sean-brydon 8b13979a41 chore: implement posthog tracking company email upgrade point (#25977)
* implement posthog tracking

* track dismiss
2025-12-19 10:39:30 +00:00
4beebd227b fix: flaky E2E tests and refactor (#25974)
* fix: flaky E2E tests and refactor

* fix

* fix: week limit tests to use same week for pre-booking and UI booking

The week limit tests were failing because the pre-booking was created in
week 1 but the UI booking was done in week 2. Since weekly limits are
per-week, the pre-booking didn't count toward the limit in week 2.

Fixed by keeping both bookings in the same week:
- Pre-booking on Monday (satisfies daily limit, counts toward weekly)
- UI booking on Tuesday (same week, hits weekly limit of 2)

This ensures the weekly limit is properly tested and all remaining
weekdays in the week get blocked after hitting the limit.

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-19 07:35:47 -03:00
Prateek Dwivedi 853358d9c4 fix(logging): replace console.log with logger.error in editLocation handler (#26037) 2025-12-19 08:15:44 +00:00
PallavandAnik Dhabal Babu 7dcf4ee5c8 fix: prevent custom calendar for team event (#26033)
* fix: prevent custom calendar for team event

* Remove commented-out disableRescheduling code

Removed commented-out code for disabling rescheduling.

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-12-19 07:22:27 +00:00
42f2c170aa feat: add coss-ui core package (#25984)
* Install/add components in base coss-ui package

* fix components imports

* add yarn script to pull

* Update packagejson

* remove skeleton duplicates

* feat: allow importing components with the cli

* fix: update exports in package.json to reference styles.css instead of globals.css

* add lucide dep

* refactor: re-pull components

* refactor: remove unused registries section from components.json

* refactor: implement changes suggested by Volnei

* refactor(wip): implemet coss ui components on the profile page

* fix src/src problem

* update command to overwrite existing components

* pulled from registry

* restore globals.css

* feat: add pull script

* feat: enhance pull script with validation and error handling

* remove duplicate components

* refactor: reimport coss component and fix ts errors

* fix: components pulling

* chore: regenerate yarn.lock

* chore: remove tailwindcss/forms

* trying different moduleResolution

* TypeScript requires module to also be "NodeNext".

* remove unnecessary changes

* type fixes plus resolve @coss/ui

* use bundler tsconfig

* add missing deps to features and ui

* Add bundler to other packages

* fix module enext resolution with bundler

* remove reduant files

* remove package json from features

* revert unrelated change to the PR

---------

Co-authored-by: pasqualevitiello <pasqualevitiello@gmail.com>
Co-authored-by: Eunjae Lee <hey@eunjae.dev>
2025-12-18 19:57:21 +00:00
Peer RichelsenandDhairyashil 3423777ee3 feat: gmail, outlook, yahoo links during email verification (#26038)
* added gmail, outlook, yahoo links during email verification

* added proton

* enable for self-hosters too

* undo i18n

* Discard changes to companion/bun.lock

* nit

* refactor: code quality improvments

---------

Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>
2025-12-18 19:56:38 +00:00
Dhairyashil ShindeandVolnei Munhoz c8a8c37b45 fix(companion): prevent localhost URL from being baked into production extension builds (#26032)
* fix(companion): separate dev and prod build scripts to prevent localhost in production

- Add ext:build-dev and ext:build-prod scripts with clear separation
- Add BUILD_FOR_STORE flag to force production URL in store builds
- Add visual build indicators (store / dev) for clarity
- Prevent EXPO_PUBLIC_COMPANION_DEV_URL from leaking into production builds

* update commands to work for ci

* update version

---------

Co-authored-by: Volnei Munhoz <volnei@cal.com>
2025-12-18 19:19:04 +00:00
Benny JooandAnik Dhabal Babu f291c1c4e7 fix: add mergeWithEnglishFallback for i18n translations (#26016)
* fix

* fix

* fix

* fix

* Improve translation cache handling in i18n.ts

Refactor translation cache retrieval and fallback logic.

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-12-18 16:47:54 +00:00
Hariom BalharaandDevin AI 71792bdeaa fix: ensure linkFailed event fires for 404, 500, and 403 errors in embeds (#25261)
- Add CalComPageStatus handling in NotFound and ErrorPage components using useLayoutEffect
- Remove redundant pageStatus logic from PageWrapperAppDir.tsx since App Router error/notFound pages set status themselves
- Refactor embed-iframe.ts: split checkPageStatusAndHandleError into hasPageError() and handlePageError()
- Add page status checks before firing linkReady to catch errors set after initialization
- Ensures linkFailed event fires correctly for all error status codes in embed scenarios

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-18 16:30:32 +00:00
Eunjae Lee 945ded951f fix: integration test of booking audit service (#26027) 2025-12-18 15:26:03 +00:00
Pedro CastroandMorgan 975fb21d86 feat(atoms): add ListEventTypes atom to enable event type management (#25047) (#25113)
* feat: add ListEventTypes atom (#25047)

* feat: add ListEventTypes atom for Platform (#25047)

- Add EventTypeListItem component in @calcom/features
- Add ListEventTypesPlatformWrapper with delete functionality
- Implement useAtomGetAllEventTypes hook
- Update backend to include slug, description, length
- Add 11 unit tests (65% coverage)
- Add 3 i18n keys

No breaking changes. Backward compatible.

* refactor(eventtypes): improve EventTypeListItem readability

- Extract EventTypeContent and EventTypeActions sub-components
- Add formatEventTypeDuration helper (90min → '1h 30m')
- Use Badge for duration display (consistency with EventTypeDescription)
- Use polymorphic Wrapper component (DRY)
- Add comprehensive tests
- Reduce main component size

Addresses @volnei feedback

* refactor: replace window.confirm with ConfirmationDialog

- Replace native window.confirm with ConfirmationDialogContent

- Update test mocks for Dialog components

- Fix HTML nesting (div instead of p for Badge container)

- Follows Cal.com pattern from AvailabilitySettings

Addresses @ThyMinimalDev feedback

* fix: add aria-label to options button for accessibility

* test: update getBulkEventTypes test to include new fields (description, slug, length)

* refactor: move EventTypeListItem to atoms package

---------

Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2025-12-18 12:24:41 -03:00
Anik Dhabal Babuandcubic-dev-ai[bot] b20b52a1f8 fix: update tempOrgRediret on updating org slug (#25838)
* fix: update tempOrgRediret on updating s
lug

* Update packages/trpc/server/routers/viewer/organizations/adminUpdate.handler.ts

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

* refactor

* fix

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-12-18 13:18:56 +00:00
Benny Joo 176aeaafd8 refactor: trpc test file is importing @calcom/web (#25979)
* add eslint config

* refactor test
2025-12-18 10:10:46 -03:00
Anik Dhabal Babu 9ba867922a fix type error (#26021) 2025-12-18 12:55:54 +00:00
Hariom BalharaandDevin AI f1011ddd08 chore: Improves the core booking audit architecture by adding new capabilities and simplifying the existing interfaces. (#25872)
* feat(booking-audit): extract core audit system changes from PR 25125

This PR extracts core audit infrastructure changes without integration changes:

1. New action services introduced:
   - SeatBookedAuditActionService
   - SeatRescheduledAuditActionService

2. Simplification of ActionService interface:
   - Streamlined IAuditActionService interface
   - Reduced TypeScript burden with cleaner type definitions

3. ActionSource support:
   - Added BookingAuditSource enum (API_V1, API_V2, WEBAPP, WEBHOOK, UNKNOWN)
   - Added source and operationId fields to BookingAudit model

4. New AuditAction types:
   - SEAT_BOOKED
   - SEAT_RESCHEDULED
   - APP actor type

5. New BookingAuditAccessService:
   - Permission-based access control for audit logs
   - Added readTeamAuditLogs and readOrgAuditLogs permissions

6. Fixes in the logs viewer flow:
   - Enhanced BookingAuditViewerService with improved filtering
   - Local AttendeeRepository for actor enrichment

Changes are contained within packages/features/booking-audit with minimal
outside changes (permission registry only).

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

* refactor(booking-audit): streamline action handling and enhance localization

- Replaced action icon retrieval with a mapping object for improved clarity and performance.
- Introduced constants for actor role labels to simplify role retrieval.
- Added new localization strings for audit log permission errors and organization requirements.
- Updated various service and repository interfaces to enhance type safety and clarity.
- Removed deprecated architecture documentation and adjusted related imports for consistency.

These changes aim to improve code maintainability and user experience in the booking audit system.

* fix(booking-audit): enhance actor role localization and operation ID tracking

- Updated actor role labels in the booking logs view to use lowercase for consistency.
- Improved localization by wrapping actor role display in a translation function.
- Added operationId field to audit logs for better correlation of actions across multiple bookings.
- Enhanced BookingAuditViewerService to include operationId in enriched audit logs.
- Updated integration tests to verify consistent operationId across related audit logs.

These changes aim to improve localization accuracy and facilitate better tracking of user actions in the booking audit system.

* feat: integrate credential repository and enhance app actor handling

- Added CredentialRepository to manage app credentials, including a method to find credentials by ID.
- Updated BookingAudit system to support app actors identified by credential ID, improving actor attribution and audit clarity.
- Introduced a new utility function to map app slugs to display names, enhancing the user experience in audit logs.
- Modified relevant interfaces and types to accommodate the new credential handling and app actor structure.
- Enhanced BookingAuditViewerService to display app names based on credentials, ensuring accurate representation in audit logs.

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-18 12:46:24 +00:00
9019be58ed fix: allow required check to pass when E2E tests are skipped due to missing label (#26006)
* fix: allow required check to pass when E2E tests are skipped due to missing label

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* revert: remove unnecessary integration-test condition change

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* chore: trigger fresh CI run

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* all should pass to allow merge

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-18 08:49:12 -03:00
Eunjae LeeandDevin AI cef8610925 feat: add enabled column to UserFeatures and TeamFeatures for tri-state semantics (#25765)
* feat: add enabled column to UserFeatures and TeamFeatures for tri-state semantics

- Add enabled Boolean column to UserFeatures model with default true
- Add enabled Boolean column to TeamFeatures model with default true
- Update FeaturesRepository to use tri-state semantics:
  - enabled=true: feature is explicitly enabled
  - enabled=false: feature is explicitly disabled (blocks inheritance)
  - No row: inherit from team/org level
- Update SQL queries to check enabled=true for feature access
- Add enableFeatureForTeam method to interface and implementation

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

* update comments

* add integration tests

* add more test

* select enabled only

* no @default(true)

* fix types and tests

* add missing enabled

* add missing enabled

* rename enableFeatureForTeam to updateFeatureForTeam and support FeatureState

* refactor: rename updateFeatureForTeam to setTeamFeatureState

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

* fix integration test

* fix tests

* add more tests

* add missing enabled

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-18 07:16:20 -03:00
Syed Ali Shahbaz 056922b6ee feat: add webhook versioning (#23861)
* add webhook version schema

* version the code

* update version from numeric to date val

* migration

* update schema and build factory

* update string

* move version picker

* tooltip instead of infobadge

* --

* fix type

* --

* fix type

* fix type

* --

* fix messed up merge

* improvements to payloadfactory

* extract version off of DB and instead keep it in IWebhookRepository

* fix webhookform

* fix type safety and routing ambiguity

* scalable with easier factory extensions and base definition

* fix types

* --

* --

* clean up prisma/client type imports

* fix

* type fix

* type fix

* cleanup

* add tests and registry changes

* unintended file inclusion

* type-fix

* select in repo

* --

* explicit return type

* --

* fix type

* fixes

* feedback 1

* feedback 2

* use enum instead of string

* fixes
2025-12-18 09:36:22 +02:00
Dhairyashil Shinde 42bd4b4057 fix: make isReschedule required in checkIfBookerEmailIsBlocked (#26002) 2025-12-17 19:52:10 -03:00
sean-brydonandcubic-dev-ai[bot] 64767cec4f chore: add onboarding events in posthog (#25981)
* add onboarding events in posthog

* Update apps/web/modules/onboarding/organization/teams/organization-teams-view.tsx

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

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-12-17 22:43:54 +00:00
Volnei MunhozandPeer Richelsen e84550ba76 chore: Isolate companion build (#25985)
* Isolate companion build

* Fix typo

* Update .github/workflows/pr.yml

* Improve branch protection

* integration tests missing

* fix typo

* fix to only have required

* fix to only have required

* fix to only have required

* adjust to keep as before

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-12-17 22:42:10 +00:00
Keith Williams e6d0253950 chore: Change atoms build command to build-npm (#25996)
* chore: Change atoms build command to build-npm to avoid turbo compilations

* Updated turbo.json atoms#build reference

* Updated atoms production build for CI
2025-12-17 16:30:54 -03:00
Dhairyashil ShindeandPeer Richelsen 471d1caac9 fix(companion): Fix Gmail OAuth integration (#25978)
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2025-12-17 15:13:54 -03:00
Keith WilliamsandDevin AI 15b1675db1 perf: reduce TypeScript type bloat in tRPC package via z.ZodType annotations (#25845)
* fix: prevent Prisma conditional types from leaking into .d.ts files

This PR addresses TypeScript performance issues caused by Prisma's conditional types leaking through the type graph:

1. Replace Prisma.UserGetPayload with explicit UpdatedUserResult type in updateProfile.handler.ts
2. Replace Prisma.EventTypeGetPayload with explicit UpdatedEventTypeResult type in update.handler.ts
3. Replace Prisma.OutOfOfficeEntryGetPayload with explicit OOOEntryResult type in outOfOfficeCreateOrUpdate.handler.ts
4. Replace Prisma.CredentialGetPayload with explicit Credential type in getUserConnectedApps.handler.ts
5. Fix inconsistent DI usage in EventTypeRepository - use this.prismaClient instead of global prisma singleton

These changes prevent massive recursive Prisma types from propagating through the type graph and being emitted in .d.ts files, which improves TypeScript performance.

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

* fix: correct reasonId type to number | null in OOOEntryResult

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

* perf: add z.ZodType annotations to reduce .d.ts file sizes

- Annotate exported Zod schemas with z.ZodType<T> to prevent full Zod generic tree from being emitted in declaration files
- eventTypes/types.d.ts reduced from 231KB to 115KB (50% reduction)
- _app.d.ts reduced from 782KB to 753KB (3.7% reduction)
- viewer/_router.d.ts reduced from 722KB to 695KB (3.7% reduction)
- workflows/getAllActiveWorkflows.schema.d.ts significantly reduced
- routing-forms/formMutation.schema.d.ts significantly reduced

Files modified:
- packages/trpc/server/routers/viewer/eventTypes/types.ts
- packages/trpc/server/routers/viewer/workflows/getAllActiveWorkflows.schema.ts
- packages/trpc/server/routers/apps/routing-forms/formMutation.schema.ts
- packages/features/eventtypes/lib/types.ts

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

* perf: comprehensive z.ZodType annotations to reduce .d.ts file sizes

Applied z.ZodType<T> annotations to 89 schema files across the tRPC package.
This prevents TypeScript from emitting the full Zod generic tree in .d.ts files,
reducing declaration file sizes for downstream consumers.

Files modified include schemas in:
- viewer/teams (round-robin, managed events, invitations, etc.)
- viewer/bookings (get, find, confirm, etc.)
- viewer/eventTypes (get, delete, getByViewer, etc.)
- viewer/workflows (list, delete, verify, etc.)
- viewer/auth (changePassword, verifyPassword, etc.)
- viewer/apiKeys (create, delete, edit, etc.)
- viewer/sso (get, update, delete, updateOIDC)
- viewer/oAuth (addClient, generateAuthCode)
- viewer/calendars (setDestinationCalendar)
- viewer/deploymentSetup (update, validateLicense)
- apps/routing-forms (formQuery, deleteForm, etc.)
- publicViewer (submitRating, markHostAsNoShow, etc.)
- loggedInViewer (eventTypeOrder, routingFormOrder, etc.)

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

* fix: revert slots/types.ts z.ZodType annotation that caused type mismatch

The slots/types.ts schema has a transform that converts duration from
string to number, which makes the z.ZodType<T> annotation incompatible.
Reverting to original to fix Unit test failure.

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

* fix: use 3-generic z.ZodType pattern for schemas with .default() modifiers

For schemas with .default() modifiers, the input and output types differ:
- Input type: field is optional (what callers send)
- Output type: field is required (what handlers receive after parsing)

This commit:
1. Fixes get.schema.ts (offset has .default(0))
2. Fixes removeMember.schema.ts (isOrg has .default(false))
3. Fixes resendInvitation.schema.ts (isOrg has .default(false))
4. Fixes listMembers.schema.ts (limit has .default(10))
5. Fixes getByViewer.schema.ts (limit has .default(10))
6. Reverts eventTypes/types.ts (complex transforms hard to model)
7. Reverts features/eventtypes/lib/types.ts (complex transforms hard to model)

The 3-generic pattern z.ZodType<Output, z.ZodTypeDef, Input> properly models
the difference between input and output types while still preventing the full
Zod generic tree from being emitted in .d.ts files.

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

* fix: use 3-generic z.ZodType pattern for schemas with transforms/defaults

- organizations/update.schema.ts: orgId has .transform() that converts string to number, so input type is string | number but output type is number
- publicViewer/event.schema.ts: fromRedirectOfNonOrgLink has .default(false), so input has it optional but output has it required

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

* fix: use 3-generic z.ZodType pattern for updateProfile.schema.ts

Address reviewer feedback: isDeleted field in secondaryEmails has .default(false),
so input type has it optional but output type has it required.

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

* chore: remove explanatory comments from schema files

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

* fix: use 3-generic z.ZodType pattern for addClient.schema.ts enablePkce field

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

* fix: address Hariom's PR feedback

- Rename TGetInputSchemaInput to TGetInputRawSchema in get.schema.ts
- Use Prisma-free JsonValue type from @calcom/types/Json in updateProfile.handler.ts
- Fix publish.schema.ts with 3-generic pattern for z.coerce.number()

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

* fix: add sort field to TGetInputSchema types

Added sort field to both TGetInputRawSchema and TGetInputSchema types
to match the Zod schema that was updated in main branch.

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-17 15:06:57 -03:00
Calcom Bot c20f6cbdd6 feat: update translations via @LingoDotDev (#24385)
Hey team,

[**Lingo.dev**](https://lingo.dev) here with fresh translations!

### In this update

- Added missing translations
- Performed brand voice, context and glossary checks
- Enhanced translations using Lingo.dev Localization Engine

### Next Steps

- [x] Review the changes
- [x] Merge when ready
2025-12-17 13:30:35 -03:00
Benny Joo 03dd0c1501 refactor: Move SelectedCalendarRepository and WorkflowRelationsRepository from /lib to /features (#25982)
* wip

* wip
2025-12-17 16:05:03 +00:00
Beto 84ecb0e568 chore(companion): update dependencies to latest expo canary version (#25948)
* chore: update dependencies and update event types screen header

* refactor: simplify EventTypeListItem component by removing unused imports and code

- Removed unnecessary imports such as Tooltip and Svg.
- Cleaned up the component by eliminating commented-out code and unused props.
- Streamlined the button rendering in the context menu for better readability.

* feat: enhance EventTypes header with blur effect and clean up code

- Added blurEffect property to Stack.Header for improved visual aesthetics.
- Removed commented-out code to streamline the EventTypes component.
- Updated search bar properties for better user experience.

* refactor: update TabLayout and EventTypes for improved platform handling

- Simplified TabLayout by removing the liquid glass effect check and adding a WebTabs fallback for web support.
- Updated EventTypes header to conditionally apply blur effect based on liquid glass availability, enhancing visual consistency across platforms.

* feat: enhance TabLayout with MaterialCommunityIcons for improved UI

- Updated TabLayout to use MaterialCommunityIcons for tab icons, enhancing visual consistency.
- Added softwareKeyboardLayoutMode to app.json for better keyboard handling on mobile devices.

* feat: update TabLayout to prevent transparent background on iOS 18

- Added disableTransparentOnScrollEdge prop to NativeTabs to ensure a solid background on iOS 18 and older versions.
2025-12-17 15:37:52 +00:00
Anik Dhabal BabuandDevin AI 27775e5d03 fix: preserve newlines and links in calendar event descriptions (#25868)
The event type description is stored as HTML from the rich text editor.
When converting to plain text for calendar events, the HTML tags were
being stripped without preserving the formatting, causing:
- Newlines to be lost (text runs together)
- Links to be broken

This fix:
- Converts <br>, </p>, </div>, </li>, </h1-6> tags to newlines
- Preserves links in readable format: 'text (url)' or just 'url'
- Normalizes multiple newlines to max 2 for cleaner output

Affects all calendar integrations (Google, Outlook, etc.)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-17 15:02:12 +00:00
Benny Joo 0986864835 refactor: Move PrismaRoutingFormRepository from lib to /features/routing-forms (#25975)
* wip

* update import paths
2025-12-17 14:26:17 +00:00
Benny Joo cb7844fd22 refactor: Migrate repositories/services from /lib to /features (#25925)
* deployment

* update imports

* booking report

* update import paths

* watch list

* watch list

* api key

* api key

* selected slots

* wip

* event type translation

* work flow step

* booking reference

* fix tests

* fix

* fix

* migrate

* wip

* address

* fix
2025-12-17 14:14:50 +00:00
Eunjae LeeandDevin AI aaaff0705b fix(bookings): enable past date selection for cancelled bookings (#25644)
* refactor(data-table): clean up DateRangeFilter range options

- Replace 'past' | 'custom' with 'past' | 'future' | 'any' | 'customOnly'
- Add direction field to PresetOption for preset compatibility filtering
- Derive presets visibility automatically based on compatible presets
- Update bookings list to use new range values:
  - past -> 'past'
  - upcoming -> 'future'
  - unconfirmed/recurring/cancelled -> 'any'

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

* feat(playground): add DateRangeFilter playground page with E2E tests

- Add playground page at /settings/admin/playground/date-range-filter
- Demonstrate all 4 range options: past, future, any, customOnly
- Add link to playground index page
- Add E2E tests for presets visibility and date restrictions

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

* fix(playground): use correct meta.filter pattern for column filter config

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

* clean up the playground esign

* add unit tests instead of e2e

* fix the implementation

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-17 13:47:51 +00:00
Benny Joo dd27d077ca refactor: Create TravelScheduleRepository and PrismaOrgMembershipRepository in /features (#25853)
* move repo to travelSchedule

* update imports

* mv

* update imports
2025-12-17 10:24:44 -03:00
Carina WollendorferandCarinaWolli 5fe3714edd feat: auto skip consent screen for trusted oauth clients (#25640)
* auto constent for trusted clients

* add loading state

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2025-12-17 13:00:12 +00:00
Eunjae LeeandDevin AI e0a28af46e feat(bookings): conditionally show heading/subtitle based on view (#25889)
* feat(bookings): conditionally show heading/subtitle based on view

- Add heading and subtitle props back to ShellMainAppDir in page.tsx
- Use headerClassName marker to identify the heading element
- Add useLayoutEffect in BookingCalendarContainer to hide heading when calendar view is mounted
- Restore heading visibility when switching back to list view

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

* refactor(bookings): extract shell heading visibility into reusable hook

- Create useBookingsShellHeadingVisibility hook with explicit visible parameter
- Move visibility logic from BookingCalendarContainer to BookingsContent
- Use data attribute to track if we hid the header (idempotent/Strict-Mode-safe)
- Explicit show/hide based on view state instead of relying on unmount

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

* refactor(bookings): simplify shell heading visibility hook

Remove HIDDEN_DATA_ATTR tracking since the header wrapper won't have
a hidden class from any other source

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-17 12:46:12 +00:00
Kartik Labhshetwar 970af8bd6a fix: change button color to destructive in WorkflowListPage (#25965) 2025-12-17 12:42:00 +00:00
Dhairyashil Shinde 2f1dd92677 feat(companion): open cal.com/app on new tab and fix extension/mobile UX issues (#25962)
* feat(companion): improve extension UX for new tab and fix mobile app issues

- Open cal.com/app when extension clicked on restricted pages (chrome://newtab, etc.)
- Auto-open sidebar when redirected to cal.com/app with ?openExtension=true
- Fix duplicate search bar in event types on web/extension
- Fix tab order mismatch on extension (Event Types, Bookings, Availability, More)
- Add logout confirmation modal for web since Alert.alert doesn't work
- Default COMPANION_DEV_URL to empty string for production builds

* fix(companion): use URL API for query parameter cleanup

Replace regex-based URL cleanup with URL API to properly handle
all query parameter positions. The previous regex produced invalid
URLs when openExtension=true was the first of multiple parameters
(e.g., ?openExtension=true&foo=bar became &foo=bar instead of ?foo=bar). fix(companion): wait for page load before auto-opening sidebar

Fix race condition where sidebar wouldn't auto-open on first visit
to cal.com/app. On uncached pages, now waits for the load event
before opening, while cached pages use a shorter delay.
2025-12-17 17:14:37 +05:30
Udit Takkar 61c8c9d970 chore: pass guests (#25961) 2025-12-17 11:43:42 +00:00
Abhishek 0604c960a4 fix: popover ios issue (#25696)
* fix: popover ios issue

* add comments

* more comments
2025-12-17 10:14:56 +00:00
Eunjae Lee c361b9bbc5 chore: enable booking redesign for e2e (#25642)
* enable bookings-v3 feature flag for e2e tests WIP

* fix e2e

* update comments
2025-12-17 10:09:09 +00:00
Volnei Munhoz c2d275551a Remove next build eslint and ts checks disabled for CI (#25950) 2025-12-17 03:43:00 +00:00
Volnei Munhoz 0ea7f1944f fix types (#25952)
Post release / release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
2025-12-17 02:56:15 +00:00
Alex van Andel 1af7bfa20e chore: release v6.0.2 2025-12-17 02:38:43 +00:00
Volnei Munhoz 641b249e92 chore: release amd as latest (#25949)
* release amd as latest

* remove dockerfile change

* Apply suggestions from code review

changed from linux/amd64 to amd64

* Revert removed comment

* introduce latest as parameter

* introduce latest as parameter
2025-12-17 02:35:55 +00:00
Volnei Munhoz f3f5725563 chore/fix onboarding types (#25951) 2025-12-17 02:09:26 +00:00
Dhairyashil Shinde a2a77376b3 fix: companion extension oauth (#25939)
* fix: companion extension oauth

* fix: ios build

* address cubics comments
2025-12-16 22:22:44 +00:00
Hariom Balhara ee298af4eb fix: update email validation to include pm.me and other email provider domain (#25879)
* fix: update email validation to include pm.me domain and improve error handling in extractDomainFromEmail function

* feat(organizations): add pm.me and additional personal email domains

- Add pm.me (ProtonMail short domain) to personal email providers list
- Add googlemail.com, ymail.com, msn.com, mac.com, and other common personal email domains
- Add Mail.com variants (email.com, post.com, consultant.com, etc.)
- Add protonmail.ch, gmx.de, naver.com, and other regional providers
- Update all three locations: utils.ts, orgCreationUtils.ts, and test file
- Fix ESLint warnings for unnecessary escape characters in regex
2025-12-16 18:45:35 +00:00
Rakshit Sisodiya 47a5fc7bf7 fix: allow organizations to sign up with existing usernames (#25941)
* fix: allow organizations to sign up with existing usernames

- Update usernameCheck to check organization context when currentOrgDomain is provided
- Organizations can now use usernames that exist in other orgs or global namespace
- Only checks username availability within the specific organization
- Fixes issue where org signups were blocked by global username conflicts

Refs #25800

* Update username.ts
2025-12-16 17:47:59 +00:00
Volnei Munhoz a1a5f2477d fix check types (#25907) 2025-12-16 17:07:32 +00:00
sean-brydon 94e0d476d9 fix: skip plan on invite to team (#25924)
* fix: skip plan on invite to team

* address cubic
2025-12-16 14:44:35 +00:00
45fcabef8c chore: replace GH_ACCESS_TOKEN with GitHub App token (#25518)
* chore: replace GH_ACCESS_TOKEN with GitHub App token

Replace personal access token (GH_ACCESS_TOKEN) with GitHub App token
generation using actions/create-github-app-token@v1 for improved security.

Updated workflows:
- draft-release.yml
- post-release.yml
- cleanup.yml
- cleanup-report.yml
- publish-report.yml
- i18n.yml

Benefits:
- Short-lived tokens (1 hour) vs long-lived PATs
- Fine-grained, scoped permissions
- Not tied to individual user accounts
- Better audit trail

Required setup:
- Create a GitHub App with contents:write permission
- Install the app on calcom/cal.com and calcom/test-results-2
- Add RELEASE_APP_ID and RELEASE_APP_PRIVATE_KEY secrets

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

* chore: rename secrets to CI_CAL_APP_ID and CI_CAL_APP_PRIVATE_KEY

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

* chore: use reusable workflow from calcom-ci-secrets for token generation

This isolates the GitHub App private key in a separate repository,
ensuring that compromised actions in cal.com can only access short-lived
tokens, not the key itself.

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

* chore: use explicit secret passing instead of secrets: inherit

Only pass the two required secrets (CI_CAL_APP_ID, CI_CAL_APP_PRIVATE_KEY)
to the reusable workflow instead of inheriting all secrets.

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

* chore: remove secrets block - using environment secrets from calcom-ci-secrets

Secrets are now loaded from the ci-github-app environment in
calcom-ci-secrets, so cal.com workflows no longer need to pass them.

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

* chore: revert to explicit secret passing

Environment secrets in cross-repo reusable workflows don't work as expected.
Secrets must be passed explicitly from the caller repository.

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

* chore: generate GitHub App token directly in workflows

Remove dependency on calcom-ci-secrets reusable workflow.
Token generation is now inline using actions/create-github-app-token
pinned to SHA 7e473efe3cb98aa54f8d4bac15400b15fad77d94 (v2.2.0).

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-12-16 14:12:56 +00:00
Anik Dhabal Babu 593ed461c8 slugify lenient (#25923) 2025-12-16 14:01:54 +00:00
Morgan b8827aca52 fix: atoms css scoping (#25921)
* fix: atoms css scoping

* fixup! fix: atoms css scoping
2025-12-16 19:20:46 +05:30
Benny JooandVolnei Munhoz c3bcd623f6 refactor: create CreditsRepository in /features/credits (#25843)
* mv test

* mv repo

* update imports

* Update packages/features/ee/billing/api/webhook/_checkout.session.completed.ts

Co-authored-by: Volnei Munhoz <volnei@cal.com>

* fix test

---------

Co-authored-by: Volnei Munhoz <volnei@cal.com>
2025-12-16 10:42:27 -03:00
Kartik Labhshetwar 272cf43322 fix: add dark mode support to emptypage skeleton and layout (#25913)
* fix: add dark mode support to emptypage skeleton and layout

* style: remove dark blur effect from EmptyPage component

* style: add dark mode divide subtle to EmptyPage component
2025-12-16 12:45:23 +00:00
Anik Dhabal Babu a8e2ba4663 Revert "fix: improve E2E test stability and reduce flakiness (#25897)" (#25919)
This reverts commit b83f8dd6b8.
2025-12-16 12:30:50 +00:00
3082d6c2f3 feat: export all booking question fields in csv for non seated events in insights (#25837)
* feat(insights): include all booking question fields in CSV export for non-seated events

- For non-seated events: export all custom booking question fields (phone, text, number, select, multiselect, url, checkbox, textarea) excluding system fields
- For seated events: preserve existing behavior (only phone-type fields)
- Add extractFieldValue helper to handle all field value types
- Fix phone fallback logic to only use actual phone field values
- Optimize cache lookup with single get() instead of has() + get()

* refactor(insights): extract CSV data transformation logic into separate module

- Extract manipulation logic from getCsvData into csvDataTransformer.ts
- Add extractFieldValue, isSystemField, and other helper functions
- Add processBookingsForCsv and transformBookingsForCsv functions
- Add comprehensive snapshot tests with dummy data
- Tests demonstrate how input becomes output for various scenarios

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

* fix(insights): update BookingWithAttendees type to match Prisma query result

- Change noShow field type from boolean to boolean | null
- Fixes type error TS2345 in InsightsBookingBaseService.ts

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: eunjae@cal.com <hey@eunjae.dev>
2025-12-16 10:35:21 +00:00
Benny JooandDevin AI f98acb7301 refactor: migrate workflows utilities from trpc to features layer (#25534)
* refactor: migrate workflows utilities from trpc to features layer

Move workflow utility functions from packages/trpc/server/routers/viewer/workflows/util.ts
to packages/features/ee/workflows/lib/workflowUtils.ts to break circular dependencies.

Functions migrated:
- isAuthorized
- getAllWorkflowsFromEventType
- scheduleWorkflowNotifications
- scheduleBookingReminders

Changes:
- Created new workflowUtils.ts in features layer with migrated functions
- Added getBookingsForWorkflowReminders to WorkflowRepository (no prisma outside repositories)
- Updated all imports in features layer to use new location
- Updated trpc util.ts to re-export from features for backward compatibility
- Fixed pre-existing lint warning (any -> unknown) in handleMarkNoShow.ts

This is part of the effort to remove circular dependencies between
packages/features and packages/trpc.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* refactor: remove re-exports from trpc util.ts, update imports to use features layer

Per user request, removed the backward compatibility re-exports from
packages/trpc/server/routers/viewer/workflows/util.ts and updated all
imports in the trpc package to import directly from the features layer.

Files updated to import from @calcom/features/ee/workflows/lib/workflowUtils:
- confirm.handler.ts (getAllWorkflowsFromEventType)
- delete.handler.ts (isAuthorized)
- update.handler.ts (isAuthorized, scheduleWorkflowNotifications)
- getAllActiveWorkflows.handler.ts (getAllWorkflowsFromEventType)
- get.handler.ts (isAuthorized)
- util.test.ts (isAuthorized)
- delete.handler.test.ts (isAuthorized)

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: update test imports to use features layer for workflow utilities

Updated test files to import scheduleBookingReminders and
scheduleWorkflowNotifications from @calcom/features/ee/workflows/lib/workflowUtils
instead of @calcom/trpc/server/routers/viewer/workflows/util.

Files updated:
- packages/features/ee/workflows/lib/test/workflows.test.ts
- packages/features/tasker/tasks/scanWorkflowBody.test.ts

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* refactor: split workflowUtils.ts into individual files

Split the monolithic workflowUtils.ts into separate files for each function:
- isAuthorized.ts - Authorization check for workflow access
- getAllWorkflowsFromEventType.ts - Get workflows for an event type
- scheduleWorkflowNotifications.ts - Schedule workflow notifications
- scheduleBookingReminders.ts - Schedule booking reminders

The workflowUtils.ts now re-exports from these individual files for
backward compatibility.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix import

* fix more

* wip

* wip

* remove workflowUtils

* wip

* refactor deleteRemindersOfActiveOnIds

* fix

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-16 10:17:46 +00:00
Anik Dhabal Babu 4e3ce77de4 fix: custom replyTo is not set (#25867) 2025-12-16 04:20:03 +00:00
InD3v 0b5b76d594 fix: adjust padding in timezone select, event advanced edit icon, and sidebar bottom nav (#25877) 2025-12-16 01:11:10 +00:00
Pallav b6935666e5 fix: disable button routing (#25894) 2025-12-16 01:10:37 +00:00
Alex van Andel b25a2bf202 chore: release v6.0.1
Post release / release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
2025-12-16 01:09:06 +00:00
Abhishek 06d4c7d102 fix lint (#25870) 2025-12-16 01:08:05 +00:00
Dhairyashil Shinde 5b9dd09f0d feat(holidays): improve UI/UX and add contextual emojis (#25895)
* refactor(holidays): improve code quality and address PR review feedback

- Move HolidaysView.tsx from /features to /apps/web/modules following
  the pattern of keeping trpc-using components in /apps/web/modules
- Fix prisma import to use named import: `import { prisma }`
- Fix timezone bug in checkConflicts: use dayjs.utc() for consistent
  date boundaries regardless of server timezone
- Fix toggleHoliday validation to include both current and next year
  holidays, matching the holidays displayed to users
- Implement dependency injection pattern for holiday repository:
  - Create PrismaHolidayRepository with instance methods
  - Add HOLIDAY_REPOSITORY DI token and module
  - Update containers to load holiday repository module
  - Update calculateHolidayBlockedDates to use injected repository
- Remove stale HOLIDAY_CACHE_DAYS env declaration (now a constant)
- Update tests to mock repository instead of prisma directly

* feat(holidays): improve UI responsiveness and add country flags

- Add country flag emojis to holidays dropdown using Unicode regional
  indicator symbols
- Handle edge cases for religious holidays (Hindu, Christian, etc.)
  which dont have 2-letter country codes
- Increase country dropdown width to 180px for better readability
- Make OOO/Holidays tabs responsive: use Select dropdown on mobile,
  ToggleGroup on desktop
- Make + Add button responsive: show only + icon on mobile,
  full text on desktop
- Fix PrismaHolidayRepository import to use @calcom/prisma for
  consistency with other repositories

* feat(holidays): add contextual emojis for holidays

- Add keyword-based emoji mapping for 80+ holidays
- Display holiday emojis in styled containers on settings page
- Add country flag emojis to dropdown using Unicode regional indicators
- Use dynamic emojis on booking page unavailable dates

* fix(holidays): address PR review feedback

- Fix emoji ordering: move Chinese/Lunar New Year before generic new year to prevent incorrect match
- Fix i18n: use t() instead of hardcoded text more in conflict warning
- Fix a11y: use sr-only pattern for mobile button to maintain screen reader accessibility

* fix failing test: packages/features/availability/lib/calculateHolidayBlockedDates.test.ts

* fix failing test: packages/features/availability/lib/calculateHolidayBlockedDates.test.ts

* fix failing tests and builds
2025-12-16 00:40:04 +00:00
Alex van Andel db2caa17ce fix: Allow single-label domains and missing dots (#25899) 2025-12-16 05:10:22 +05:30
b83f8dd6b8 fix: improve E2E test stability and reduce flakiness (#25897)
* fix: improve E2E test stability and reduce flakiness

- Replace hardcoded waits with proper Playwright waitFor assertions in slot selection
- Add explicit waits for calendar and time slot elements to be visible before clicking
- Replace fixed 2s wait in gotoRoutingLink with networkidle wait
- Replace fixed 5s email wait with retry logic (10 retries, 500ms intervals)
- Use unique usernames with timestamps to avoid parallel test collisions
- Use features fixture instead of direct prisma calls for feature flag mutations
- Fix login.e2e.ts to use unique username instead of hardcoded 'pro'
- Fix signup.e2e.ts to use unique usernames and proper feature flag handling
- Remove unused 'users' parameter from tests that don't need it

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* perf: replace waitForTimeout with smart waits for faster E2E tests

- Replace 30 waitForTimeout calls with proper Playwright waits
- Use waitFor({ state: 'visible' }) for element visibility
- Use waitForLoadState('networkidle') for page load completion
- Use waitForFunction for localStorage state changes

Performance improvements:
- limit-tab.e2e.ts: 10s fixed wait -> element visibility wait
- booking-duplicate-api-calls.e2e.ts: 5s fixed wait -> networkidle
- change-theme.e2e.ts: 3s fixed wait -> localStorage state check
- team-invitation.e2e.ts: multiple 500ms-3s waits -> element waits
- booking-seats.e2e.ts: 2s waits -> dropdown visibility waits
- embed-code-generator.e2e.ts: 1s waits -> iframe visibility waits
- organization-privacy.e2e.ts: 500ms waits -> element/networkidle waits
- organization-invitation.e2e.ts: 500ms-1s waits -> element waits
- analyticsApps.e2e.ts: 1s wait -> networkidle
- integrations.e2e.ts: 1s wait -> calendar element wait
- fixtures/apps.ts: 1s waits -> element visibility waits

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-15 20:19:47 -03:00
Beto 883ac103f8 fix: android redirect (#25888)
* fix android redirect

* remove logs
2025-12-15 18:14:42 +00:00
Volnei Munhoz d13adc8ffd Fix user parameter (#25884) 2025-12-15 18:07:28 +00:00
Kartik Labhshetwar d64255be47 fix: change sidebar hover background to subtle when locale ready (#25876) 2025-12-15 17:50:03 +00:00
Alex van Andel 5c5d221c76 chore: release v6.0.0
Post release / release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
2025-12-15 17:40:14 +00:00
Alex van Andel 852daa0175 chore: release v6.0.0 2025-12-15 17:16:33 +00:00
Volnei Munhoz 1123b56a09 chore/upgrade_deps (#25873) 2025-12-15 17:04:17 +00:00
Dhairyashil Shinde 12e07f20d4 feat: Add Holidays feature to block availability on public holidays (#25561)
* feat: add holidays feature for automatic availability blocking- Add UserHolidaySettings model for storing user preferences- Generate static holiday data for 20 countries using date-holidays- Create HolidayService for runtime holiday queries- Add TRPC router with endpoints for country selection and holiday toggles- Create Holidays tab UI in Availability page with conflict warnings- Integrate holiday blocking into getUserAvailability calculation- Show holiday indicator on blocked dates in booker page- Add warning in OOO modal when dates overlap with holidays

* feat: add optimizations, tests, and code quality improvements

- Add memoization/caching to HolidayService for better performance
- Optimize checkConflicts DB query with OR conditions for specific dates
- Add HolidayService unit tests (10 tests)
- Add error handling with Alert component for failed queries
- Memoize HolidayListItem component to prevent unnecessary re-renders
- Extract magic numbers into constants.ts
- Use TRPCError consistently in handlers
- Add missing i18n keys for error messages
- Update handlers to follow Cal.com patterns (default exports, minimal comments)
- Add regeneration instructions in constants

* refactor: replace static JSON with Google Calendar API integration

- Add GoogleHolidayService to fetch holidays from Google Calendar public calendars
- Add HolidayCache Prisma model for caching API responses
- Add GOOGLE_CALENDAR_API_KEY and HOLIDAY_CACHE_DAYS env variables
- Support 38 countries via Google Calendar holiday calendars
- Update HolidayService methods to async with database caching
- Update all TRPC handlers for async holiday methods
- Fix UI to display holiday dates correctly
- Remove static holidays.json and generate script

* use we instead of calcom in i18n message

* address cubics comments

* move holidays from availability to ooo

* public holidays filter for holidays

* follow i18n _one and _other pattern

* remove holiday feature flag

* revert lint command code change

* revert lint command code change 2.0

* revert lint command code change 3.0

* bye bye my christmas emoji :crying-emoji

* remove comments

* refactor(holidays): add repository pattern, split services, and add tests

- Create HolidayRepository for database operations
- Split GoogleHolidayService into GoogleCalendarClient and HolidayCacheService
- Add dependency injection to HolidayService and HolidayCacheService
- Update TRPC handlers to use HolidayRepository
- Add tests for HolidayRepository and calculateHolidayBlockedDates
- Update calendar IDs to use official holiday format (244 countries + religions)

* fix: address PR review feedback

- Remove unused date-holidays package
- Add pluralization for and_more_holidays_with_conflicts translation
- DRY: spread GOOGLE_RELIGIOUS_HOLIDAY_CALENDARS into GOOGLE_HOLIDAY_CALENDARS
- Add select to userHolidaySettings query in getUserAvailability
- Optimize checkConflicts with pre-computed timestamps

* refactor(holidays): apply proxy pattern and move logic to service

- Rename HolidayCacheService to HolidayServiceCachingProxy (proxy pattern)
- Remove HOLIDAY_CACHE_DAYS env var, use constant directly
- Add isSupportedCountry() method to HolidayService
- Add getUserSettings() and updateSettings() to HolidayService
- Move toggleHoliday logic from handler to service
- Move checkConflicts logic from handler to service
- Add findBookingsInDateRanges() to HolidayRepository
- Simplify all handlers to just call service methods

* feat(bookings): add backend validation to prevent booking on holidays

Adds explicit holiday conflict validation during booking creation to
handle the race condition where a host enables a holiday after a guest
selects a date but before they submit the booking.

Changes:
- Add checkHolidayConflict validation with HolidayRepository integration
- Integrate ensureNoHolidayConflict in RegularBookingService
- Add BookingOnHoliday error code with proper HTTP 400 response
- Handle holiday error display in BookEventForm with name interpolation
- Hide trace ID for expected validation errors
- Add unit tests for holiday conflict validation

* fix failing type check

* fix: address PR review comments for holiday feature

- Change error code from BAD_REQUEST to INTERNAL_SERVER_ERROR in
  toggleHoliday handler (errors are internal failures, not bad input)
- Refactor ensureNoHolidayConflict to use Promise.all for parallel
  user checking instead of sequential loop

* refactor: use Promise.all with logging in loop for holiday check

- Check all users in parallel using Promise.all
- Log conflicts inside the loop as they are detected
- Wait for all checks to complete before throwing error

* fix(holidays): use host timezone for holiday conflict checks

The holiday feature was checking booking dates against holidays using
server/local timezone instead of the host's timezone. This caused
bookings near midnight boundaries to incorrectly pass or fail the
holiday check.

Example: A booking at Dec 24th 8PM UTC (which is Dec 25th in IST)
was not being blocked for an Indian host with Christmas as a holiday.

Changes:
- Add .utc() to holiday date formatting for consistency
- Fetch host's timezone in checkHolidayConflict
- Convert booking time to host's timezone before comparison
- Add findUserSettingsWithTimezone to HolidayRepository
- Update error message to clarify it's the host's local time
- Add timezone edge case tests

* fix(holidays): align holiday blocking with OOO pattern for consistent timezone handling

- Simplify calculateHolidayBlockedDates to match OOO pattern using dayjs.utc()
- Fix date range query to use full day bounds (startOfDay/endOfDay) so holidays
  stored at midnight UTC are correctly found during booking validation
- Remove separate checkHolidayConflict booking-time validation - holidays now
  block through oooExcludedDateRanges like OOO does
- Remove getHolidayOnDate from HolidayService (no longer needed)
- Remove findUserSettingsWithTimezone from HolidayRepository (no longer needed)
- Clean up related tests

Holiday blocking now works exactly like OOO:
1. Holidays are added to datesOutOfOffice in calculateHolidayBlockedDates
2. buildDateRanges processes them via processOOO with .tz(timeZone, true)
3. oooExcludedDateRanges excludes those dates from availability
4. ensureAvailableUsers uses oooExcludedDateRanges to block bookings

This ensures consistent timezone handling where Dec 25th blocks all hours
of Dec 25th in the host's timezone, regardless of booker's timezone.

* update test

* update .env.example file
2025-12-15 16:39:10 +00:00
Carina WollendorferandCarinaWolli 18415e35a7 fix browser extension redirect (#25885)
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2025-12-15 16:32:59 +00:00
Udit Takkar 856792e1e7 fix: slots ooo bug (#25878) 2025-12-15 16:19:11 +00:00
52d5261b51 feat(booking): implement cross-page/week navigation in booking details sheet with view persistence (#25545)
* display UTM parameters

* persist view (list | calendar) in localStorage

* move to next page on clicking "next" of last item in the page

improve navigation

^ Conflicts:
^	apps/web/modules/bookings/components/BookingCalendarContainer.tsx

* fix navigation on calendar view

* Delete apps/web/modules/bookings/NAVIGATION_IMPLEMENTATION.md

* avoid page size being 0

* check feature flag on user level

* use map to improve useBookingListData

* address feedback

* feat(bookings): add smart navigation for calendar view

- Add sort option to tRPC bookings.get schema and handler
- Create NAVIGATION_PROBE_WINDOW_MONTHS constant (3 months)
- Create useNearestFutureBooking hook to find nearest future booking
- Create useNearestPastBooking hook to find nearest past booking
- Update useCalendarNavigationCapabilities to use probe results
- Update BookingCalendarContainer to wire up probe hooks

This enables the booking details sheet to:
- Disable next/prev buttons when no bookings exist in that direction
- Jump directly to the week containing the nearest booking

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

* fix type error

* feat: add booking selection state when using slideover (#25637)

* implement booking selection when using slideover

* remove pixel shift

* fix

* auto scroll to selected event on calendar

* make DateValues header sticky when scrolling

---------

Co-authored-by: Eunjae Lee <hey@eunjae.dev>

* prefetch previous / next weeks on calendar view

* clean up classes

* handle "fetched & but no data" situation more correctly in useCalendarAutoSelector

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
2025-12-15 16:04:00 +00:00
Morgan 53776d28e6 fix: atoms vite config (#25883)
* fix: atoms vite config

* fixup! fix: atoms vite config

* fixup! fixup! fix: atoms vite config
2025-12-15 12:31:31 -03:00
Volnei Munhoz 2b666f3e91 Fix CI for Companion (#25886) 2025-12-15 15:22:35 +00:00
Anik Dhabal Babu 7562ad2a16 refactor: Fix N+1 queries and optimize database operations (#25813)
* refactor: prisma N+1 Queries

* addressed review
2025-12-15 14:14:19 +00:00
Volnei Munhoz 5626bceeff fix companion CI (#25881) 2025-12-15 11:00:50 -03:00
Dhairyashil Shinde e312d1c044 feat: add gradient indicator for scrollable event descriptions (#25460)
* feat: add gradient indicator for scrollable event descriptions

- Create EventDescription component with dynamic gradient overlay
- Show gradient only when description content overflows (180px max-height)
- Use Tailwind v4 gradient utilities for optimal styling
- Replace inline description rendering in EventMeta with new component
- Minimal implementation: 28 lines, no useEffect, single state variable

* add top gradient and optimize ScrollableWithGradients component

* add top gradient and optimize ScrollableWithGradients component

* refactor: extract reusable ScrollableWithGradients component with top/bottom gradients

* adjust gradient fades
2025-12-15 14:14:28 +01:00
Dhairyashil ShindeandAnik Dhabal Babu 9050f9b61f fix: dynamic group organizer order (#25474)
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-12-15 11:28:45 +00:00
2218a45d83 feat: extract core booking audit infrastructure from PR 25125 (#25729)
* feat: extract core booking audit infrastructure from PR 25125

This PR contains only the core booking audit infrastructure changes from PR 25125,
excluding integration changes with booking flows.

Included:
- All packages/features/booking-audit/* (core audit services, actions, repository)
- packages/features/di/containers/BookingAuditViewerService.container.ts
- packages/features/tasker/tasker.ts (audit task types)
- packages/features/bookings/lib/types/actor.ts (actor types for audit)
- packages/features/bookings/repositories/BookingRepository.ts (getFromRescheduleUid method)
- apps/web/modules/booking/logs/views/booking-logs-view.tsx (UI for viewing audit logs)
- apps/web/public/static/locales/en/common.json (translations)

Excluded (integration changes):
- packages/trpc/server/* (tRPC handlers)
- packages/features/ee/round-robin/* (round-robin integration)
- packages/features/bookings/lib/handleCancelBooking.ts
- packages/features/bookings/lib/handleConfirmation.ts
- packages/features/bookings/lib/onBookingEvents/BookingEventHandlerService.ts
- packages/features/bookings/lib/service/RegularBookingService.ts
- apps/api/v2/* (API v2 integration)

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

* fix: make booking audit interfaces backwards-compatible with main

- Add queueAudit method back to BookingAuditProducerService interface for backwards compatibility
- Implement queueAudit method in BookingAuditTaskerProducerService
- Make userTimeZone parameter optional in BookingAuditViewerService
- Add BookingAuditTaskProducerActionData type for legacy queueAudit method
- Use any generics in BookingAuditActionServiceRegistry (matching PR 25125)
- Fix type assertions in BookingAuditTaskConsumer

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

* fix switch eslint and ts

* feat: enhance BookingAuditViewerService with logging and type improvements

- Added ISimpleLogger dependency to BookingAuditViewerService for better error handling.
- Updated actor type in enriched audit logs to use AuditActorType for improved type safety.
- Replaced console.error with logger for error reporting when no rescheduled log is found.

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-12-15 10:51:30 +00:00
Udit Takkar 4e1d05a7e7 feat: dist tracing 4 (#25574)
* feat: distributed tracing 2

* feat: distributed tracing 2

* refactor: feedback

* refactor: feedback

* fix: type error

* fix: trpc error

* feat: distributed tracing - 3

* chore: translation

* refactor: improvements

* fix: feedback

* chore: remove

* feat: dist tracing 4

* fix: type errors

* fix: type errors

* fix: remove string type

* fix: type errors
2025-12-15 10:43:22 +00:00
devin-ai-integration[bot]andlauris@cal.com 0d4108dd69 chore: bump @calcom/atoms version to 2.1.0 (#25831)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: lauris@cal.com <lauris@cal.com>
2025-12-15 09:26:47 +00:00
Dhairyashil Shinde 6e2e826001 fix(ooo): make show note publicly consistent across all booking views (#25827)
- Update weekly view to display OOO when showNotePublicly is true
- Update column view to include days with public notes in schedule
- Add notes and showNotePublicly props to weekly view calendar
- Disable show note publicly checkbox when notes field is empty
2025-12-15 10:24:10 +01:00
Anik Dhabal Babu 84a4dd4147 fix: one integration test flake (#25832) 2025-12-15 09:09:01 +00:00
Benny JooandVolnei Munhoz deca7ce40a refactor: move calAIPhone-specific repositories to features from lib (#25840)
* add prisma agent repository to features

* add

* wip

* wip

* wip

* Update apps/web/app/api/webhooks/retell-ai/route.ts

Co-authored-by: Volnei Munhoz <volnei@cal.com>

* ts fix

* ts fix

---------

Co-authored-by: Volnei Munhoz <volnei@cal.com>
2025-12-15 13:43:24 +05:30
5394d80969 chore: Cleanup some outdated pages files (#25600)
* chore: Cleanup some outdated pages files

* revert: endpoint

* revert: endpoint

---------

Co-authored-by: Udit Takkar <udit222001@gmail.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-12-15 09:16:59 +05:30
Udit Takkar fd8f2a9ff6 fix: checkout session completed (#25767)
* fix: checkout session completed

* refactor: code quality
2025-12-15 09:12:13 +05:30
Alex van Andel 28f9c8f4cf chore: release v5.9.15
Post release / release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
2025-12-15 00:14:28 +00:00
Volnei Munhoz 37884d26e3 chore: bump next versions (#25864) 2025-12-15 00:13:42 +00:00
Peer Richelsen e46df92492 small wxt related fixes (#25866) 2025-12-14 21:01:08 +01:00
Beto 35cf827cb1 feat(companion): Event types screen update (#25847) 2025-12-14 20:59:48 +01:00
Beto e9c3d7e40c feat: upgrade to sdk 55 canary (#25810) 2025-12-14 20:15:40 +01:00
Dhairyashil Shinde c218a0afad feat(companion): Add caching, redesign ui, and refactor code (#25654) 2025-12-14 14:53:38 +00:00
Keith Williams b9a09117e3 chore: Remove team-labels action (#25862) 2025-12-14 14:31:13 +00:00
an_ifrah24 550caa6665 fix: added conditional check for the unkey logger to reduce the number of logs (#25858) 2025-12-14 12:35:57 +00:00
Benny Joo a8f43da472 refactor: Move Users Admin TRPC router from features package to trpc layer (#25816)
* move users admin router to trpc package

* users admin router

* update import path

* fix
2025-12-14 08:45:20 -03:00
43b6c63294 refactor: Move insights trpc router from features package to trpc layer (#25778)
* update imports

* move trpc router from features to trpc

* update imports

* wip

* update imports

* wip

* wip

* wip

* fix import

* create objectToCsv.ts

* rename

* fix: restore proper types and static imports in insights handlers

- Add proper type definitions for all handler options instead of using 'any'
- Restore static imports for PermissionCheckService and MembershipRole
- Remove dynamic imports that were introduced during refactoring

This ensures the refactoring is pure with no behavioral changes.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: update getEventTypeList import path after utils.ts deletion

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* remove handlers

* fix

* refactor

* wip

* rm

* wip

* select only needed + fix type error

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Eunjae Lee <hey@eunjae.dev>
2025-12-14 08:44:36 -03:00
Benny Joo 9ef650ceed refactor: Move OrganizationOnboardingRepository from lib to /features/organizations (#25854)
* mv organization onboarding repository

* update imports
2025-12-14 08:42:21 -03:00
Benny Joo e394a03365 refactor: create DestinationCalendarRepository in /features/calendars (#25851)
* mv destination calendar repo

* fix
2025-12-14 08:41:13 -03:00
Benny Joo 972f983824 refactor: create PrismaOOORepository in /features/ooo (#25850)
* move to features

* update imports
2025-12-14 08:39:58 -03:00
sean-brydon 68a8fade89 add tests (#25566) 2025-12-14 19:14:15 +09:00
Benny Joo d81993892a refactor: create HostRepository in /features/host (#25842)
* mv test

* mv host repository

* update imports
2025-12-13 11:04:57 +00:00
Eesh MidhaandUdit Takkar d034e7aff7 fix: enforce team-only access on premium toggles in cal video (#25680) (#25681)
* fix(cal-video): enforce team-only access on premium toggles

* fix(cal-video): disable redirect URL field and add upgrade badge for non-team users

* chore: improvments

---------

Co-authored-by: Udit Takkar <udit222001@gmail.com>
2025-12-12 21:04:30 +00:00
sean-brydon 13103c0881 feat: Improve error handling in ratelimit (#25223)
* Improve error handling in ratelimit

* Update route.ts

* Update route.ts

* Update route.ts

* address feedback
2025-12-12 20:39:23 +00:00
Dhairyashil Shinde 983af06787 fix: allow two dots in exclude email (#24968)
* add test and fix two dots bug in exclude email

* add test and fix two dots bug in exclude email
2025-12-13 02:06:42 +05:30
Benny Joo 29076d681b refactor: create CalVideoSettingsRepository in features package (#25841)
* add new repo

* wip
2025-12-12 19:53:28 +00:00
3cadf105d5 feat: add skipContactCreation toggle to EventTypeAppCard component (#25756)
Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-12-12 18:55:19 +00:00
Peer Richelsen 411483a447 added OAuth badges (#25830) 2025-12-12 17:11:21 +00:00
Kartik Labhshetwar 223c967f81 style: add spacing and rounded corners to toolbar dropdown items (#25829) 2025-12-12 15:59:24 +00:00
Carina WollendorferandCarinaWolli 440b69138e treat web version as extension (#25834)
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2025-12-12 15:05:33 +00:00
5a3f15357c fix: filter slots by requested date range to prevent date override leakage (#25822)
* fix: filter slots by requested date range to prevent date override leakage

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

* refactor: move filterSlotsByRequestedDateRange to private method

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-12 11:28:07 -03:00
Anik Dhabal Babu e46c1bb40c fix delete payment app (#25801) 2025-12-12 14:24:45 +00:00
Anik Dhabal Babu 758b820a92 fix: slugified eventype slug (#25791) 2025-12-12 14:02:00 +00:00
sean-brydon b46fb82695 feat: minium reschedule notice on events (#25575)
* wip

* add i18n and essential tests

* fix UI and add migration

* fixes

* add logic on book event

* restore comment

* remove dev debug box

* extract min reschedule notice to util

* one more replace

* add to disable reschedule component

* tidy up state

* restore lock

* restore file

* fix zod utils

* respond to cubic feedback

* fix type error

* unit tests

* add zod util

* build tests with nul minReshceuldeNotice

* fix stuff
2025-12-12 10:53:01 -03:00
Alex van Andel 71c9567169 fix: Lazy loaded Stripe proxy to avoid crash on BillingService instantiation (#25400) 2025-12-12 19:18:06 +05:30
Hariom BalharaandDevin AI 5918e66cc5 docs: link embed events to help center to avoid duplicate maintenance (#25811)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-12 13:41:15 +00:00
2ad24048b6 fix: use relative redirects in booking confirmation routes to fix localhost redirect issue (#25794)
* fix: use relative redirects in booking confirmation routes to fix localhost redirect issue

When Cal.com runs behind a reverse proxy, request.url may return the internal
server URL (localhost:3000) instead of the external URL. This causes users to
be redirected to localhost after confirming bookings via email links.

This fix changes the redirect URLs from using url.origin (which could be
localhost) to using relative URLs via new URL(path, request.url). This ensures
the browser resolves the redirect against whatever domain the user actually
requested, fixing the issue for self-hosted deployments behind proxies.

Fixes #20358

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* test: add tests for booking confirmation redirect URL construction

Add unit tests for verify-booking-token and link API routes to ensure:
- Redirect URLs preserve the request origin (not hardcoded localhost)
- Redirect URLs use the correct booking path (/booking/{uid})
- Error messages are properly encoded in query params
- POST handler returns correct 303 status code

These tests verify the fix for #20358 where users were redirected to
localhost:3000 instead of the proper production URL after confirming
bookings via email links.

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* fix: add second argument to GET/POST calls in test files to fix type errors

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-12 19:02:54 +05:30
Lauris SkraucisandPallav a69fe2ed00 docs: how to fetch managed event type slots (#24977)
Co-authored-by: Pallav <90088723+Pallava-Joshi@users.noreply.github.com>
2025-12-12 14:12:59 +02:00
sean-brydon a5000cb3b7 fix not found nc command (#25823) 2025-12-12 12:05:01 +00:00
Anik Dhabal Babu eb0cf10f67 fix: webhook template (#25783) 2025-12-12 11:55:09 +00:00
Eunjae Lee 728e1173cb chore: update AGENTS.md on running unit tests for specific test name (#25820) 2025-12-12 11:48:30 +00:00
Lauris Skraucis b4e773da69 chore: atoms rrHostSubsetIds changelog for release (#25819) 2025-12-12 10:49:19 +00:00
Hariom BalharaandDevin AI bf38eb8cb1 refactor: Use sessionStorage instead of localStorage for decoy booking data (#24450)
* feat: Add async spam check integration and decoy booking response

- Integrate SpamCheckService with handleNewBooking workflow
- Implement parallel spam check execution for minimal performance impact
- Add decoy booking response with localStorage-based success page
- Extract organization ID from event type for org-specific blocking
- Add comprehensive test coverage for spam detection scenarios
- Create reusable components for booking success cards
- Implement fail-open behavior to never block legitimate bookings

This builds on the spam blocker DI infrastructure from PR #24040 by
adding the actual integration into the booking flow and implementing
the decoy response mechanism to avoid revealing spam detection to
malicious actors.

Related: #24040
Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Do checks in paralle

* Fix leaking host name in title

* Reduce expoiry time localstorage

* refactor: Use sessionStorage instead of localStorage for decoy booking data

- Replace localStorage with sessionStorage for automatic expiration on tab close
- Remove timestamp tracking and TTL logic (no longer needed)
- Improve privacy by auto-clearing data when browser tab/window closes
- Update documentation to reflect sessionStorage behavior

This change addresses privacy concerns by ensuring decoy booking data
(including attendee email) is automatically removed when the user closes
the tab, rather than persisting for 5 minutes or requiring manual cleanup.

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

* feat: Add sessionStorage wrapper to webstorage module

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

* Reset RegularBookingService.ts to main's version exactly

* feat: Add 5-minute expiration timeout to decoy booking data

- Adds timestamp to DecoyBookingData interface
- Checks expiration when retrieving booking data
- Automatically removes expired data from sessionStorage
- Provides defense-in-depth against potential misuse
- Works alongside sessionStorage auto-clear on tab close

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-12 07:42:44 -03:00
Hariom Balhara 010ee0d066 add-tests- usePrefetch (#23918) 2025-12-12 07:39:57 -03:00
sean-brydon f0a7d69c7e fix (#25818) 2025-12-12 10:26:56 +00:00
Anik Dhabal Babu cb2509683d fix: unit test flake (#25780) 2025-12-12 10:28:29 +05:30
Alex van Andel e2ac05e82f chore: release v5.9.14
Post release / release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
2025-12-12 00:52:39 +00:00
Volnei Munhoz 34ab02702e fix react version (#25809) 2025-12-12 06:15:25 +05:30
Pasquale Vitiello 1da118a534 chore: update Next.js (#25807) 2025-12-12 00:42:45 +00:00
Kartik LabhshetwarandDhairyashil acf2f53daf fix: hide insights submenu for free users (#25754)
* fix: hide insights submenu for free users

* fix: allow navigation access while plan pending

* refactor: update upgrade link to insights in navigation

* fix: addressed all the issues

* fix: prevent flash of premium features for free users during loading

Change from optimistic to pessimistic loading so free users don't
briefly see the Insights submenu while plan status is being fetched.

---------

Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>
2025-12-11 21:04:13 +00:00
Kartik LabhshetwarandUdit Takkar c7bb28d64c fix: show hidden badge on mobile view for event types (#25701)
* fix: show hidden badge on mobile view for event types

* fix: update event type hidden toggle in infinite list

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-12-11 20:31:51 +00:00
Kartik Labhshetwarandcubic-dev-ai[bot] 8dc8d87ad0 feat: add time shift badge for recurring events with shifted local times (#25568)
* feat: highlight recurring bookings with time shift badge across DST

* Update packages/lib/__tests__/timeShift.test.ts

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

* refactor: show time shift badge only on first shift in bookings view and occurrences

* refactor: update recurring bookings display logic and wrap booking title text

* refactor: add getFirstShiftFlags helper for time shift flags and update components

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-12-11 20:18:00 +00:00
Udit Takkar da4fec9c27 chore: add missing translation (#25753) 2025-12-12 01:45:43 +05:30
Hariom BalharaandDevin AI 0ecfd78e47 fix: Update timeZoneSchema to handle +00:00 timezone case and maintain IANA compliance (#25776)
* fix: Update timeZoneSchema to handle +00:00 timezone case and maintain IANA compliance

* fix: Use superRefine to properly handle +00:00 timezone and transform to UTC

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

* feat: Add logging for non-IANA timezone cases

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

* refactor: Simplify timeZoneSchema to use .refine() instead of superRefine

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

* chore: Remove warn log for +00:00 timezone to avoid spam

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

* chore: Remove logger from timeZone schema

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-11 19:46:13 +00:00
Udit Takkar f007fe8407 feat: system admin blocklist backend (#25077)
* feat: admin blocklist backend

* chore:

* refactor: use DI

* fix: tests

* refactor; improve error

* refactor; improve error

* perf: use bulk

* chore: some more

* refactor: feedback

* test: update test

* refactor: improvements

* refactor: improvements

* fix: remove

* refactor: move to service

* refactor: move to service

* chore: add logs

* refactor: remove default
2025-12-11 19:41:29 +00:00
Kartik LabhshetwarandDhairyashil e1324bd9c3 fix(settings): improve spacing between navigation child items (#25631)
* fix(settings): improve spacing between navigation child items

* chore: removing prettier formatting

* style: update dropdown item class names for consistent rounding

* style: add spacing and hover margin to navigation items

* style: add hover margin top to navigation item

* apply same ui changes for team profile menu

---------

Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>
2025-12-11 19:09:32 +00:00
Alex van Andel ca152d73f2 chore: release v5.9.13
Post release / release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
2025-12-11 12:44:04 +00:00
Hariom Balhara 6f0c09d2be feat: add booker lifecycle SDK events for embed tracking (#25569)
* feat: add embed prerendering support and enhance event handling

- Introduced `useIsEmbedPrerendering` hook to determine if the embed is in prerender mode.
- Updated `useAvailabilityEvents` to prevent firing events during prerendering.
- Added `bookerLoadedEvent` and `availabilityRefreshed` types to `EventDataMap`.
- Implemented `useFirebookerLoadedEvent` to manage firing the booker loaded event conditionally.
- Refactored event firing logic in `useSchedule` and `BookerWebWrapper` components to utilize new hooks.

* feat: add embed prerendering support and enhance event handling

- Introduced `useIsEmbedPrerendering` hook to determine if the embed is in prerender mode.
- Updated `useAvailabilityEvents` to prevent firing events during prerendering.
- Added `bookerLoadedEvent` and `availabilityRefreshed` types to `EventDataMap`.
- Implemented `useFirebookerLoadedEvent` to manage firing the booker loaded event conditionally.
- Refactored event firing logic in `useSchedule` and `BookerWebWrapper` components to utilize new hooks.

* feat: enhance embed event handling and introduce link reopening detection

- Added `useEmbedReopened` hook to track when the embed is reopened.
- Updated `BookerWebWrapper` to reset event firing state upon embed reopening.
- Refactored event firing logic to use `bookerViewed` instead of `bookerLoadedEvent`.
- Introduced scheduling for event firing in `useSchedule` to ensure correct order of events during prerendering.

* feat: add lifecycle diagrams for inline and modal embeds

- Introduced `inline-embed-lifecycle.mermaid` and `modal-embed-lifecycle.mermaid` files to visualize the lifecycle events and states of inline and modal embeds.
- Updated `LIFECYCLE.md` to reference the new diagrams and provide a clearer explanation of the embed lifecycle processes.
- Added `modal-prerendering-flow.mermaid` to illustrate the prerendering flow for modal embeds.
- Enhanced the routing playground with new features and improved event handling for availability and booking events.

* refactor: update event handling for booker lifecycle events

- Replaced `availabilityLoaded` event with `bookerReady` to better reflect the state when the booker view is fully loaded and ready for interaction.
- Updated related documentation and diagrams to reflect changes in event triggers and descriptions.
- Adjusted internal state management to track `viewId` instead of `reopenCount` for distinguishing between initial views and reopens.
- Added tests for new event handling logic to ensure correct firing of `bookerViewed`, `bookerReopened`, and `bookerReady` events.

* refactor: enhance embed event handling and state management

- Updated event handling for booker lifecycle events, replacing `resetViewVariables` with `resetPageData` to manage page-specific state.
- Introduced new utility functions for managing event firing states and reload initiation.
- Refactored `fireBookerViewedEvent` and `fireBookerReadyEvent` to utilize the new state management functions.
- Added comprehensive tests for the updated event handling logic and state resets to ensure correct functionality across various scenarios.

* refactor: update embed iframe configuration and utility functions

- Reduced `slotsStaleTimeMs` from 30 seconds to 10 seconds and `iframeForceReloadThresholdMs` from 100 seconds to 30 seconds for improved responsiveness.
- Refactored utility functions to use `isBrowser` for client-side checks instead of `isClientSide`.
- Removed unused `isPrerendering` function and updated related documentation for clarity.
- Enhanced event handling by exporting `useBookerEmbedEvents` from the appropriate module for better accessibility.

* refactor: update embed iframe configuration and utility functions

- Reduced `slotsStaleTimeMs` from 30 seconds to 10 seconds and `iframeForceReloadThresholdMs` from 100 seconds to 30 seconds for improved responsiveness.
- Refactored utility functions to use `isBrowser` for client-side checks instead of `isClientSide`.
- Removed unused `isPrerendering` function and updated related documentation for clarity.
- Enhanced event handling by exporting `useBookerEmbedEvents` from the appropriate module for better accessibility.

* fix cubic feedback
2025-12-11 09:11:38 -03:00
Dhairyashil Shinde f6642c17f8 feat: optimize getLuckyUser to skip data fetching for single user (#25337)
- Add early return when only one user is available
- Prevents unnecessary database queries, calendar API calls, and OOO checks
- Add comprehensive test to verify optimization works correctly

Fixes #19503 [CAL-5212]
2025-12-11 08:50:57 -03:00
Dhairyashil Shinde 26b4385679 feat: Add public OOO notes display on booking pages (#25471)
* feat: ooo message on booking page

* make ooo days selectable even when no redirect booking

* handle long notes

* remove unused i18n key

* Private notes stay private on the server, No accidental data leaks through client-side payloads

* address cubics comments

* fix: replace toggle with checkbox for OOO note visibility

- Replace Switch with Checkbox for "show note publicly" option
- Remove "OOO Message:" prefix from displayed notes on booking page
- Update i18n text to "Show note on public booking page"
- Remove unused ooo_message i18n key

* fix the accessibility issue by using proper htmlFor and id association

* only allow selecting OOO dates when the note is public
2025-12-11 11:31:59 +00:00
Dhairyashil Shinde b220420630 fix: reset Cloudflare Turnstile token on signup errors (#24927)
* fix: cloudflare turnstile token reset

* fix: silently reset turnstile on invalid token error

* refactor: remove unused forwardRef logic from Turnstile component

- Remove forwardRef, useImperativeHandle, and useRef imports
- Remove unused TurnstileInstance type export
- Simplify to a plain function component
- The ref-based reset was replaced by key-based remount in signup-view

* refactor: remove redundant cfToken validation check

The submit button is already disabled when cfToken is missing,
making this defensive check unreachable during normal form flow.

* revert prettier formatiing

* chore: revert yarn.lock changes

* refactor(auth): use shared constant for cloudflare token error message

Replace hardcoded "Invalid cloudflare token" string with an exported
constant to prevent silent breakage if the error message changes.
2025-12-11 16:45:01 +05:30
Morgan 7d5e9a4e0e chore: hide rrHostSubsetIds and rrHostSubsetEnabled from api docs for now (#25769) 2025-12-11 11:12:10 +00:00
Rajiv Sahal 5253f26c94 fix: css for checkbox in light mode (#25782) 2025-12-11 10:48:59 +00:00
sean-brydon 9b09544c62 fix: try submit instead of form manual submition (#25789)
* try submit

* add toaster and logs
2025-12-11 10:35:09 +00:00
44104e1ba4 feat: gated features modal (#25296)
* feat: Modal for gated features

* use zustand

* refactor

* Apply suggestions from code review

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

* Update packages/ui/components/card/Card.tsx

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

* dismiss button fix and url fix

* fix: broken redirect to teams

* fix: type check and review comments

* add learn more tracking back

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-12-11 11:14:31 +01:00
Kartik Labhshetwar 191dcc45b5 style: add mb-2 to workflows page flex container (#25787) 2025-12-11 10:07:31 +00:00
Benny Joo 5de8576473 remove duplicate code for buildBaseWhereCondition (#25779) 2025-12-11 08:25:19 +00:00
Udit Takkar 6440c60c96 fix: use safeStringify (#25766) 2025-12-11 07:27:33 +00:00
Alex van Andel 016ae6ea4b fix: Add orgSlug to slots.getSchedule call (#25397)
* fix: Add orgSlug to slots.getSchedule call

* Don't pass null if orgSlug is missing
2025-12-11 16:10:40 +09:00
AbhishekandDhairyashil Shinde d3f7308b9f fix(validation): disallow whitespace-only team name (#25467)
* fix(validation): disallow whitespace-only team name

* fix validation at team profile

* fix validation for title at event type

---------

Co-authored-by: Dhairyashil Shinde <93669429+dhairyashiil@users.noreply.github.com>
2025-12-11 07:09:05 +00:00
Anik Dhabal Babu 060176cd08 Fix: Hide team members in social preview when team is private (#25770) 2025-12-11 04:17:56 +00:00
Dhairyashil Shindeandcubic-dev-ai[bot] a306a77678 feat: Include booking question response in csv file from insights page (#25454)
* feat: booking-question-phone-csv-insights-page

* feat: Include booking question responses in insights CSV download (#25453)

- Add custom question responses to CSV export
- Parse booking responses and eventType bookingFields
- Filter out system fields (email, name, etc.)
- Map field names to display labels
- Add dynamic columns for each custom question

Performance optimizations:
- Cache parsed bookingFields by eventTypeId (99% fewer parsing operations)
- Use Map for O(1) field label lookups (100x faster than array.find)
- Single-pass data processing (75% fewer iterations)
- Optimized attendee processing (67% reduction in loops)
- Reduced memory allocations (3x less memory usage)

Estimated 3-5x performance improvement for large datasets

* refactor: Remove optimization-related comments, keep code flow comments

* fix: Include attendee phone numbers in CSV export

- Add phoneNumber field to attendees and seatsReferences query
- Collect phone numbers from attendees during processing
- Add attendeePhone1, attendeePhone2, etc. columns to CSV output
- Fixes missing attendee phone numbers in insights CSV download

* fix: Handle falsy values correctly in custom responses

Previously, falsy values like 0 or false were incorrectly skipped
because !answer treats them as empty. This caused issues with:
- Numeric answers: 0, -1, etc.
- Boolean answers: false
- Empty strings: '' (intentionally skipped)

Now explicitly check for null, undefined, empty arrays, and empty strings
while allowing legitimate falsy values (0, false) to pass through.

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

* feat(insights): add phone numbers to CSV export

- Add attendeePhone1, attendeePhone2, etc. columns with fallback to booking responses
- Add columns for custom phone-type booking questions
- Exclude system phone fields (attendeePhoneNumber, smsReminderNumber) from duplicate columns

* fix: address PR review comments

- Move SYSTEM_PHONE_FIELDS constant to packages/lib/bookings/SystemField.ts
- Restore comments

---------

Co-authored-by: cubic-dev-ai[bot] <cubic-dev-ai[bot]@users.noreply.github.com>
2025-12-10 14:51:09 +00:00
Eunjae Lee 3986d61f40 feat(bookings): improve bookings redesign (#25251)
* use booking.uid instead of booking.id for url param

* show timezone on calendar

* fix type

* restore horizontal tab and remove header and subtitle

* clean up sidebar items

* fix event propagation from attendees

* fetch all statuses except for cancelled on calendar view

* clean up styles of the badges on BookingListItem

* fix useMediaQuery

* add close button to the header

* add assignment reason to the details sheet

* use separator row

* use ToggleGroup for the top bookings tab

* move ViewToggleButton

* resize the action button

* remove wrong prop

* fix type error

* fix type error

* hide view toggle button on mobile (and fix the breakpoint)

* remove unused e2e tests

* fix e2e tests

* hide toggle button when feature flag is off

* update skeleton

* improve attendees on booking list item and slide over

* improve attendee dropdown

* fix type error

* move query to containers

* select attendee email

* infinite fetching for calendar view

* update styles

* fix compatibility

* fix: add backward compatibility for status field in getAllUserBookings

* increase calendar height

* fix type error

* support Member filter only for admin / owners

* add debug log (TEMP)

* add event border color

* show Reject / Accept buttons on BookingDetailsSheet

* move description section to the top

* update When section

* update style of Who section

* add CancelBookingDialog WIP

* fix CancelBookingDialog

* increase clickable area

* add schedule info section WIP

* fix flaky reject button

* fixing reschedule info WIP

* add fromReschedule index to Booking

* improve rescheduled information

* improve reassignment

* fix type error

* fix unit test

* respect user's weekStart value on the booking calendar view

* update debug log

* improve payment section

* clean up

* fix log message

* reposition filters on list view

* fix bookings controller api2 e2e test

* clean up file by extracting logic into custom hooks

* rename files

* merge BookingCalendar into its container

* extract logic into separate hook files

* remove redundant logic

* rearrange items on calendar view

* add WeekPicker

* extract filter button

* responsive header on list view

* horizontal scroll for ToggleGroup WIP

* fix type error

* fix cancelling recurring event

* address feedback

* fix e2e tests

* fix unit test

* fix e2e tests

* make hover style more visible for ToggleGroup

* fix margin on CancelBookingDialog

* update styles on the slide over (mostly font weight)

* update style of CancelBookingDialog

* update styles

* update margin top for the header

* refactor getBookingDetails handler

* fix gap in who section

* auto-filter the current user on the calendar view

* calculate calendar height considering top banners

* improve booking details sheet interaction without overlay

* update calendar event styles

* update reject dialog style

* put uid first in the query params

* fix class name

* memoize functions in useMediaQuery

* query attendee with id instead of email

* update margins

* replace TRPCError with ErrorWithCode

* move calculation outside loop

* remove dead code
2025-12-10 13:40:04 +00:00
Eunjae LeeandDevin AI 41b71d845c docs: add ErrorWithCode vs TRPCError guidelines and packages/features import restrictions (#25751)
* docs: add ErrorWithCode vs TRPCError guidelines and packages/features import restrictions

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

* fix: correct ErrorWithCode syntax with proper imports and Factory pattern

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

* docs: update AGENTS.md with ErrorWithCode guidance for non-tRPC files

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

* docs: reduce duplication by linking to knowledge-base.md for error handling details

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-10 13:39:27 +00:00
sean-brydon e6bfdd9ebb fix (#25764) 2025-12-10 13:22:40 +00:00
devin-ai-integration[bot]andlauris@cal.com f4223d1657 docs: fix grammar, redundant word, and simplify OAuth client docs (#25747)
* docs: fix grammar and redundant word in managed organizations guide

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

* docs: simplify OAuth client fetching paragraphs per Pedro's feedback

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: lauris@cal.com <lauris@cal.com>
2025-12-10 17:17:23 +05:30
Volnei Munhoz b0bf0aaec2 upgrade lingo.dev (#25748) 2025-12-10 11:41:39 +00:00
e4fde4dc16 fix: Playwright user cleanup deadlock in E2E (#25677)
* fix: increase Docker build MAX_OLD_SPACE_SIZE to 8192 to fix OOM

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* fix

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-10 17:04:09 +05:30
Kartik Labhshetwar 6c21a12a88 fix(phone-input): resolve styling inconsistencies in focus states and hover effects (#25744) 2025-12-10 11:25:38 +00:00
sean-brydon 34e1122667 watch invites to ensure reactivity i (#25755) 2025-12-10 11:22:31 +00:00
6b62557a92 feat: add hostSubsetIds parameter for round robin host filtering (#25627)
* feat: add hostSubsetIds parameter for round robin host filtering

Add support for filtering round robin event type hosts via API v2.
When hostSubsetIds is provided, only the specified hosts are considered
for availability calculation and booking assignment.

Changes:
- Add hostSubsetIds to slots API input (GET /slots/available)
- Add hostSubsetIds to booking API input (POST /bookings)
- Update _findQualifiedHostsWithDelegationCredentials to filter by hostSubsetIds
- Pass hostSubsetIds through all layers: API -> tRPC -> slots/booking services

This allows API consumers to request availability and create bookings
for a subset of hosts within a round robin event type.

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

* chore: add e2e tests

* chore: add enableHostSubset team event-type setting

* fixup! chore: add enableHostSubset team event-type setting

* fix tests

* fix tests

* improve isWithinRRHostSubset

* rename to rrHost subset

* fix ai review

* fix: add booker platform wrapper rrHostSubsetIds prop

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-10 10:37:39 +00:00
300b9c916d fix: preserve metadata fields during partial event type updates (#25621)
* fix: preserve metadata fields during partial event type updates

- Fix multipleDuration (lengthInMinutesOptions) being reset to undefined on partial updates
- Fix bookerLayouts being reset to undefined on partial updates
- Fix requiresConfirmationThreshold being reset to undefined on partial updates
- Add e2e test for lengthInMinutesOptions preservation

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

* test: expand metadata preservation test to include bookerLayouts and confirmationPolicy

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-10 10:33:01 +00:00
devin-ai-integration[bot]andlauris@cal.com 5ac374374c chore: delete changeset files for atoms release (#25746)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: lauris@cal.com <lauris@cal.com>
2025-12-10 15:43:12 +05:30
Benny Joo 09a4247aa1 refactor: migrate schedule utils from TRPC to ScheduleRepository to break circular dependency (#24764)
* remove util files

* wip

* wip

* wip

* wip

* wip

* wip

* add test file

* refactors

* refactors

* fix type error

* simplify

* host repository test

* di
2025-12-10 12:01:48 +02:00
Volnei MunhozandDevin AI eb01e2f9d8 fix(companion): update react-native-reanimated to Expo 54 compatible version (#25741)
The Android build was failing with errors like:
- cannot find symbol: ReactViewBackgroundDrawable
- cannot find symbol: TRACE_TAG_REACT_JAVA_BRIDGE
- cannot find symbol: getRuntimeExecutor()
- no suitable method found for updateLayout

Root cause: react-native-reanimated ~3.10.1 is incompatible with React Native 0.81.5 (used by Expo SDK 54).

Fix: Update to Expo 54 bundled versions using 'npx expo install':
- react-native-reanimated: ~3.10.1 → ~4.1.1
- react-native-worklets: ^0.6.1 → 0.5.1

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-10 01:24:50 +00:00
Alex van Andel 20efb566b2 chore: release v5.9.12
Post release / release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
2025-12-10 01:09:32 +00:00
d9ebf26e21 chore: standarize rate limit structure (#25736)
* feat: add toggle to opt out of booking title translation in instant meetings (#25547)

* feat: add toggle to opt out of booking title translation in instant meetings

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

* fix: add autoTranslateTitleEnabled to test builder

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

* fix: respect autoTranslateTitleEnabled toggle in InstantBookingCreateService

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

* fix: fetch autoTranslateTitleEnabled directly in InstantBookingCreateService

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

* refactor: rename autoTranslateTitleEnabled to autoTranslateInstantMeetingTitleEnabled

- Renamed field to clarify it only applies to instant meeting title translation
- Moved Prisma query to EventTypeRepository.findInstantMeetingConfigById()
- Removed title translation logic from update.handler.ts (flag only controls instant meeting title)
- Updated all references across the codebase
- Added new i18n translation keys for the renamed field

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

* fix: add autoTranslateInstantMeetingTitleEnabled to test destructuring patterns

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

* fix: use Prisma.TeamCreateInput type for metadata in test helper

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

* fix: add autoTranslateInstantMeetingTitleEnabled to mockUpdatedEventType in test

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

* refactor: use generic findByIdMinimal instead of business-specific method

- Add autoTranslateInstantMeetingTitleEnabled to eventTypeSelect constant
- Remove findInstantMeetingConfigById from EventTypeRepository
- Update InstantBookingCreateService to use findByIdMinimal

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

* refactor: remove autoTranslateInstantMeetingTitleEnabled from eventTypeSelect (not needed for findByIdMinimal)

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

* feat: add autoTranslateInstantMeetingTitleEnabled to event type form defaults

- Rename shouldTranslateTitle to shouldAutoTranslateInstantMeetingTitle for clarity
- Add autoTranslateInstantMeetingTitleEnabled to findById and findByIdForOrgAdmin selects
- Add autoTranslateInstantMeetingTitleEnabled to useEventTypeForm defaultValues

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

* fix: only update autoTranslateInstantMeetingTitleEnabled when explicitly provided

Fixes issue where omitting the field in update requests would overwrite
the saved opt-out setting with the default value (true). Now the field
is only included in the update payload when explicitly provided.

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* chore: Create standard for rate limits

---------

Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-10 01:04:21 +00:00
Volnei Munhoz cb13874574 Fix react version for lingo.dev (#25740) 2025-12-10 01:01:37 +00:00
Volnei Munhoz 1fa02d957e sync yarn.lock (#25737) 2025-12-09 20:19:22 +00:00
Benny JooandDevin AI 529ca159f7 refactor: remove TRPCError handling from getServerErrorFromUnknown (#25691)
* refactor: remove TRPCError handling from getServerErrorFromUnknown

This removes the @trpc/server dependency from packages/lib by removing
TRPCError handling from getServerErrorFromUnknown.ts.

packages/lib is meant to be a general utility library that other packages
depend on, so it shouldn't import tRPC. The callers that need to handle
TRPCError (like onErrorHandler.ts and defaultResponder.ts) already handle
it explicitly before calling getServerErrorFromUnknown, so this change
has no behavioral impact.

Changes:
- Remove TRPCError and getHTTPStatusCodeFromError imports
- Remove TRPCError instanceof check from getServerErrorFromUnknown
- Update docstring to note that TRPCError is not handled
- Remove TRPCError-related tests (they belong in the tRPC layer)
- Fix lint warnings in Prisma error tests (replace 'as any' with proper type)

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* wip

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-09 16:21:55 -03:00
devin-ai-integration[bot]andlauris@cal.com be12ac75b4 docs: add managed organizations documentation (#25735)
- Create docs/platform/guides/managed-orgs.mdx with guide for creating managed organizations and their OAuth clients via the API
- Add entry to docs/mint.json navigation menu in the Platform Guides section

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: lauris@cal.com <lauris@cal.com>
2025-12-09 18:49:54 +00:00
Eunjae LeeandDevin AI 68cdfd42b1 docs: add Repository + DTO pattern guidance for Prisma type isolation (#25730)
* docs: add Repository + DTO pattern guidance for Prisma type isolation

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

* docs: add 'Why this pattern?' section explaining benefits of Repository + DTO

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

* docs: condense Repository + DTO pattern guidance for readability

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-09 18:26:02 +00:00
Pedro CastroandUdit Takkar 3ebac0194e fix: block Google Meet installation without Google Calendar dependency (#25513)
* fix: block Google Meet installation without Google Calendar dependency

  - Prevent users from installing Google Meet when Google Calendar is not connected
  - Update AppDependencyComponent to show error state for unmet dependencies
  - Fix InstallAppButtonChild to respect disabled prop from dependencies check
  - Ensure consistent dependency validation across App Store and app detail pages

  Fixes #25497

* test: add unit tests for dependency validation
- Add tests for AppDependencyComponent (8 tests)
- Add tests for InstallAppButtonChild (5 tests)
- Cover dependency blocking behavior
- Test visual state changes (bg-error/bg-subtle)

* test: resolve type-check error in InstallAppButtonChild tests

- Add complete MockCredential type definition
- Create factory function to generate typed mock credentials
- Eliminate code duplication across test cases

* fix: remove redundant disabled prop assignment

Disabled state is already passed through via props.disableInstall
which gets converted to props.disabled in InstallAppButtonWithoutPlanCheck.
This change addresses the review comment to avoid unnecessary duplication

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2025-12-09 17:56:20 +00:00
Rajiv Sahal 6bdf320640 fix: dont pass any default values for new oauth client creation (#25734) 2025-12-09 16:34:59 +00:00
Lauris Skraucis cdfdce533e chore: atoms release changelog and package.json (#25733) 2025-12-09 16:28:33 +00:00
PallavandAmit Sharma 5e29a7fa2a feat: add option to ignore guests in HubSpot integration and update related schemas (#25727)
Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com>
2025-12-09 15:21:33 +00:00
Pallavandcubic-dev-ai[bot] 97377c4554 docs: updated the steps to connect hubspot (#25724)
* updated the stpes to connect the app

* chore

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

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-12-09 15:06:43 +00:00
Eunjae LeeandDevin AI acc82f808d docs: instruct to use ast-grep > ripgrep > grep for searching (#25725)
* docs: instruct to use ripgrep with grep fallback

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

* docs: update search tool preference to ast-grep > ripgrep > grep

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-09 14:13:06 +00:00
3a59cd41cc feat: add toggle to opt out of booking title translation in instant meetings (#25547)
* feat: add toggle to opt out of booking title translation in instant meetings

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

* fix: add autoTranslateTitleEnabled to test builder

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

* fix: respect autoTranslateTitleEnabled toggle in InstantBookingCreateService

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

* fix: fetch autoTranslateTitleEnabled directly in InstantBookingCreateService

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

* refactor: rename autoTranslateTitleEnabled to autoTranslateInstantMeetingTitleEnabled

- Renamed field to clarify it only applies to instant meeting title translation
- Moved Prisma query to EventTypeRepository.findInstantMeetingConfigById()
- Removed title translation logic from update.handler.ts (flag only controls instant meeting title)
- Updated all references across the codebase
- Added new i18n translation keys for the renamed field

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

* fix: add autoTranslateInstantMeetingTitleEnabled to test destructuring patterns

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

* fix: use Prisma.TeamCreateInput type for metadata in test helper

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

* fix: add autoTranslateInstantMeetingTitleEnabled to mockUpdatedEventType in test

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

* refactor: use generic findByIdMinimal instead of business-specific method

- Add autoTranslateInstantMeetingTitleEnabled to eventTypeSelect constant
- Remove findInstantMeetingConfigById from EventTypeRepository
- Update InstantBookingCreateService to use findByIdMinimal

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

* refactor: remove autoTranslateInstantMeetingTitleEnabled from eventTypeSelect (not needed for findByIdMinimal)

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

* feat: add autoTranslateInstantMeetingTitleEnabled to event type form defaults

- Rename shouldTranslateTitle to shouldAutoTranslateInstantMeetingTitle for clarity
- Add autoTranslateInstantMeetingTitleEnabled to findById and findByIdForOrgAdmin selects
- Add autoTranslateInstantMeetingTitleEnabled to useEventTypeForm defaultValues

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

* fix: only update autoTranslateInstantMeetingTitleEnabled when explicitly provided

Fixes issue where omitting the field in update requests would overwrite
the saved opt-out setting with the default value (true). Now the field
is only included in the update payload when explicitly provided.

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-09 13:51:51 +00:00
Anik Dhabal Babu 6ae2ce8ed9 fix: workflow email is not sending on form submission (#25722)
* fix: email not sending on form submission

* Remove handleCheckoutSessionExpired function

Removed the handleCheckoutSessionExpired function and its registration in webhookHandlers.
2025-12-09 13:24:41 +00:00
Anik Dhabal Babu 476460dad8 fix: Add custom payload template support for form submission webhooks (#25719)
* fix: Add custom payload template support for form submission webhooks

* delete

* Update applyTemplate function signature

Refactor applyTemplate function to accept specific data type.
2025-12-09 13:22:13 +00:00
Rajiv Sahal 19cadd18e3 fix: preserve description for event type (#25726) 2025-12-09 13:05:24 +00:00
Hariom Balhara e20cc960f1 feat: add uuid plumbing from API v2 to packages/features (#25721)
## What does this PR do?

This PR adds user UUID plumbing from API v2 controllers through to packages/features functions. This is preparatory work extracted from PR #25125 to support future audit logging functionality.

**Key changes:**
- API v2 controllers (2024-04-15, 2024-08-13) now extract and pass `userUuid` to downstream functions
- `handleMarkNoShow` and `CancelBookingInput` types now accept optional `userUuid` parameter
- `UserRepository.findUnlockedUserForSession` now selects `uuid` field
- Session middleware now includes `uuid` in the returned user object
- Fixed lint warning: changed `PromiseSettledResult<any>` to `PromiseSettledResult<unknown>`

**Refactoring (optimization):**
- Renamed `getOwnerId` → `getOwner` and `getOwnerIdRescheduledBooking` → `getOwnerRescheduledBooking`
- These methods now return `{ id: number; uuid: string } | null` instead of just `number | undefined`
- This eliminates redundant database calls by fetching user id and uuid in a single query

**Important:** This is plumbing-only - packages/features receives the `userUuid` but does not use it directly (note the `_userUuid` prefix). The actual audit logging usage will come in a follow-up PR.

Requested by: @hariombalhara (hariom@cal.com)

Link to Devin run: https://app.devin.ai/sessions/545209189f6347cd807bf1b336f9ac40

## Mandatory Tasks (DO NOT REMOVE)

- [x] I have self-reviewed the code (A decent size PR without self-review might be rejected).
- [x] I have updated the developer docs in /docs if this PR makes changes that would require a [documentation change](https://cal.com/docs). N/A - no documentation changes needed.
- [x] I confirm automated tests are in place that prove my fix is effective or that my feature works. N/A - plumbing only, existing tests cover the functionality.

## How should this be tested?

1. Run type checks: `yarn type-check:ci --force`
2. Verify the changes compile without new type errors related to uuid
3. The `userUuid` parameters are optional, so existing functionality should work unchanged

## Checklist

- [x] My code follows the style guidelines of this project
- [x] I have checked if my changes generate no new warnings

## Human Review Checklist

- [ ] Verify the `userUuid` parameter is intentionally unused (prefixed with `_userUuid`) - this is plumbing for future audit logging
- [ ] Verify all callers of `getOwner` and `getOwnerRescheduledBooking` correctly handle the new `{ id, uuid } | null` return type
- [ ] Confirm the change from `undefined` to `null` as the "not found" return value is handled consistently
- [ ] Verify the `uuid` field exists in the User model schema
2025-12-09 17:29:55 +05:30
Hariom BalharaandDevin AI f350542d0d feat: add booking audit action services for lib/actions folder (#25720)
Extract lib/actions folder changes from booking-audit-more-infra branch:
- AcceptedAuditActionService
- AttendeeAddedAuditActionService
- AttendeeNoShowUpdatedAuditActionService
- AttendeeRemovedAuditActionService
- CancelledAuditActionService
- CreatedAuditActionService (modified)
- HostNoShowUpdatedAuditActionService
- IAuditActionService (modified)
- LocationChangedAuditActionService
- ReassignmentAuditActionService
- RejectedAuditActionService
- RescheduleRequestedAuditActionService
- RescheduledAuditActionService

Also includes common/changeSchemas.ts required for type-checks to pass.

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-09 14:29:41 +05:30
Peer RichelsenandDhairyashil Shinde 257a49ce88 fix(companion): replaced localhost with prod url (#25576)
* replaced localhost with prod url

* nit

---------

Co-authored-by: Dhairyashil Shinde <93669429+dhairyashiil@users.noreply.github.com>
2025-12-09 07:47:17 +00:00
sean-brydon 75b93cebdb fix: troubleshooter team events + improve race condition (#25704)
* fix query to bring back teams + fix hover state

* fix team issues with troubleshooter
2025-12-09 07:37:21 +00:00
Anik Dhabal Babu 161ebdbbec perf: Fix N+1 queries and optimize database operations (#25630)
* perf: batch database operations and fix N+1 queries

* delete

* Fix condition for checking CalVideo location activity
2025-12-09 07:32:30 +00:00
Kartik Labhshetwar 978c5bdb95 fix(insights): align call history empty state with search (#25718) 2025-12-09 07:19:10 +00:00
Alex van Andel 895d039efc chore: release v5.9.11
Post release / release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
2025-12-09 03:08:28 +00:00
Anik Dhabal Babu 9f566bc8fc fix: orgbanner (#25706) 2025-12-08 20:35:11 +05:30
Volnei Munhoz 518e541177 chore: upgrade husky (#25698)
* bump husky version

* fix new husky version warning

* Fix husky version
2025-12-08 10:47:29 -03:00
Anik Dhabal Babu c1be922ee1 perf: Workflows are taking too long to load (#25705)
* perf: workflows are too slow

* Refactor eventTypeRepository for improved clarity

* Reintroduce ErrorCode and ErrorWithCode imports
2025-12-08 18:31:46 +05:30
Volnei Munhoz 967bba1e80 Remove coderrabit config (#25702) 2025-12-08 12:27:28 +00:00
Hariom Balhara 0fc26f782f feat: Add support to audit and view audit log with Booking CREATED action (#25468)
## What does this PR do?

This PR introduces the booking audit infrastructure with a viewer service to fetch, enrich, and format audit logs. This is the first iteration that includes only the CREATED action with versioned schema

Note: Additional audit actions, UI improvements to match with Figma will be taken care of in followup PRs, to ensure the PR size remains as small as possible(as it is large enough already)

Demo - Loom - https://www.loom.com/share/22c2f38b052b480b8be3716e1608eaf6

### Key Changes

**New Booking Audit Package** (`packages/features/booking-audit/`):

- `BookingAuditViewerService` - Fetches, enriches, and formats audit logs for display
- `BookingAuditTaskConsumer` - Processes audit tasks asynchronously via Tasker
- `CreatedAuditActionService` (v1) - Handles RECORD_CREATED action with versioned schema

**Repository Layer**:

- `BookingAuditRepository` - CRUD operations for audit records
- `AuditActorRepository` - Actor management (users, guests, system)
- `UserRepository.findByUuid()` - User lookup for actor enrichment

**UI Components**:

- New page at `/booking/logs/[bookinguid]` for viewing audit history
- Filterable audit log list with search, type, and actor filters
- Expandable log entries showing detailed change information

**Infrastructure**:

- `bookingAudit` Tasker task type for async processing
- `booking-audit` feature flag (disabled by default)
- tRPC endpoint `viewer.bookings.getAuditLogs`

### Updates since last revision

- **Refactored `Task` class to `TaskRepository`**: Converted all static methods to instance methods following the repository pattern. A singleton `Task` is exported for backward compatibility, so existing call sites continue to work unchanged.

### Important Notes for Reviewers

- **Permission check is TODO**: `checkPermissions()` in `BookingAuditViewerService` is not yet implemented
- **Only CREATED action supported**: Other actions will throw an error - additional actions will be added iteratively in follow-up PRs
- **Feature flag controlled**: System is behind `booking-audit` flag, disabled by default
- **UI strings need i18n**: Some UI text in `booking-logs-view.tsx` may need translation

### Human Review Checklist

- [ ] Verify permission enforcement strategy for audit log access
- [ ] Review DI wiring in module files
- [ ] Confirm error handling in `BookingAuditTaskConsumer` is appropriate for retry scenarios
- [ ] Check if UI strings need to be added to translation files
- [ ] Verify `TaskRepository` refactoring maintains backward compatibility (singleton export `Task` should work for all existing call sites)

## Mandatory Tasks (DO NOT REMOVE)

- [ ] I have self-reviewed the code (A decent size PR without self-review might be rejected).
- [x] I have updated the developer docs in /docs if this PR makes changes that would require a [documentation change](https://cal.com/docs). N/A - internal infrastructure
- [x] I confirm automated tests are in place that prove my fix is effective or that my feature works.

## How should this be tested?

Run the integration tests:

```bash
TZ=UTC yarn test packages/features/booking-audit/lib/service/BookingAuditViewerService.integration-test.ts
TZ=UTC yarn test packages/features/booking-audit/lib/service/BookingAuditTaskConsumer.integration-test.ts
```

To test the UI:

1. Enable the `booking-audit` feature flag in the database
2. Create a booking (only CREATED action is supported in this PR)
3. Navigate to `/booking/logs/{bookingUid}` to view the audit trail

## Checklist

- [x] I have read the [contributing guide](https://github.com/calcom/cal.com/blob/main/CONTRIBUTING.md)
- [x] My code follows the style guidelines of this project
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have checked if my changes generate no new warnings

<!-- Link to Devin run: https://app.devin.ai/sessions/a8ae61c253b549429401c9651dcbcf44 -->
<!-- Requested by: hariom@cal.com (@hariombalhara) -->
2025-12-08 17:38:58 +05:30
sean-brydon fadd824d12 feat: onboarding v3 QA final roast (#25667)
* remove leading none

* remove back button if coming from teams/org onboarding

* add skip now
2025-12-08 11:35:44 +00:00
Volnei MunhozandDevin AI c1b7b6e83d fix: prevent OOO dialog from closing on outside click (#25699)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-08 11:23:09 +00:00
Volnei Munhoz e82a53a442 add fallback discovery for oauth (#25656) 2025-12-08 11:15:31 +00:00
a6578fdcd2 perf: handleChildrenEventType link old event-type with workflows using create/findMany (#25653)
* perf: link old event-type with workflows using create/findMany

* test: fix handleChildrenEventTypes test mocks for new workflow linking implementation

Update test to match the new implementation that uses findMany + createMany
instead of upsert for linking workflows to old event types.

- Add mock for workflowsOnEventTypes.findMany to return empty array
- Update assertion from upsert to findMany + createMany

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-08 13:11:21 +02:00
Eunjae LeeandDevin AI 4e68bcb021 docs: improve AGENTS.md and rename .agents to agents/ (#25665)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-08 11:06:59 +00:00
1e673f1df4 perf: handleChildrenEventTypes createManyAndReturn (#25652)
* perf: handleChildrenEventTypes createManyAndReturn

* fix: update test mocks for createManyAndReturn

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

* fix: use full EventType shape in createManyAndReturn mock return values

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-08 10:21:57 +00:00
Morgan b91f27dc80 perf: handleChildrenEventType eventtype user connect raw sql (#25650)
* perf: handleChildrenEventType eventtype user connect raw sql

* fixup! perf: handleChildrenEventType eventtype user connect raw sql

* remove user connect with prisma
2025-12-08 11:41:25 +02:00
Benny Joo becae27b45 refactor: migrate verifyCodeUnAuthenticated from TRPC layer to features layer (#25639)
* rm

* update test

* verifyCodeUnAuthenticated

* wip
2025-12-08 10:54:46 +02:00
Benny JooandDevin AI 584f5581fa refactor: move handleNotificationWhenNoSlots from trpc to features/slots (#25538)
Move handleNotificationWhenNoSlots.ts and its test file from
packages/trpc/server/routers/viewer/slots/ to packages/features/slots/
to resolve circular dependency issue where packages/features imports
from packages/trpc.

This file is not TRPC-specific and belongs in the features package.

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-08 10:54:21 +02:00
Anik Dhabal Babu e10c4c1cb5 fix: unable to reject the booking from email (#25673)
* fix: unable to reject the booking

* Refactor error handling for booking confirmation
2025-12-08 12:32:19 +05:30
Syed Ali Shahbaz c78552ce60 fix: OnDelete SetNull for watchlist delete on watchlistAudit (#25690)
* OnDelete SetNull for watchlist delete on watchlistAudit

* make watchlistId nullable

* type fix
2025-12-08 05:22:01 +00:00
Morgan 9631d0a64b chore: update add members to team (#25685) 2025-12-08 03:48:15 +00:00
1182460d5c chore: add permission checks to invite member and list team members handlers (#25679)
* chore: update invite team member handler

* chore: update invite team member handler

* fix: add mock for PermissionCheckService in inviteMember handler tests

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

* fix: add mocks for PBAC dependencies in inviteMember handler tests

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-07 16:32:55 +00:00
1181 changed files with 65272 additions and 33095 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"@calcom/atoms": minor
---
Fix Booker atom verify email dialog infinite re-render when entering verification code
-5
View File
@@ -1,5 +0,0 @@
---
"@calcom/atoms": minor
---
This PR introduces two variants for the calendar view atom, a generic calendar view and an event type specific view containing bookings data and busy times from connected calendars.
-5
View File
@@ -1,5 +0,0 @@
---
"@calcom/atoms": minor
---
Refactor SettingsHeader to accept onBackButtonClick callback instead of using useRouter directly.
-5
View File
@@ -1,5 +0,0 @@
---
"@calcom/atoms": minor
---
Add defaultPhoneCountry prop to BookerPlatformWrapper with ISO 3166-1 alpha-2 type safety
-5
View File
@@ -1,5 +0,0 @@
---
"@calcom/atoms": patch
---
This PR fixes the issue of connect atoms not working inside iframes. It also updates the atoms exports to include the `useAvailableSlots` hook.
+5
View File
@@ -0,0 +1,5 @@
---
"@calcom/atoms": minor
---
feat: Booker accepts rrHostSubsetIds to specify round robin hosts
-5
View File
@@ -1,5 +0,0 @@
---
"@calcom/atoms": major
---
feat: use tailwind v4 (breaking change)
-187
View File
@@ -1,187 +0,0 @@
language: en-US
tone_instructions: ''
early_access: false
enable_free_tier: true
reviews:
profile: chill
request_changes_workflow: false
high_level_summary: false
high_level_summary_placeholder: '@coderabbitai summary'
high_level_summary_in_walkthrough: false
auto_title_placeholder: '@coderabbitai'
auto_title_instructions: ''
review_status: true
commit_status: true
fail_commit_status: false
collapse_walkthrough: false
changed_files_summary: false
sequence_diagrams: false
estimate_code_review_effort: false
assess_linked_issues: true
related_issues: false
related_prs: true
suggested_labels: false
auto_apply_labels: false
suggested_reviewers: false
auto_assign_reviewers: false
poem: false
labeling_instructions: []
path_filters:
- '!**/node_modules/**'
- '!**/dist/**'
- '!**/build/**'
- '!**/.next/**'
path_instructions:
- path: "**/*.{ts,tsx,js,jsx}"
instructions: "Flag default exports and encourage named exports. Named exports provide better tree-shaking, easier refactoring, and clearer imports. Exempt main components like pages, layouts, and components that serve as the primary export of a module."
abort_on_close: true
disable_cache: false
auto_review:
enabled: true
auto_incremental_review: true
ignore_title_keywords: []
labels: []
drafts: false
base_branches: []
finishing_touches:
docstrings:
enabled: true
unit_tests:
enabled: true
pre_merge_checks:
docstrings:
mode: warning
threshold: 80
title:
mode: warning
requirements: ''
description:
mode: warning
issue_assessment:
mode: warning
tools:
ast-grep:
rule_dirs: []
util_dirs: []
essential_rules: true
packages: []
shellcheck:
enabled: true
ruff:
enabled: true
markdownlint:
enabled: true
github-checks:
enabled: true
timeout_ms: 180000
languagetool:
enabled: true
enabled_rules: []
disabled_rules: []
enabled_categories: []
disabled_categories: []
enabled_only: false
level: default
biome:
enabled: true
hadolint:
enabled: true
swiftlint:
enabled: true
phpstan:
enabled: true
level: default
phpmd:
enabled: true
phpcs:
enabled: true
golangci-lint:
enabled: true
yamllint:
enabled: true
gitleaks:
enabled: true
checkov:
enabled: true
detekt:
enabled: true
eslint:
enabled: true
flake8:
enabled: true
rubocop:
enabled: true
buf:
enabled: true
regal:
enabled: true
actionlint:
enabled: true
pmd:
enabled: true
cppcheck:
enabled: true
semgrep:
enabled: true
circleci:
enabled: true
clippy:
enabled: true
sqlfluff:
enabled: true
prismaLint:
enabled: true
pylint:
enabled: true
oxc:
enabled: true
shopifyThemeCheck:
enabled: true
luacheck:
enabled: true
brakeman:
enabled: true
dotenvLint:
enabled: true
htmlhint:
enabled: true
checkmake:
enabled: true
osvScanner:
enabled: true
chat:
art: true
auto_reply: true
integrations:
jira:
usage: auto
linear:
usage: auto
knowledge_base:
opt_out: false
web_search:
enabled: true
code_guidelines:
enabled: true
filePatterns: []
learnings:
scope: auto
issues:
scope: auto
jira:
usage: auto
project_keys: []
linear:
usage: auto
team_keys: []
pull_requests:
scope: auto
mcp:
usage: auto
disabled_servers: []
code_generation:
docstrings:
language: en-US
path_instructions: []
unit_tests:
path_instructions: []
+8
View File
@@ -127,6 +127,14 @@ NEXT_PUBLIC_HELPSCOUT_KEY=
NEXT_PUBLIC_FRESHCHAT_TOKEN=
NEXT_PUBLIC_FRESHCHAT_HOST=
# For holiday feature:
# Step-by-step: Get a Google Calendar API Key
# 1. Go to Google Cloud Console: https://console.cloud.google.com/
# 2. Select or Create a Project
# 3. Enable Google Calendar API (APIs & Services → Library , Search for Google Calendar API)
# 4. Create the API Key (APIs & Services → Credentials)
GOOGLE_CALENDAR_API_KEY=
# Google OAuth credentials
# To enable Login with Google you need to:
# 1. Set `GOOGLE_API_CREDENTIALS` below
+4
View File
@@ -0,0 +1,4 @@
/.yarn/** linguist-vendored
/.yarn/releases/* binary
/.yarn/plugins/**/* binary
/.pnp.* binary linguist-generated
@@ -34,6 +34,10 @@ inputs:
description: "Whether to push the built image"
required: false
default: "false"
use-as-latest:
description: "Publish as latest"
required: false
default: "false"
runs:
using: "composite"
@@ -61,7 +65,7 @@ runs:
docker.io/calcom/cal.com
ghcr.io/calcom/cal.com
flavor: |
latest=${{ !github.event.release.prerelease }}
latest=${{ !github.event.release.prerelease && inputs.use-as-latest == 'true' }}
suffix=${{ inputs.platform-suffix }}
- name: Copy env
+1 -1
View File
@@ -37,5 +37,5 @@ jobs:
export NODE_OPTIONS="--max_old_space_size=8192"
rm -rf packages/platform/atoms/node_modules
yarn install
yarn workspace @calcom/atoms run build
yarn workspace @calcom/atoms run build-npm
shell: bash
+2
View File
@@ -3,6 +3,8 @@ on:
workflow_call:
env:
NODE_OPTIONS: --max-old-space-size=4096
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
permissions:
contents: read
jobs:
+9 -1
View File
@@ -11,12 +11,20 @@ jobs:
cleanup-report:
runs-on: ubuntu-latest
steps:
- name: Generate GitHub App token
id: generate-token
uses: actions/create-github-app-token@7e473efe3cb98aa54f8d4bac15400b15fad77d94
with:
app-id: ${{ secrets.CI_CAL_APP_ID }}
private-key: ${{ secrets.CI_CAL_APP_PRIVATE_KEY }}
repositories: 'test-results-2'
- name: Checkout GitHub Pages Branch
uses: actions/checkout@v4
with:
repository: calcom/test-results-2
ref: gh-pages
token: ${{ secrets.GH_ACCESS_TOKEN }}
token: ${{ steps.generate-token.outputs.token }}
- name: Set Git User
run: |
+10 -2
View File
@@ -22,12 +22,20 @@ jobs:
# Contains all reports for deleted branch
BRANCH_REPORTS_DIR: reports/${{ github.event.ref }}
steps:
- name: Generate GitHub App token
id: generate-token
uses: actions/create-github-app-token@7e473efe3cb98aa54f8d4bac15400b15fad77d94
with:
app-id: ${{ secrets.CI_CAL_APP_ID }}
private-key: ${{ secrets.CI_CAL_APP_PRIVATE_KEY }}
repositories: 'test-results-2'
- name: Checkout GitHub Pages Branch
uses: actions/checkout@v2
uses: actions/checkout@v4
with:
repository: calcom/test-results-2
ref: gh-pages
token: ${{ secrets.GH_ACCESS_TOKEN }}
token: ${{ steps.generate-token.outputs.token }}
- name: Set Git User
# see: https://github.com/actions/checkout/issues/13#issuecomment-724415212
run: |
+13 -8
View File
@@ -14,24 +14,29 @@ jobs:
name: Build Companion App & Extension
runs-on: buildjet-4vcpu-ubuntu-2204
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/dangerous-git-checkout
- name: Setup Node.js
uses: actions/setup-node@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
node-version: 20
cache: npm
cache-dependency-path: companion/package-lock.json
bun-version: 1.3.0
cache: true
cache-dependency-path: companion/bun.lock
- name: Install dependencies
working-directory: companion
run: npm ci
run: bun install --frozen-lockfile
- name: Build Expo web app
working-directory: companion
env:
EXPO_NO_TELEMETRY: 1
CI: true
run: npx expo export --platform web
run: bunx expo export --platform web
- name: Build browser extension
working-directory: companion
run: npm run ext:build
run: bun run ext:build
+9 -2
View File
@@ -17,13 +17,20 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Generate GitHub App token
id: generate-token
uses: actions/create-github-app-token@7e473efe3cb98aa54f8d4bac15400b15fad77d94
with:
app-id: ${{ secrets.CI_CAL_APP_ID }}
private-key: ${{ secrets.CI_CAL_APP_PRIVATE_KEY }}
repositories: 'cal.com'
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: 'main'
token: ${{ secrets.GH_ACCESS_TOKEN }}
token: ${{ steps.generate-token.outputs.token }}
- name: Configure git
run: |
+9 -1
View File
@@ -16,6 +16,14 @@ jobs:
contents: write
pull-requests: write
steps:
- name: Generate GitHub App token
id: generate-token
uses: actions/create-github-app-token@7e473efe3cb98aa54f8d4bac15400b15fad77d94
with:
app-id: ${{ secrets.CI_CAL_APP_ID }}
private-key: ${{ secrets.CI_CAL_APP_PRIVATE_KEY }}
repositories: 'cal.com'
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
@@ -23,7 +31,7 @@ jobs:
cache: 'npm'
- uses: lingodotdev/lingo.dev@main
env:
GH_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }}
GH_TOKEN: ${{ steps.generate-token.outputs.token }}
with:
api-key: ${{ secrets.CI_LINGO_DOT_DEV_API_KEY }}
pull-request: true
-12
View File
@@ -15,18 +15,6 @@ jobs:
- uses: actions/labeler@v5
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
team-labels:
permissions:
contents: read
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: equitybee/team-label-action@main
with:
repo-token: ${{ secrets.EQUITY_BEE_TEAM_LABELER_ACTION_TOKEN }}
organization-name: calcom
ignore-labels: "admin, app-store, ai, api, authentication, automated-testing, billing, bookings, caldav, calendar-apps, ci, console, crm-apps, dba, devops, docs, documentation, emails, embeds, event-types, i18n, impersonation, manual-testing, ui, performance, ops-stack, organizations, public-api, routing-forms, seats, self-hosted, sre, teams, webhooks, workflows, zapier"
apply-labels-from-issue:
runs-on: ubuntu-latest
+12 -1
View File
@@ -6,16 +6,27 @@ on:
tags:
- "*"
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Generate GitHub App token
id: generate-token
uses: actions/create-github-app-token@7e473efe3cb98aa54f8d4bac15400b15fad77d94
with:
app-id: ${{ secrets.CI_CAL_APP_ID }}
private-key: ${{ secrets.CI_CAL_APP_PRIVATE_KEY }}
repositories: 'cal.com'
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: 'main'
token: ${{ secrets.GH_ACCESS_TOKEN }}
token: ${{ steps.generate-token.outputs.token }}
- name: Configure git
run: |
+31 -5
View File
@@ -24,6 +24,7 @@ jobs:
pull-requests: read
outputs:
has-files-requiring-all-checks: ${{ steps.filter.outputs.has-files-requiring-all-checks }}
has_companion: ${{ steps.filter.outputs.has_companion }}
commit-sha: ${{ steps.get_sha.outputs.commit-sha }}
steps:
- uses: actions/checkout@v4
@@ -33,7 +34,9 @@ jobs:
with:
filters: |
has-files-requiring-all-checks:
- "!(**.md|**.mdx|.github/CODEOWNERS|docs/**|help/**|apps/web/public/static/locales/**/common.json|i18n.lock)"
- "!(companion/**|**.md|**.mdx|.github/CODEOWNERS|docs/**|help/**|apps/web/public/static/locales/**/common.json|i18n.lock)"
has_companion:
- "companion/**"
- name: Get Latest Commit SHA
id: get_sha
run: |
@@ -148,8 +151,8 @@ jobs:
build-companion:
name: Companion builds
needs: [changes, check-label, deps]
if: ${{ needs.check-label.outputs.run-e2e == 'true' && needs.changes.outputs.has-files-requiring-all-checks == 'true' }}
needs: [changes, check-label]
if: needs.changes.outputs.has_companion == 'true'
uses: ./.github/workflows/companion-build.yml
secrets: inherit
@@ -256,11 +259,34 @@ jobs:
e2e-api-v2,
e2e-embed,
e2e-embed-react,
e2e-app-store
e2e-app-store,
]
if: always()
runs-on: buildjet-2vcpu-ubuntu-2204
steps:
- name: fail if conditional jobs failed
if: needs.changes.outputs.has-files-requiring-all-checks == 'true' && (contains(needs.*.result, 'failure') || contains(needs.*.result, 'skipped') || contains(needs.*.result, 'cancelled'))
run: exit 1
if: |
(
needs.changes.outputs.has-files-requiring-all-checks == 'true' &&
(
needs.lint.result != 'success' ||
needs.type-check.result != 'success' ||
needs.unit-test.result != 'success' ||
needs.build.result != 'success' ||
needs.build-api-v1.result != 'success' ||
needs.build-api-v2.result != 'success' ||
needs.build-atoms.result != 'success' ||
needs.build-docs.result != 'success' ||
needs.integration-test.result != 'success' ||
needs.e2e.result != 'success' ||
needs.e2e-api-v2.result != 'success' ||
needs.e2e-embed.result != 'success' ||
needs.e2e-embed-react.result != 'success' ||
needs.e2e-app-store.result != 'success'
)
) ||
(
needs.changes.outputs.has_companion == 'true' &&
needs.build-companion.result != 'success'
)
+9 -1
View File
@@ -13,12 +13,20 @@ jobs:
HTML_REPORT_URL_PATH: reports/${{ github.head_ref }}/${{ github.run_id }}/${{ github.run_attempt }}
BRANCH_REPORTS_DIR: reports/${{ github.head_ref }}
steps:
- name: Generate GitHub App token
id: generate-token
uses: actions/create-github-app-token@7e473efe3cb98aa54f8d4bac15400b15fad77d94
with:
app-id: ${{ secrets.CI_CAL_APP_ID }}
private-key: ${{ secrets.CI_CAL_APP_PRIVATE_KEY }}
repositories: 'test-results-2'
- name: Checkout GitHub Pages Branch
uses: actions/checkout@v4
with:
repository: calcom/test-results-2
ref: gh-pages
token: ${{ secrets.GH_ACCESS_TOKEN }}
token: ${{ steps.generate-token.outputs.token }}
- name: Set Git User
# see: https://github.com/actions/checkout/issues/13#issuecomment-724415212
run: |
+1
View File
@@ -40,6 +40,7 @@ jobs:
postgres-db: ${{ env.POSTGRES_DB }}
database-host: ${{ env.DATABASE_HOST }}
push-image: "true"
use-as-latest: "true"
- name: Notify Slack on Success
if: success()
-3
View File
@@ -1,6 +1,3 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn lint-staged
yarn app-store:build && git add packages/app-store/*.generated.*
+202 -19
View File
@@ -1,30 +1,213 @@
# Cal.com Development Guide for AI Agents
**📖 Complete documentation is in the [.agents/](.agents/) directory.**
You are a senior Cal.com engineer working in a Yarn/Turbo monorepo. You prioritize type safety, security, and small, reviewable diffs.
## Quick Reference
## Do
### Essential Commands
- Use `select` instead of `include` in Prisma queries for performance and security
- Use `import type { X }` for TypeScript type imports
- Use early returns to reduce nesting: `if (!booking) return null;`
- Use `ErrorWithCode` for errors in non-tRPC files (services, repositories, utilities); use `TRPCError` only in tRPC routers
- Use conventional commits: `feat:`, `fix:`, `refactor:`
- Create PRs in draft mode by default
- Run `yarn type-check:ci --force` before concluding CI failures are unrelated to your changes
- Import directly from source files, not barrel files (e.g., `@calcom/ui/components/button` not `@calcom/ui`)
- Add translations to `apps/web/public/static/locales/en/common.json` for all UI strings
- Use `date-fns` or native `Date` instead of Day.js when timezone awareness isn't needed
- Put permission checks in `page.tsx`, never in `layout.tsx`
- Use `ast-grep` for searching if available; otherwise use `rg` (ripgrep), then fall back to `grep`
- `yarn dev` - Start development server
- `yarn build` - Build all packages
- `yarn lint:fix` - Lint and fix code
- `yarn type-check` - TypeScript checking
- `yarn test <filename> -- --integrationTestsOnly` - Run integration tests
- `yarn e2e <filename> --grep "<testName>"` - Run specific E2E test
## Don't
## Tool Preferences
- Never use `as any` - use proper type-safe solutions instead
- Never expose `credential.key` field in API responses or queries
- Never commit secrets or API keys
- Never modify `*.generated.ts` files directly - they're created by app-store-cli
- Never put business logic in repositories - that belongs in Services
- Never use barrel imports from index.ts files
- Never skip running type checks before pushing
- Never create large PRs (>500 lines or >10 files) - split them instead
### Search Tools Priority
## Commands
Use tools in this order of preference:
### File-scoped (preferred for speed)
1. **ast-grep** - For AST-based code searches (if available)
2. **rg (ripgrep)** - For fast text searches
3. **grep** - As fallback for text searches
```bash
# Type check - always run on changed files
yarn type-check:ci --force
## 📚 Detailed Documentation
# Lint single file
yarn eslint --fix path/to/file.tsx
- **[.agents/README.md](.agents/README.md)** - Complete development guide
- **[.agents/commands.md](.agents/commands.md)** - All build, test & dev commands
- **[.agents/knowledge-base.md](.agents/knowledge-base.md)** - Knowledge base & best practices
# Format single file
yarn prettier --write path/to/file.tsx
# Unit test specific file
yarn vitest run path/to/file.test.ts
# Unit test specific file + specific test
yarn vitest run path/to/file.test.ts --testNamePattern="specific test name"
# Integration test specific file
yarn test path/to/file.integration-test.ts -- --integrationTestsOnly
# Integration test specific file + specific test
yarn test path/to/file.integration-test.ts --testNamePattern="specific test name" -- --integrationTestsOnly
# E2E test specific file
PLAYWRIGHT_HEADLESS=1 yarn e2e path/to/file.e2e.ts
# E2E test specific file + specific test
PLAYWRIGHT_HEADLESS=1 yarn e2e path/to/file.e2e.ts --grep "specific test name"
```
### Project-wide (use sparingly)
```bash
# Development
yarn dev # Start dev server
yarn dx # Dev with database setup
# Build & check
yarn build # Build all packages
yarn lint:fix # Lint and fix all
yarn type-check # Type check all
# Tests (use TZ=UTC for consistency)
TZ=UTC yarn test # All unit tests
yarn e2e # All E2E tests
# Database
yarn prisma generate # Regenerate types after schema changes
yarn workspace @calcom/prisma db-migrate # Run migrations
```
## Boundaries
### Always do
- Run type check on changed files before committing
- Run relevant tests before pushing
- Use `select` in Prisma queries
- Follow conventional commits for PR titles
### Ask first
- Adding new dependencies
- Schema changes to `packages/prisma/schema.prisma`
- Changes affecting multiple packages
- Deleting files
- Running full build or E2E suites
### Never do
- Commit secrets, API keys, or `.env` files
- Expose `credential.key` in any query
- Use `as any` type casting
- Force push or rebase shared branches
- Modify generated files directly
## Project Structure
```
apps/web/ # Main Next.js application
packages/prisma/ # Database schema (schema.prisma) and migrations
packages/trpc/ # tRPC API layer (routers in server/routers/)
packages/ui/ # Shared UI components
packages/features/ # Feature-specific code
packages/app-store/ # Third-party integrations
packages/lib/ # Shared utilities
```
### Key files
- Routes: `apps/web/app/` (App Router)
- Database schema: `packages/prisma/schema.prisma`
- tRPC routers: `packages/trpc/server/routers/`
- Translations: `apps/web/public/static/locales/en/common.json`
- Workflow constants: `packages/features/ee/workflows/lib/constants.ts`
## Tech Stack
- **Framework**: Next.js 13+ (App Router in some areas)
- **Language**: TypeScript (strict)
- **Database**: PostgreSQL with Prisma ORM
- **API**: tRPC for type-safe APIs
- **Auth**: NextAuth.js
- **Styling**: Tailwind CSS
- **Testing**: Vitest (unit), Playwright (E2E)
- **i18n**: next-i18next
## Code Examples
### Good error handling
```typescript
// Good - Descriptive error with context
throw new Error(`Unable to create booking: User ${userId} has no available time slots for ${date}`);
// Bad - Generic error
throw new Error("Booking failed");
```
For which error class to use (`ErrorWithCode` vs `TRPCError`) and concrete examples, see [Error Types in knowledge-base.md](agents/knowledge-base.md#error-types).
### Good Prisma query
```typescript
// Good - Use select for performance and security
const booking = await prisma.booking.findFirst({
select: {
id: true,
title: true,
user: {
select: {
id: true,
name: true,
email: true,
}
}
}
});
// Bad - Include fetches all fields including sensitive ones
const booking = await prisma.booking.findFirst({
include: { user: true }
});
```
### Good imports
```typescript
// Good - Type imports and direct paths
import type { User } from "@prisma/client";
import { Button } from "@calcom/ui/components/button";
// Bad - Regular import for types, barrel imports
import { User } from "@prisma/client";
import { Button } from "@calcom/ui";
```
## PR Checklist
- [ ] Title follows conventional commits: `feat(scope): description`
- [ ] Type check passes: `yarn type-check:ci --force`
- [ ] Lint passes: `yarn lint:fix`
- [ ] Relevant tests pass
- [ ] Diff is small and focused (<500 lines, <10 files)
- [ ] No secrets or API keys committed
- [ ] UI strings added to translation files
- [ ] Created as draft PR
## When Stuck
- Ask a clarifying question before making large speculative changes
- Propose a short plan for complex tasks
- Open a draft PR with notes if unsure about approach
- Fix type errors before test failures - they're often the root cause
- Run `yarn prisma generate` if you see missing enum/type errors
## Extended Documentation
For detailed information, see the `agents/` directory:
- **[agents/README.md](agents/README.md)** - Architecture overview and patterns
- **[agents/commands.md](agents/commands.md)** - Complete command reference
- **[agents/knowledge-base.md](agents/knowledge-base.md)** - Domain knowledge and best practices
- **[agents/coding-standards.md](agents/coding-standards.md)** - Coding standards with examples
+3
View File
@@ -77,6 +77,9 @@ RUN scripts/replace-placeholder.sh http://NEXT_PUBLIC_WEBAPP_URL_PLACEHOLDER ${N
FROM node:20 AS runner
WORKDIR /calcom
RUN apt-get update && apt-get install -y --no-install-recommends netcat-openbsd wget && rm -rf /var/lib/apt/lists/*
COPY --from=builder-two /calcom ./
ARG NEXT_PUBLIC_WEBAPP_URL=http://localhost:3000
ENV NEXT_PUBLIC_WEBAPP_URL=$NEXT_PUBLIC_WEBAPP_URL \
+2 -2
View File
@@ -836,12 +836,12 @@ following
1. Open [HubSpot Developer](https://developer.hubspot.com/) and sign into your account, or create a new one.
2. From within the home of the Developer account page, go to "Manage apps".
3. Click "Create app" button top right.
3. Click "Create legacy app" button top right and select public app.
4. Fill in any information you want in the "App info" tab
5. Go to tab "Auth"
6. Now copy the Client ID and Client Secret to your `.env` file into the `HUBSPOT_CLIENT_ID` and `HUBSPOT_CLIENT_SECRET` fields.
7. Set the Redirect URL for OAuth `<Cal.com URL>/api/integrations/hubspot/callback` replacing Cal.com URL with the URI at which your application runs.
8. In the "Scopes" section at the bottom of the page, make sure you select "Read" and "Write" for scope called `crm.objects.contacts`
8. In the "Scopes" section at the bottom of the page, make sure you select "Read" and "Write" for scopes called `crm.objects.contacts` and `crm.lists`.
9. Click the "Save" button at the bottom footer.
10. You're good to go. Now you can see any booking in Cal.com created as a meeting in HubSpot for your contacts.
@@ -27,6 +27,12 @@ import { User } from "@prisma/client";
- Use React children and context instead of passing props through multiple components
### ORM and Types
- Never import `@calcom/prisma/client` in features, services, UI, or handlers.
- Use repository DTOs or domain types instead.
- See "Repository + DTO Pattern and Method Conventions" in the knowledge base for details and examples.
### Security Rules
```typescript
+8 -2
View File
@@ -28,11 +28,17 @@
- `yarn test` - Run unit tests (vitest)
- `yarn test <filename>` - Run tests for specific file
- `yarn test <filename> -- --integrationTestsOnly` - Run integration tests for specific file
- `yarn test <filename> -t "<testName>" -- --integrationTestsOnly` - Run specific test by name
- `yarn test <filename> -t "<testName>"` - Run specific test by name for specific file
- `yarn tdd` - Run tests in watch mode
- `yarn test:ui` - Run tests with UI interface
### Integration Tests
- `yarn test -- --integrationTestsOnly` - Run integration tests (vitest)
- `yarn test <filename> -- --integrationTestsOnly` - Run integration tests for specific file
- `yarn test <filename> -t "<testName>" -- --integrationTestsOnly` - Run specific integration test by name for specific file
### End-to-End Tests
- `yarn e2e` - Run end-to-end tests (Playwright)
@@ -225,16 +225,38 @@ throw new Error("Booking failed");
### Error Types
Use `ErrorWithCode` for files that are not directly coupled to tRPC. The tRPC package has a middleware called `errorConversionMiddleware` that automatically converts `ErrorWithCode` instances into `TRPCError` instances.
```typescript
// ✅ Good - Use proper error classes
// ✅ Good - Use ErrorWithCode in non-tRPC files (services, repositories, utilities)
import { ErrorCode } from "@calcom/lib/errorCodes";
import { ErrorWithCode } from "@calcom/lib/errors";
// Option 1: Using constructor with ErrorCode enum
throw new ErrorWithCode(ErrorCode.BookingNotFound, "Booking not found");
// Option 2: Using the Factory pattern for common HTTP errors
throw ErrorWithCode.Factory.Forbidden("You don't have permission to view this");
throw ErrorWithCode.Factory.NotFound("Resource not found");
throw ErrorWithCode.Factory.BadRequest("Invalid input");
// ✅ Good - Use TRPCError only in tRPC routers/procedures
import { TRPCError } from "@trpc/server";
throw new TRPCError({
code: "BAD_REQUEST",
message: "Invalid booking time slot",
});
// ❌ Bad - Using TRPCError in non-tRPC files
import { TRPCError } from "@trpc/server";
// Don't use TRPCError in services, repositories, or utility files
```
### packages/features Import Restrictions
Files in `packages/features/**` should NOT import from `trpc`. This keeps the features package decoupled from the tRPC layer, making the code more reusable and testable. Use `ErrorWithCode` for error handling in these files, and let the tRPC middleware handle the conversion.
## Basic Performance Guidelines
- Aim for O(n) or O(n log n) complexity, avoid O(n²)
@@ -306,9 +328,54 @@ import { Button } from "@calcom/ui/components/button";
- **Tests**: Same as source file + `.test.ts` or `.spec.ts`
- **Avoid**: Dot-suffixes like `.service.ts`, `.repository.ts` (except for tests, types, specs)
## Repository Method Conventions
## Repository + DTO Pattern and Method Conventions
Repositories should follow consistent naming and design patterns to promote reusability and maintainability.
We use a Repository + DTO pattern to isolate Prisma and the database from business logic. Repositories are the only layer that talks to Prisma and database models. All services, tRPC handlers, API controllers, workflows, and UI should depend on DTOs or domain types, not Prisma types.
DTOs (Data Transfer Objects) are simple TypeScript types or interfaces that represent our domain data in an ORM-agnostic way and are returned from repositories.
### Why this pattern?
- **Prevent type leaks**: Prisma type changes stay inside repositories instead of breaking services, handlers, and UI across dozens of files.
- **Enable safe refactors**: Business logic works against stable DTOs, so you can change storage details without touching higher layers.
- **Keep ORM swappable**: If we ever change ORM, only repository implementations change; services and handlers stay the same.
### What not to do: tight Prisma coupling in business logic
Do not import Prisma types in business logic. Prisma types belong only in the data access layer.
```typescript
// ❌ Bad – business logic depends on Prisma
import type { Webhook } from "@calcom/prisma/client";
export function sendPayload(webhook: Webhook) { /* ... */ }
// ✅ Good – business logic depends on DTO + repository
export interface WebhookDTO { id: string; url: string; }
export interface IWebhookRepository { findById(id: string): Promise<WebhookDTO | null>; }
export async function sendPayload(repo: IWebhookRepository, id: string) {
const webhook = await repo.findById(id);
// ...
}
```
### DTOs in repositories
Repositories should expose DTOs from their public methods and keep Prisma types internal. Inside the repository, use `Prisma.*GetPayload` and map rows to DTOs. The public methods should only return DTOs, never Prisma models.
```typescript
// DTO – ORM-agnostic type exported from the repository module
export interface BookingDTO {
id: string;
userId: number;
startTime: Date;
status: "PENDING" | "CONFIRMED" | "CANCELLED";
}
```
### Prisma boundaries
- **Allowed**: `packages/prisma`, repository implementations (`packages/features/**/repositories/*Repository.ts`), and low-level data access infrastructure.
- **Not allowed**: `packages/features/**` business logic (non-repository), `packages/trpc/**` handlers, `apps/web/**`, `apps/api/v2/**` services/controllers, and workflow/webhook/service layers.
### Method Naming Rules
+5 -5
View File
@@ -11,9 +11,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ILicenseKeyService } from "@calcom/ee/common/server/LicenseKeyService";
import LicenseKeyService, { LicenseKeySingleton } from "@calcom/ee/common/server/LicenseKeyService";
import { PrismaApiKeyRepository } from "@calcom/lib/server/repository/PrismaApiKeyRepository";
import type { IDeploymentRepository } from "@calcom/lib/server/repository/deployment.interface";
import { ApiKeyService } from "@calcom/lib/server/service/ApiKeyService";
import { PrismaApiKeyRepository } from "@calcom/features/ee/api-keys/repositories/PrismaApiKeyRepository";
import { ApiKeyService } from "@calcom/features/ee/api-keys/services/ApiKeyService";
import type { IDeploymentRepository } from "@calcom/features/ee/deployment/repositories/IDeploymentRepository";
import { UserPermissionRole } from "@calcom/prisma/enums";
import { isAdminGuard } from "../utils/isAdmin";
@@ -21,11 +21,11 @@ import { isLockedOrBlocked } from "../utils/isLockedOrBlocked";
import { ScopeOfAdmin } from "../utils/scopeOfAdmin";
import { verifyApiKey } from "./verifyApiKey";
vi.mock("@calcom/lib/server/service/ApiKeyService", () => ({
vi.mock("@calcom/features/ee/api-keys/services/ApiKeyService", () => ({
ApiKeyService: vi.fn(),
}));
vi.mock("@calcom/lib/server/repository/PrismaApiKeyRepository", () => ({
vi.mock("@calcom/features/ee/api-keys/repositories/PrismaApiKeyRepository", () => ({
PrismaApiKeyRepository: vi.fn(),
}));
+3 -3
View File
@@ -2,10 +2,10 @@ import type { NextMiddleware } from "next-api-middleware";
import { LicenseKeySingleton } from "@calcom/ee/common/server/LicenseKeyService";
import { hashAPIKey } from "@calcom/features/ee/api-keys/lib/apiKeys";
import { PrismaApiKeyRepository } from "@calcom/features/ee/api-keys/repositories/PrismaApiKeyRepository";
import { ApiKeyService } from "@calcom/features/ee/api-keys/services/ApiKeyService";
import { DeploymentRepository } from "@calcom/features/ee/deployment/repositories/DeploymentRepository";
import { IS_PRODUCTION } from "@calcom/lib/constants";
import { PrismaApiKeyRepository } from "@calcom/lib/server/repository/PrismaApiKeyRepository";
import { DeploymentRepository } from "@calcom/lib/server/repository/deployment";
import { ApiKeyService } from "@calcom/lib/server/service/ApiKeyService";
import { prisma } from "@calcom/prisma";
import { isAdminGuard } from "../utils/isAdmin";
+4
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { WEBHOOK_TRIGGER_EVENTS } from "@calcom/features/webhooks/lib/constants";
import { WebhookVersion } from "@calcom/features/webhooks/lib/interface/IWebhookRepository";
import { WebhookSchema } from "@calcom/prisma/zod/modelSchema/WebhookSchema";
const schemaWebhookBaseBodyParams = WebhookSchema.pick({
@@ -21,6 +22,7 @@ export const schemaWebhookCreateParams = z
eventTypeId: z.number().optional(),
userId: z.number().optional(),
secret: z.string().optional().nullable(),
version: z.nativeEnum(WebhookVersion).optional(),
// API shouldn't mess with Apps webhooks yet (ie. Zapier)
// appId: z.string().optional().nullable(),
})
@@ -33,6 +35,7 @@ export const schemaWebhookEditBodyParams = schemaWebhookBaseBodyParams
z.object({
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array().optional(),
secret: z.string().optional().nullable(),
version: z.nativeEnum(WebhookVersion).optional(),
})
)
.partial()
@@ -44,6 +47,7 @@ export const schemaWebhookReadPublic = WebhookSchema.pick({
eventTypeId: true,
payloadTemplate: true,
eventTriggers: true,
version: true,
// FIXME: We have some invalid urls saved in the DB
// subscriberUrl: true,
/** @todo: find out how to properly add back and validate those. */
+1 -1
View File
@@ -35,7 +35,7 @@
"@sentry/nextjs": "^9.15.0",
"bcryptjs": "^2.4.3",
"memory-cache": "^0.2.0",
"next": "^15.4.8",
"next": "15.4.10",
"next-api-middleware": "^1.0.1",
"next-axiom": "^0.17.0",
"next-swagger-doc": "^0.3.6",
+1 -1
View File
@@ -161,7 +161,7 @@ vi.mock("@calcom/features/ee/workflows/lib/getAllWorkflows", () => ({
workflowSelect: {},
}));
vi.mock("@calcom/trpc/server/routers/viewer/workflows/util", () => ({
vi.mock("@calcom/features/ee/workflows/lib/getAllWorkflowsFromEventType", () => ({
getAllWorkflowsFromEventType: vi.fn().mockResolvedValue([]),
}));
@@ -125,7 +125,7 @@ export class BookingsController_2024_04_15 {
private readonly instantBookingCreateService: InstantBookingCreateService,
private readonly eventTypeRepository: PrismaEventTypeRepository,
private readonly teamRepository: PrismaTeamRepository
) {}
) { }
@Get("/")
@UseGuards(ApiAuthGuard)
@@ -270,6 +270,7 @@ export class BookingsController_2024_04_15 {
const res = await handleCancelBooking({
bookingData: bookingRequest.body,
userId: bookingRequest.userId,
userUuid: bookingRequest.userUuid,
arePlatformEmailsEnabled: bookingRequest.arePlatformEmailsEnabled,
platformClientId: bookingRequest.platformClientId,
platformCancelUrl: bookingRequest.platformCancelUrl,
@@ -300,7 +301,7 @@ export class BookingsController_2024_04_15 {
@Permissions([BOOKING_WRITE])
@UseGuards(ApiAuthGuard)
async markNoShow(
@GetUser("id") userId: number,
@GetUser() user: UserWithProfile,
@Body() body: MarkNoShowInput_2024_04_15,
@Param("bookingUid") bookingUid: string
): Promise<MarkNoShowOutput_2024_04_15> {
@@ -309,7 +310,8 @@ export class BookingsController_2024_04_15 {
bookingUid: bookingUid,
attendees: body.attendees,
noShowHost: body.noShowHost,
userId,
userId: user.id,
userUuid: user.uuid,
});
return { status: SUCCESS_STATUS, data: markNoShowResponse };
@@ -378,7 +380,7 @@ export class BookingsController_2024_04_15 {
): Promise<ApiResponse<InstantBookingCreateResult>> {
const oAuthClientId =
clientId?.toString() || (await this.getOAuthClientIdFromEventType(body.eventTypeId));
req.userId = (await this.getOwnerId(req)) ?? -1;
req.userId = (await this.getOwner(req))?.id ?? -1;
try {
const bookingReq = await this.createNextApiBookingRequest(req, oAuthClientId, undefined, isEmbed);
const instantMeeting = await this.instantBookingCreateService.createBooking({
@@ -405,30 +407,45 @@ export class BookingsController_2024_04_15 {
throw new InternalServerErrorException("Could not create instant booking.");
}
private async getOwnerId(req: Request): Promise<number | undefined> {
private async getOwner(req: Request): Promise<{ id: number; uuid: string } | null> {
try {
const bearerToken = req.get("Authorization")?.replace("Bearer ", "");
if (bearerToken) {
if (isApiKey(bearerToken, this.config.get<string>("api.apiKeyPrefix") ?? "cal_")) {
const strippedApiKey = stripApiKey(bearerToken, this.config.get<string>("api.keyPrefix"));
const apiKeyHash = sha256Hash(strippedApiKey);
const keyData = await this.apiKeyRepository.getApiKeyFromHash(apiKeyHash);
return keyData?.userId;
} else {
// Access Token
const ownerId = await this.oAuthFlowService.getOwnerId(bearerToken);
return ownerId;
}
if (!bearerToken) {
return null;
}
let ownerId: number | null = null;
if (isApiKey(bearerToken, this.config.get<string>("api.apiKeyPrefix") ?? "cal_")) {
const strippedApiKey = stripApiKey(bearerToken, this.config.get<string>("api.keyPrefix"));
const apiKeyHash = sha256Hash(strippedApiKey);
const keyData = await this.apiKeyRepository.getApiKeyFromHash(apiKeyHash);
ownerId = keyData?.userId ?? null;
} else {
// Access Token
ownerId = await this.oAuthFlowService.getOwnerId(bearerToken);
}
if (!ownerId) {
return null;
}
const user = await this.usersRepository.findById(ownerId);
if (!user) {
return null;
}
return { id: user.id, uuid: user.uuid };
} catch (err) {
this.logger.error(err);
return null;
}
}
private async getOwnerIdRescheduledBooking(
private async getOwnerRescheduledBooking(
request: Request,
platformClientId?: string
): Promise<number | undefined> {
): Promise<{ id: number; uuid: string } | null> {
if (
platformClientId &&
request.body.rescheduledBy &&
@@ -440,13 +457,15 @@ export class BookingsController_2024_04_15 {
);
}
if (request.body.rescheduledBy) {
if (request.body.rescheduledBy !== request.body.responses.email) {
return (await this.usersRepository.findByEmail(request.body.rescheduledBy))?.id;
if (request.body.rescheduledBy && request.body.rescheduledBy !== request.body.responses.email) {
const user = await this.usersRepository.findByEmail(request.body.rescheduledBy);
if (!user) {
return null;
}
return { id: user.id, uuid: user.uuid };
}
return undefined;
return null;
}
private async getOAuthClientIdFromEventType(eventTypeId: number): Promise<string | undefined> {
@@ -498,7 +517,8 @@ export class BookingsController_2024_04_15 {
}
}
const userId = await this.getOwnerId(req);
const owner = await this.getOwner(req);
const userId = owner?.id;
if (!userId) {
throw new UnauthorizedException(
@@ -561,12 +581,16 @@ export class BookingsController_2024_04_15 {
oAuthClientId?: string,
platformBookingLocation?: string,
isEmbed?: string
): Promise<NextApiRequest & { userId?: number } & OAuthRequestParams> {
): Promise<NextApiRequest & { userId?: number; userUuid?: string } & OAuthRequestParams> {
const requestId = req.get("X-Request-Id");
const clone = { ...req };
const userId = clone.body.rescheduleUid
? await this.getOwnerIdRescheduledBooking(req, oAuthClientId)
: await this.getOwnerId(req);
const owner = clone.body.rescheduleUid
? await this.getOwnerRescheduledBooking(req, oAuthClientId)
: await this.getOwner(req);
const userId = owner?.id;
const userUuid = owner?.uuid;
const oAuthParams = oAuthClientId
? await this.getOAuthClientsParams(oAuthClientId, this.transformToBoolean(isEmbed))
: DEFAULT_PLATFORM_PARAMS;
@@ -577,7 +601,7 @@ export class BookingsController_2024_04_15 {
oAuthClientId,
...oAuthParams,
});
Object.assign(clone, { userId, ...oAuthParams, platformBookingLocation });
Object.assign(clone, { userId, userUuid, ...oAuthParams, platformBookingLocation });
clone.body = {
...clone.body,
noEmail: !oAuthParams.arePlatformEmailsEnabled,
@@ -586,7 +610,7 @@ export class BookingsController_2024_04_15 {
if (oAuthClientId) {
await this.setPlatformAttendeesEmails(clone.body, oAuthClientId);
}
return clone as unknown as NextApiRequest & { userId?: number } & OAuthRequestParams;
return clone as unknown as NextApiRequest & { userId?: number; userUuid?: string } & OAuthRequestParams;
}
async setPlatformAttendeesEmails(
@@ -612,9 +636,12 @@ export class BookingsController_2024_04_15 {
oAuthClientId?: string,
platformBookingLocation?: string,
isEmbed?: string
): Promise<NextApiRequest & { userId?: number } & OAuthRequestParams> {
): Promise<NextApiRequest & { userId?: number; userUuid?: string } & OAuthRequestParams> {
const clone = { ...req };
const userId = (await this.getOwnerId(req)) ?? -1;
const owner = await this.getOwner(req);
const userId = owner?.id ?? -1;
const userUuid = owner?.uuid;
const oAuthParams = oAuthClientId
? await this.getOAuthClientsParams(oAuthClientId, this.transformToBoolean(isEmbed))
: DEFAULT_PLATFORM_PARAMS;
@@ -628,6 +655,7 @@ export class BookingsController_2024_04_15 {
});
Object.assign(clone, {
userId,
userUuid,
...oAuthParams,
platformBookingLocation,
noEmail: !oAuthParams.arePlatformEmailsEnabled,
@@ -636,7 +664,7 @@ export class BookingsController_2024_04_15 {
if (oAuthClientId) {
await this.setPlatformAttendeesEmails(clone.body, oAuthClientId);
}
return clone as unknown as NextApiRequest & { userId?: number } & OAuthRequestParams;
return clone as unknown as NextApiRequest & { userId?: number; userUuid?: string } & OAuthRequestParams;
}
private handleBookingErrors(
@@ -11,6 +11,7 @@ import {
ValidateNested,
isEmail,
Validate,
IsInt,
} from "class-validator";
import { ValidationOptions, registerDecorator } from "class-validator";
@@ -26,7 +27,7 @@ function ValidateBookingName(validationOptions?: ValidationOptions) {
propertyName: propertyName,
options: validationOptions,
validator: {
validate(value: any) {
validate(value: string | Record<string, string>): boolean {
if (typeof value === "string") {
return value.trim().length > 0;
}
@@ -226,4 +227,16 @@ export class CreateBookingInput_2024_04_15 {
@IsOptional()
@ApiPropertyOptional()
crmOwnerRecordType?: string;
/* @ApiPropertyOptional({
type: [Number],
description:
"For round robin event types, filter available hosts to only consider the specified subset of host user IDs. This allows you to book with specific hosts within a round robin event type.",
example: [1, 2, 3],
}) */
@ApiHideProperty()
@IsOptional()
@IsArray()
@IsInt({ each: true })
rrHostSubsetIds?: number[];
}
@@ -397,18 +397,18 @@ export class BookingsController_2024_08_13 {
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
`,
})
async markNoShow(
@Param("bookingUid") bookingUid: string,
@Body() body: MarkAbsentBookingInput_2024_08_13,
@GetUser("id") ownerId: number
): Promise<MarkAbsentBookingOutput_2024_08_13> {
const booking = await this.bookingsService.markAbsent(bookingUid, ownerId, body);
async markNoShow(
@Param("bookingUid") bookingUid: string,
@Body() body: MarkAbsentBookingInput_2024_08_13,
@GetUser() user: ApiAuthGuardUser
): Promise<MarkAbsentBookingOutput_2024_08_13> {
const booking = await this.bookingsService.markAbsent(bookingUid, user.id, body, user.uuid);
return {
status: SUCCESS_STATUS,
data: booking,
};
}
return {
status: SUCCESS_STATUS,
data: booking,
};
}
@Post("/:bookingUid/reassign")
@HttpCode(HttpStatus.OK)
@@ -64,12 +64,14 @@ describe("Bookings Endpoints 2024-08-13", () => {
let team1EventTypeId: number;
let team2EventTypeId: number;
let team2RREventTypeId: number;
let phoneOnlyEventTypeId: number;
let collectiveEventWithoutHostsId: number;
let roundRobinEventWithoutHostsId: number;
const team1EventTypeSlug = `team-bookings-event-type-${randomString()}`;
const team2EventTypeSlug = `team-bookings-event-type-${randomString()}`;
const team2RREventTypeSlug = `team-bookings-rr-event-type-${randomString()}`;
const phoneOnlyEventTypeSlug = `team-bookings-event-type-${randomString()}`;
let phoneBasedBooking: BookingOutput_2024_08_13;
@@ -339,6 +341,50 @@ describe("Bookings Endpoints 2024-08-13", () => {
team2EventTypeId = team2EventType.id;
const team2RREventType = await eventTypesRepositoryFixture.createTeamEventType({
schedulingType: "ROUND_ROBIN",
team: {
connect: { id: team2.id },
},
title: `team-bookings-2024-08-13-event-type-rr-${randomString()}`,
slug: team2RREventTypeSlug,
length: 60,
assignAllTeamMembers: true,
bookingFields: [],
locations: [],
rrHostSubsetEnabled: true,
});
team2RREventTypeId = team2RREventType.id;
await hostsRepositoryFixture.create({
isFixed: false,
user: {
connect: {
id: teamUser2.id,
},
},
eventType: {
connect: {
id: team2RREventType.id,
},
},
});
await hostsRepositoryFixture.create({
isFixed: true,
user: {
connect: {
id: teamUser.id,
},
},
eventType: {
connect: {
id: team2RREventType.id,
},
},
});
await hostsRepositoryFixture.create({
isFixed: true,
user: {
@@ -603,6 +649,163 @@ describe("Bookings Endpoints 2024-08-13", () => {
}
});
});
it("should create a team 2 RR booking and use rrHostSubsetIds to force teamUser2 as host ", async () => {
const body: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 0, 8, 12, 0, 0)).toISOString(),
eventTypeId: team2RREventTypeId,
attendee: {
name: "bob2",
email: "bob2@gmail.com",
timeZone: "Europe/Rome",
language: "it",
},
meetingUrl: "https://meet.google.com/abc-def-ghi",
rrHostSubsetIds: [teamUser2.id],
};
return request(app.getHttpServer())
.post("/v2/bookings")
.send(body)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201)
.then(async (response) => {
const responseBody: CreateBookingOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
expect(responseDataIsBooking(responseBody.data)).toBe(true);
if (responseDataIsBooking(responseBody.data)) {
const data: BookingOutput_2024_08_13 = responseBody.data;
expect(data.id).toBeDefined();
expect(data.uid).toBeDefined();
expect(data.hosts.length).toEqual(1);
expect(data.hosts[0].id).toEqual(teamUser2.id);
expect(data.status).toEqual("accepted");
expect(data.start).toEqual(body.start);
expect(data.end).toEqual(new Date(Date.UTC(2030, 0, 8, 13, 0, 0)).toISOString());
expect(data.duration).toEqual(60);
expect(data.eventTypeId).toEqual(team2RREventTypeId);
expect(data.attendees.length).toEqual(1);
expect(data.attendees[0]).toEqual({
name: body.attendee.name,
email: body.attendee.email,
timeZone: body.attendee.timeZone,
language: body.attendee.language,
absent: false,
});
expect(data.meetingUrl).toEqual(body.meetingUrl);
expect(data.absentHost).toEqual(false);
} else {
throw new Error(
"Invalid response data - expected booking but received array of possibly recurring bookings"
);
}
});
});
it("should create a team 2 RR booking and use rrHostSubsetIds to force teamUser as host ", async () => {
const body: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 0, 8, 12, 0, 0)).toISOString(),
eventTypeId: team2RREventTypeId,
attendee: {
name: "bob",
email: "bob@gmail.com",
timeZone: "Europe/Rome",
language: "it",
},
meetingUrl: "https://meet.google.com/abc-def-ghi",
rrHostSubsetIds: [teamUser.id],
};
return request(app.getHttpServer())
.post("/v2/bookings")
.send(body)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201)
.then(async (response) => {
const responseBody: CreateBookingOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
expect(responseDataIsBooking(responseBody.data)).toBe(true);
if (responseDataIsBooking(responseBody.data)) {
const data: BookingOutput_2024_08_13 = responseBody.data;
expect(data.id).toBeDefined();
expect(data.uid).toBeDefined();
expect(data.hosts.length).toEqual(1);
expect(data.hosts[0].id).toEqual(teamUser.id);
expect(data.status).toEqual("accepted");
expect(data.start).toEqual(body.start);
expect(data.end).toEqual(new Date(Date.UTC(2030, 0, 8, 13, 0, 0)).toISOString());
expect(data.duration).toEqual(60);
expect(data.eventTypeId).toEqual(team2RREventTypeId);
expect(data.attendees.length).toEqual(1);
expect(data.attendees[0]).toEqual({
name: body.attendee.name,
email: body.attendee.email,
timeZone: body.attendee.timeZone,
language: body.attendee.language,
absent: false,
});
expect(data.meetingUrl).toEqual(body.meetingUrl);
expect(data.absentHost).toEqual(false);
} else {
throw new Error(
"Invalid response data - expected booking but received array of possibly recurring bookings"
);
}
});
});
it("should create a team 2 RR booking and use rrHostSubsetIds to force teamUser and teamUser2 as host ", async () => {
const body: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 0, 8, 14, 0, 0)).toISOString(),
eventTypeId: team2RREventTypeId,
attendee: {
name: "bob",
email: "bob@gmail.com",
timeZone: "Europe/Rome",
language: "it",
},
meetingUrl: "https://meet.google.com/abc-def-ghi",
rrHostSubsetIds: [teamUser.id, teamUser2.id],
};
return request(app.getHttpServer())
.post("/v2/bookings")
.send(body)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201)
.then(async (response) => {
const responseBody: CreateBookingOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
expect(responseDataIsBooking(responseBody.data)).toBe(true);
if (responseDataIsBooking(responseBody.data)) {
const data: BookingOutput_2024_08_13 = responseBody.data;
expect(data.id).toBeDefined();
expect(data.uid).toBeDefined();
expect(data.hosts.length).toEqual(1);
expect(data.hosts[0].id).toEqual(teamUser.id);
expect(data.status).toEqual("accepted");
expect(data.start).toEqual(body.start);
expect(data.end).toEqual(new Date(Date.UTC(2030, 0, 8, 15, 0, 0)).toISOString());
expect(data.duration).toEqual(60);
expect(data.eventTypeId).toEqual(team2RREventTypeId);
expect(data.attendees.length).toEqual(2);
expect(data.attendees.find((a) => a.email === body.attendee.email)).toBeDefined();
expect(data.attendees.find((a) => a.email === teamUser2.email)).toBeDefined();
expect(data.meetingUrl).toEqual(body.meetingUrl);
expect(data.absentHost).toEqual(false);
} else {
throw new Error(
"Invalid response data - expected booking but received array of possibly recurring bookings"
);
}
});
});
});
describe("get team bookings", () => {
@@ -639,7 +842,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
| RecurringBookingOutput_2024_08_13
| GetSeatedBookingOutput_2024_08_13
)[] = responseBody.data;
expect(data.length).toEqual(1);
expect(data.length).toEqual(3);
expect(data[0].eventTypeId).toEqual(team2EventTypeId);
});
});
@@ -684,7 +887,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
| RecurringBookingOutput_2024_08_13
| GetSeatedBookingOutput_2024_08_13
)[] = responseBody.data;
expect(data.length).toEqual(3);
expect(data.length).toEqual(5);
expect(data.find((booking) => booking.eventTypeId === team1EventTypeId)).toBeDefined();
expect(data.find((booking) => booking.eventTypeId === team2EventTypeId)).toBeDefined();
});
@@ -845,6 +1048,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
await userRepositoryFixture.deleteByEmail(teamUser.email);
await userRepositoryFixture.deleteByEmail(teamUserEmail2);
await bookingsRepositoryFixture.deleteAllBookings(teamUser.id, teamUser.email);
await bookingsRepositoryFixture.deleteAllBookings(teamUser2.id, teamUser2.email);
await app.close();
});
});
@@ -919,34 +919,40 @@ export class BookingsService_2024_08_13 {
return await this.getBooking(recurringBookingUid, authUser);
}
async markAbsent(bookingUid: string, bookingOwnerId: number, body: MarkAbsentBookingInput_2024_08_13) {
const bodyTransformed = this.inputService.transformInputMarkAbsentBooking(body);
const bookingBefore = await this.bookingsRepository.getByUid(bookingUid);
async markAbsent(
bookingUid: string,
bookingOwnerId: number,
body: MarkAbsentBookingInput_2024_08_13,
userUuid?: string
) {
const bodyTransformed = this.inputService.transformInputMarkAbsentBooking(body);
const bookingBefore = await this.bookingsRepository.getByUid(bookingUid);
if (!bookingBefore) {
throw new NotFoundException(`Booking with uid=${bookingUid} not found.`);
}
if (!bookingBefore) {
throw new NotFoundException(`Booking with uid=${bookingUid} not found.`);
}
const nowUtc = DateTime.utc();
const bookingStartTimeUtc = DateTime.fromJSDate(bookingBefore.startTime, { zone: "utc" });
const nowUtc = DateTime.utc();
const bookingStartTimeUtc = DateTime.fromJSDate(bookingBefore.startTime, { zone: "utc" });
if (nowUtc < bookingStartTimeUtc) {
throw new BadRequestException(
`Bookings can only be marked as absent after their scheduled start time. Current time in UTC+0: ${nowUtc.toISO()}, Booking start time in UTC+0: ${bookingStartTimeUtc.toISO()}`
);
}
if (nowUtc < bookingStartTimeUtc) {
throw new BadRequestException(
`Bookings can only be marked as absent after their scheduled start time. Current time in UTC+0: ${nowUtc.toISO()}, Booking start time in UTC+0: ${bookingStartTimeUtc.toISO()}`
);
}
const platformClientParams = bookingBefore?.eventTypeId
? await this.platformBookingsService.getOAuthClientParams(bookingBefore.eventTypeId)
: undefined;
const platformClientParams = bookingBefore?.eventTypeId
? await this.platformBookingsService.getOAuthClientParams(bookingBefore.eventTypeId)
: undefined;
await handleMarkNoShow({
bookingUid,
attendees: bodyTransformed.attendees,
noShowHost: bodyTransformed.noShowHost,
userId: bookingOwnerId,
platformClientParams,
});
await handleMarkNoShow({
bookingUid,
attendees: bodyTransformed.attendees,
noShowHost: bodyTransformed.noShowHost,
userId: bookingOwnerId,
userUuid,
platformClientParams,
});
const booking = await this.bookingsRepository.getByUidWithAttendeesAndUserAndEvent(bookingUid);
@@ -188,6 +188,7 @@ export class InputBookingsService_2024_08_13 {
location,
},
...this.getRoutingFormData(inputBooking.routing),
rrHostSubsetIds: inputBooking.rrHostSubsetIds,
};
}
@@ -484,6 +485,7 @@ export class InputBookingsService_2024_08_13 {
},
schedulingType: eventType.schedulingType,
...this.getRoutingFormData(inputBooking.routing),
rrHostSubsetIds: inputBooking.rrHostSubsetIds,
});
switch (timeBetween) {
@@ -1486,6 +1486,7 @@ describe("Event types Endpoints", () => {
locations: [],
schedulingType: "COLLECTIVE",
team: { connect: { id: team.id } },
rrHostSubsetEnabled: true,
});
return request(app.getHttpServer())
@@ -1498,6 +1499,7 @@ describe("Event types Endpoints", () => {
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data.id).toEqual(teamEventType.id);
expect(responseBody.data.teamId).toEqual(team.id);
expect(responseBody.data.rrHostSubsetEnabled).toEqual(true);
await teamRepositoryFixture.delete(team.id);
});
});
@@ -27,6 +27,7 @@ import {
import { UserWithProfile } from "@/modules/users/users.repository";
import { Injectable, BadRequestException } from "@nestjs/common";
import { slugifyLenient } from "@calcom/platform-libraries";
import { getApps, getUsersCredentialsIncludeServiceAccountKey } from "@calcom/platform-libraries/app-store";
import {
validateCustomEventName,
@@ -129,6 +130,7 @@ export class InputEventTypesService_2024_06_14 {
useDestinationCalendarEmail,
disableGuests,
bookerActiveBookingsLimit,
slug,
...rest
} = inputEventType;
const confirmationPolicyTransformed = this.transformInputConfirmationPolicy(confirmationPolicy);
@@ -144,6 +146,8 @@ export class InputEventTypesService_2024_06_14 {
? this.transformInputBookerActiveBookingsLimit(bookerActiveBookingsLimit)
: {};
const slugifiedSlug = slugifyLenient(slug);
const metadata: EventTypeMetadata = {
bookerLayouts: this.transformInputBookerLayouts(bookerLayouts),
requiresConfirmationThreshold:
@@ -153,6 +157,7 @@ export class InputEventTypesService_2024_06_14 {
const eventType = {
...rest,
slug: slugifiedSlug,
length: lengthInMinutes,
locations: locationsTransformed,
bookingFields: this.transformInputBookingFields(effectiveBookingFields),
@@ -209,6 +214,7 @@ export class InputEventTypesService_2024_06_14 {
useDestinationCalendarEmail,
disableGuests,
bookerActiveBookingsLimit,
slug,
...rest
} = inputEventType;
const eventTypeDb = await this.eventTypesRepository.getEventTypeWithMetaData(eventTypeId);
@@ -229,14 +235,21 @@ export class InputEventTypesService_2024_06_14 {
const metadata: EventTypeMetadata = {
...metadataTransformed,
bookerLayouts: this.transformInputBookerLayouts(bookerLayouts),
requiresConfirmationThreshold:
confirmationPolicyTransformed?.requiresConfirmationThreshold ?? undefined,
multipleDuration: lengthInMinutesOptions,
...(bookerLayouts !== undefined
? { bookerLayouts: this.transformInputBookerLayouts(bookerLayouts) }
: {}),
...(confirmationPolicy !== undefined
? {
requiresConfirmationThreshold:
confirmationPolicyTransformed?.requiresConfirmationThreshold ?? undefined,
}
: {}),
...(lengthInMinutesOptions !== undefined ? { multipleDuration: lengthInMinutesOptions } : {}),
};
const eventType = {
...rest,
...(slug ? { slug: slugifyLenient(slug) } : {}),
length: lengthInMinutes,
locations: locations ? this.transformInputLocations(locations) : undefined,
bookingFields: effectiveBookingFields
@@ -1,6 +1,7 @@
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 { PrismaScheduleRepository } from "@/lib/repositories/prisma-schedule.repository";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { UsersModule } from "@/modules/users/users.module";
@@ -8,7 +9,7 @@ import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule, UsersModule, TokensModule],
providers: [SchedulesRepository_2024_04_15, SchedulesService_2024_04_15],
providers: [SchedulesRepository_2024_04_15, SchedulesService_2024_04_15, PrismaScheduleRepository],
controllers: [SchedulesController_2024_04_15],
exports: [SchedulesService_2024_04_15, SchedulesRepository_2024_04_15],
})
@@ -1,12 +1,12 @@
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 { SchedulesRepository_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.repository";
import { PrismaScheduleRepository } from "@/lib/repositories/prisma-schedule.repository";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { UserWithProfile, UsersRepository } from "@/modules/users/users.repository";
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
import { updateSchedule } from "@calcom/platform-libraries/schedules";
import { ScheduleRepository } from "@calcom/platform-libraries/schedules";
import type { UpdateScheduleInput_2024_04_15 } from "@calcom/platform-types";
import type { PrismaClient } from "@calcom/prisma";
import type { Schedule } from "@calcom/prisma/client";
@@ -16,7 +16,8 @@ export class SchedulesService_2024_04_15 {
constructor(
private readonly schedulesRepository: SchedulesRepository_2024_04_15,
private readonly usersRepository: UsersRepository,
private readonly dbWrite: PrismaWriteService
private readonly dbWrite: PrismaWriteService,
private readonly prismaScheduleRepository: PrismaScheduleRepository
) {}
async createUserDefaultSchedule(userId: number, timeZone: string) {
@@ -53,8 +54,7 @@ export class SchedulesService_2024_04_15 {
const user = await this.usersRepository.findById(userId);
if (!user?.defaultScheduleId) return null;
return await ScheduleRepository.findDetailedScheduleById({
return await this.prismaScheduleRepository.findDetailedScheduleById({
scheduleId: user.defaultScheduleId,
isManagedEventType: undefined,
userId,
@@ -70,7 +70,7 @@ export class SchedulesService_2024_04_15 {
throw new NotFoundException(`User with ID=${userId} does not exist.`);
}
const existingSchedule = await ScheduleRepository.findDetailedScheduleById({
const existingSchedule = await this.prismaScheduleRepository.findDetailedScheduleById({
scheduleId: scheduleId,
isManagedEventType: undefined,
userId,
@@ -88,7 +88,11 @@ export class SchedulesService_2024_04_15 {
}
async getUserSchedules(userId: number, timeZone: string, defaultScheduleId: number | null) {
return ScheduleRepository.findManyDetailedScheduleByUserId({ userId, timeZone, defaultScheduleId });
return this.prismaScheduleRepository.findManyDetailedScheduleByUserId({
userId,
timeZone,
defaultScheduleId,
});
}
async updateUserSchedule(
@@ -1,6 +1,7 @@
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
import { PrismaEventTypeRepository } from "@/lib/repositories/prisma-event-type.repository";
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
import { PrismaHolidayRepository } from "@/lib/repositories/prisma-holiday.repository";
import { PrismaMembershipRepository } from "@/lib/repositories/prisma-membership.repository";
import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";
import { PrismaRoutingFormResponseRepository } from "@/lib/repositories/prisma-routing-form-response.repository";
@@ -23,6 +24,7 @@ import { Module } from "@nestjs/common";
imports: [PrismaWorkerModule],
providers: [
PrismaOOORepository,
PrismaHolidayRepository,
PrismaScheduleRepository,
PrismaBookingRepository,
PrismaSelectedSlotRepository,
@@ -5,6 +5,7 @@ import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.rep
import { PrismaHostRepository } from "@/lib/repositories/prisma-host.repository";
import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
import { BookingAuditProducerService } from "@/lib/services/booking-audit-producer.service";
import { BookingEmailSmsService } from "@/lib/services/booking-emails-sms-service";
import { BookingEventHandlerService } from "@/lib/services/booking-event-handler.service";
import { CheckBookingAndDurationLimitsService } from "@/lib/services/check-booking-and-duration-limits.service";
@@ -16,6 +17,7 @@ import { BookingEmailAndSmsSyncTaskerService } from "@/lib/services/tasker/booki
import { BookingEmailAndSmsTaskService } from "@/lib/services/tasker/booking-emails-sms-task.service";
import { BookingEmailAndSmsTasker } from "@/lib/services/tasker/booking-emails-sms-tasker.service";
import { BookingEmailAndSmsTriggerTaskerService } from "@/lib/services/tasker/booking-emails-sms-trigger-tasker.service";
import { TaskerService } from "@/lib/services/tasker.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { Module, Scope } from "@nestjs/common";
@@ -35,6 +37,7 @@ import { Module, Scope } from "@nestjs/common";
},
scope: Scope.TRANSIENT,
},
BookingAuditProducerService,
BookingEventHandlerService,
CheckBookingAndDurationLimitsService,
CheckBookingLimitsService,
@@ -45,6 +48,7 @@ import { Module, Scope } from "@nestjs/common";
BookingEmailAndSmsSyncTaskerService,
BookingEmailAndSmsTriggerTaskerService,
BookingEmailAndSmsTasker,
TaskerService,
RegularBookingService,
],
exports: [RegularBookingService],
@@ -0,0 +1,13 @@
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { PrismaHolidayRepository as PrismaHolidayRepositoryLib } from "@calcom/platform-libraries/repositories";
import type { PrismaClient } from "@calcom/prisma";
@Injectable()
export class PrismaHolidayRepository extends PrismaHolidayRepositoryLib {
constructor(private readonly dbWrite: PrismaWriteService) {
super(dbWrite.prisma as unknown as PrismaClient);
}
}
@@ -0,0 +1,16 @@
import { TaskerService } from "@/lib/services/tasker.service";
import { Logger } from "@/lib/logger.bridge";
import { Injectable } from "@nestjs/common";
import { BookingAuditTaskerProducerService, getAuditActorRepository } from "@calcom/platform-libraries/bookings";
@Injectable()
export class BookingAuditProducerService extends BookingAuditTaskerProducerService {
constructor(taskerService: TaskerService, bridgeLogger: Logger) {
super({
tasker: taskerService.getTasker(),
log: bridgeLogger,
auditActorRepository: getAuditActorRepository(),
});
}
}
@@ -4,14 +4,20 @@ import { BookingEventHandlerService as BaseBookingEventHandlerService } from "@c
import { Logger } from "@/lib/logger.bridge";
import { BookingAuditProducerService } from "./booking-audit-producer.service";
import { HashedLinkService } from "./hashed-link.service";
@Injectable()
export class BookingEventHandlerService extends BaseBookingEventHandlerService {
constructor(hashedLinkService: HashedLinkService, bridgeLogger: Logger) {
constructor(
hashedLinkService: HashedLinkService,
bridgeLogger: Logger,
bookingAuditProducerService: BookingAuditProducerService
) {
super({
log: bridgeLogger,
hashedLinkService,
bookingAuditProducerService,
});
}
}
@@ -0,0 +1,18 @@
import { Injectable } from "@nestjs/common";
import { getTasker, type Tasker } from "@calcom/platform-libraries";
@Injectable()
export class TaskerService {
private readonly tasker: Tasker;
constructor() {
this.tasker = getTasker();
}
getTasker(): Tasker {
return this.tasker;
}
}
@@ -1,5 +1,6 @@
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
import { PrismaEventTypeRepository } from "@/lib/repositories/prisma-event-type.repository";
import { PrismaHolidayRepository } from "@/lib/repositories/prisma-holiday.repository";
import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";
import { RedisService } from "@/modules/redis/redis.service";
import { Injectable } from "@nestjs/common";
@@ -12,13 +13,15 @@ export class UserAvailabilityService extends BaseUserAvailabilityService {
oooRepoDependency: PrismaOOORepository,
bookingRepository: PrismaBookingRepository,
eventTypeRepository: PrismaEventTypeRepository,
redisService: RedisService
redisService: RedisService,
holidayRepository: PrismaHolidayRepository
) {
super({
oooRepo: oooRepoDependency,
bookingRepo: bookingRepository,
eventTypeRepo: eventTypeRepository,
redisClient: redisService,
holidayRepo: holidayRepository,
});
}
}
@@ -32,8 +32,8 @@ export class SchedulesAtomsService {
const user = await this.usersRepository.findById(userId);
if (!user?.defaultScheduleId) return null;
return await ScheduleRepository.findDetailedScheduleById({
const scheduleRepo = new ScheduleRepository(this.dbWrite.prisma as unknown as PrismaClient);
return await scheduleRepo.findDetailedScheduleById({
scheduleId: scheduleId ?? user.defaultScheduleId,
isManagedEventType,
userId,
@@ -389,6 +389,7 @@ describe("Organizations Event Types Endpoints", () => {
expect(data.hideOrganizerEmail).toEqual(body.hideOrganizerEmail);
expect(data.lockTimeZoneToggleOnBookingPage).toEqual(body.lockTimeZoneToggleOnBookingPage);
expect(data.color).toEqual(body.color);
expect(data.rrHostSubsetEnabled).toEqual(false);
expect(data.successRedirectUrl).toEqual("https://masterchief.com/argentina/flan/video/1234");
expect(data.emailSettings).toEqual(body.emailSettings);
collectiveEventType = responseBody.data;
@@ -537,6 +538,7 @@ describe("Organizations Event Types Endpoints", () => {
const data = responseBody.data;
expect(data.title).toEqual(collectiveEventType.title);
expect(data.hosts.length).toEqual(2);
expect(data.rrHostSubsetEnabled).toEqual(false);
evaluateHost(collectiveEventType.hosts[0], data.hosts[0]);
evaluateHost(collectiveEventType.hosts[1], data.hosts[1]);
@@ -1142,6 +1144,7 @@ describe("Organizations Event Types Endpoints", () => {
hideCalendarEventDetails: true,
hideOrganizerEmail: true,
lockTimeZoneToggleOnBookingPage: true,
rrHostSubsetEnabled: true,
color: {
darkThemeHex: "#292929",
lightThemeHex: "#fafafa",
@@ -1175,6 +1178,7 @@ describe("Organizations Event Types Endpoints", () => {
expect(data.hideOrganizerEmail).toEqual(body.hideOrganizerEmail);
expect(data.lockTimeZoneToggleOnBookingPage).toEqual(body.lockTimeZoneToggleOnBookingPage);
expect(data.color).toEqual(body.color);
expect(data.rrHostSubsetEnabled).toEqual(true);
expect(data.successRedirectUrl).toEqual("https://masterchief.com/argentina/flan/video/1234");
collectiveEventType = responseBody.data;
});
@@ -1294,6 +1298,80 @@ describe("Organizations Event Types Endpoints", () => {
expect(updatedEventType.bookingRequiresAuthentication).toEqual(false);
});
it("should preserve metadata fields when doing partial update", async () => {
const createBody: CreateTeamEventTypeInput_2024_06_14 = {
title: "Coding consultation with metadata",
slug: `organizations-event-types-metadata-${randomString()}`,
description: "Our team will review your codebase.",
lengthInMinutes: 30,
lengthInMinutesOptions: [15, 30, 60],
locations: [
{
type: "integration",
integration: "cal-video",
},
],
schedulingType: "COLLECTIVE",
hosts: [
{
userId: teammate1.id,
},
],
bookerLayouts: {
enabledLayouts: [
BookerLayoutsInputEnum_2024_06_14.column,
BookerLayoutsInputEnum_2024_06_14.month,
BookerLayoutsInputEnum_2024_06_14.week,
],
defaultLayout: BookerLayoutsInputEnum_2024_06_14.month,
},
confirmationPolicy: {
type: ConfirmationPolicyEnum.TIME,
noticeThreshold: {
count: 60,
unit: NoticeThresholdUnitEnum.MINUTES,
},
blockUnconfirmedBookingsInBooker: true,
},
};
const createResponse = await request(app.getHttpServer())
.post(`/v2/organizations/${org.id}/teams/${team.id}/event-types`)
.send(createBody)
.expect(201);
const createdEventType: TeamEventTypeOutput_2024_06_14 = createResponse.body.data;
// Verify all metadata fields are set correctly on creation
expect(createdEventType.lengthInMinutesOptions).toBeDefined();
expect(createdEventType.lengthInMinutesOptions).toEqual([15, 30, 60]);
expect(createdEventType.bookerLayouts).toBeDefined();
expect(createdEventType.bookerLayouts).toEqual(createBody.bookerLayouts);
expect(createdEventType.confirmationPolicy).toBeDefined();
expect(createdEventType.confirmationPolicy).toEqual(createBody.confirmationPolicy);
// Now do a partial update that only changes a different field (not metadata fields)
const updateBody: UpdateTeamEventTypeInput_2024_06_14 = {
bookingRequiresAuthentication: false,
};
const updateResponse = await request(app.getHttpServer())
.patch(`/v2/organizations/${org.id}/teams/${team.id}/event-types/${createdEventType.id}`)
.send(updateBody)
.expect(200);
const updatedEventType: TeamEventTypeOutput_2024_06_14 = updateResponse.body.data;
// Verify that all metadata fields are preserved and not reset to undefined
expect(updatedEventType.lengthInMinutesOptions).toBeDefined();
expect(updatedEventType.lengthInMinutesOptions).toEqual([15, 30, 60]);
expect(updatedEventType.bookerLayouts).toBeDefined();
expect(updatedEventType.bookerLayouts).toEqual(createBody.bookerLayouts);
expect(updatedEventType.confirmationPolicy).toBeDefined();
expect(updatedEventType.confirmationPolicy).toEqual(createBody.confirmationPolicy);
expect(updatedEventType.bookingRequiresAuthentication).toEqual(false);
});
function evaluateHost(expected: Host, received: Host | undefined) {
expect(expected.userId).toEqual(received?.userId);
expect(expected.mandatory).toEqual(received?.mandatory);
@@ -8,6 +8,7 @@ import { UsersRepository } from "@/modules/users/users.repository";
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
import { SchedulingType } from "@calcom/platform-libraries";
import { slugifyLenient } from "@calcom/platform-libraries";
import { EventTypeMetadata } from "@calcom/platform-libraries/event-types";
import {
CreateTeamEventTypeInput_2024_06_14,
@@ -42,11 +43,13 @@ export class InputOrganizationsEventTypesService {
teamId: number,
inputEventType: CreateTeamEventTypeInput_2024_06_14
) {
const slugifiedInputEventType = { ...inputEventType, slug: slugifyLenient(inputEventType.slug) };
await this.validateInputLocations(teamId, inputEventType.locations);
await this.validateHosts(teamId, inputEventType.hosts);
await this.validateTeamEventTypeSlug(teamId, inputEventType.slug);
await this.validateTeamEventTypeSlug(teamId, slugifiedInputEventType.slug);
const transformedBody = await this.transformInputCreateTeamEventType(teamId, inputEventType);
const transformedBody = await this.transformInputCreateTeamEventType(teamId, slugifiedInputEventType);
await this.inputEventTypesService.validateEventTypeInputs({
seatsPerTimeSlot: transformedBody.seatsPerTimeSlot,
@@ -75,13 +78,21 @@ export class InputOrganizationsEventTypesService {
teamId: number,
inputEventType: UpdateTeamEventTypeInput_2024_06_14
) {
const slugifiedInputEventType = inputEventType.slug
? { ...inputEventType, slug: slugifyLenient(inputEventType.slug) }
: inputEventType;
await this.validateInputLocations(teamId, inputEventType.locations);
await this.validateHosts(teamId, inputEventType.hosts);
if (inputEventType.slug) {
await this.validateTeamEventTypeSlug(teamId, inputEventType.slug);
if (slugifiedInputEventType.slug) {
await this.validateTeamEventTypeSlug(teamId, slugifiedInputEventType.slug);
}
const transformedBody = await this.transformInputUpdateTeamEventType(eventTypeId, teamId, inputEventType);
const transformedBody = await this.transformInputUpdateTeamEventType(
eventTypeId,
teamId,
slugifiedInputEventType
);
await this.inputEventTypesService.validateEventTypeInputs({
eventTypeId: eventTypeId,
@@ -88,6 +88,7 @@ type Input = Pick<
| "rescheduleWithSameRoundRobinHost"
| "maxActiveBookingPerBookerOfferReschedule"
| "maxActiveBookingsPerBooker"
| "rrHostSubsetEnabled"
>;
@Injectable()
@@ -103,8 +104,14 @@ export class OutputOrganizationsEventTypesService {
const emailSettings = this.transformEmailSettings(metadata);
const { teamId, userId, parentId, assignAllTeamMembers, rescheduleWithSameRoundRobinHost } =
databaseEventType;
const {
teamId,
userId,
parentId,
assignAllTeamMembers,
rescheduleWithSameRoundRobinHost,
rrHostSubsetEnabled,
} = databaseEventType;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { ownerId, users, ...rest } = this.outputEventTypesService.getResponseEventType(
0,
@@ -139,6 +146,7 @@ export class OutputOrganizationsEventTypesService {
theme: databaseEventType?.team?.theme,
},
rescheduleWithSameRoundRobinHost,
rrHostSubsetEnabled,
};
}
@@ -112,7 +112,7 @@ describe("Organizations Roles Endpoints", () => {
});
await featuresRepositoryFixture.create({ slug: "pbac", enabled: true });
await featuresRepositoryFixture.enableFeatureForTeam(pbacEnabledOrganization.id, "pbac");
await featuresRepositoryFixture.setTeamFeatureState(pbacEnabledOrganization.id, "pbac", "enabled");
// Create memberships
await membershipRepositoryFixture.create({
@@ -58,7 +58,7 @@ describe("Organizations Roles Permissions Endpoints", () => {
});
await featuresRepositoryFixture.create({ slug: "pbac", enabled: true });
await featuresRepositoryFixture.enableFeatureForTeam(pbacEnabledOrganization.id, "pbac");
await featuresRepositoryFixture.setTeamFeatureState(pbacEnabledOrganization.id, "pbac", "enabled");
// Create user + membership in org
pbacOrgUserWithRolePermission = await userRepositoryFixture.create({
@@ -126,7 +126,7 @@ describe("Organizations Roles Endpoints", () => {
});
await featuresRepositoryFixture.create({ slug: "pbac", enabled: true });
await featuresRepositoryFixture.enableFeatureForTeam(pbacEnabledTeam.id, "pbac");
await featuresRepositoryFixture.setTeamFeatureState(pbacEnabledTeam.id, "pbac", "enabled");
// Create memberships
await membershipRepositoryFixture.create({
@@ -67,7 +67,7 @@ describe("Organizations Teams Roles Permissions Endpoints", () => {
});
await featuresRepositoryFixture.create({ slug: "pbac", enabled: true });
await featuresRepositoryFixture.enableFeatureForTeam(pbacEnabledTeam.id, "pbac");
await featuresRepositoryFixture.setTeamFeatureState(pbacEnabledTeam.id, "pbac", "enabled");
// Create user + membership in org
pbacOrgUserWithRolePermission = await userRepositoryFixture.create({
@@ -53,6 +53,7 @@ describe("Slots 2024-09-04 Endpoints", () => {
const teammateEmailOne = `slots-2024-09-04-user-1-team-slots-${randomString()}`;
let teammateApiKeyString: string;
const teammateEmailTwo = `slots-2024-09-04-user-2-team-slots-${randomString()}`;
const teammateEmailThree = `slots-2024-09-04-user-3-team-slots-${randomString()}`;
let teammateTwoApiKeyString: string;
const outsiderEmail = `slots-2024-09-04-unrelated-team-slots-${randomString()}`;
@@ -63,6 +64,7 @@ describe("Slots 2024-09-04 Endpoints", () => {
let team: Team;
let teammateOne: User;
let teammateTwo: User;
let teammateThree: User;
let collectiveEventTypeId: number;
let collectiveEventTypeSlug: string;
let collectiveEventTypeWithoutHostsId: number;
@@ -114,6 +116,12 @@ describe("Slots 2024-09-04 Endpoints", () => {
username: teammateEmailTwo,
});
teammateThree = await userRepositoryFixture.create({
email: teammateEmailThree,
name: teammateEmailThree,
username: teammateEmailThree,
});
outsider = await userRepositoryFixture.create({
email: outsiderEmail,
name: outsiderEmail,
@@ -155,6 +163,13 @@ describe("Slots 2024-09-04 Endpoints", () => {
accepted: true,
});
await membershipsRepositoryFixture.create({
role: "MEMBER",
user: { connect: { id: teammateThree.id } },
team: { connect: { id: team.id } },
accepted: true,
});
const collectiveEventType = await eventTypesRepositoryFixture.createTeamEventType({
schedulingType: "COLLECTIVE",
team: {
@@ -243,7 +258,7 @@ describe("Slots 2024-09-04 Endpoints", () => {
bookingFields: [],
locations: [],
users: {
connect: [{ id: teammateOne.id }, { id: teammateTwo.id }],
connect: [{ id: teammateOne.id }, { id: teammateTwo.id }, { id: teammateThree.id }],
},
hosts: {
create: [
@@ -255,8 +270,13 @@ describe("Slots 2024-09-04 Endpoints", () => {
userId: teammateTwo.id,
isFixed: false,
},
{
userId: teammateThree.id,
isFixed: false,
},
],
},
rrHostSubsetEnabled: true,
});
roundRobinEventTypeWithoutFixedHostsId = roundRobinEventTypeWithoutFixedHosts.id;
@@ -274,7 +294,7 @@ describe("Slots 2024-09-04 Endpoints", () => {
bookingFields: [],
locations: [],
users: {
connect: [{ id: teammateOne.id }, { id: teammateTwo.id }],
connect: [{ id: teammateOne.id }, { id: teammateTwo.id }, { id: teammateThree.id }],
},
hosts: {
create: [
@@ -286,8 +306,13 @@ describe("Slots 2024-09-04 Endpoints", () => {
userId: teammateTwo.id,
isFixed: false,
},
{
userId: teammateThree.id,
isFixed: false,
},
],
},
rrHostSubsetEnabled: true,
});
roundRobinEventTypeWithFixedAndNonFixedHostsId = roundRobinEventTypeWithFixedAndNonFixedHosts.id;
@@ -301,6 +326,17 @@ describe("Slots 2024-09-04 Endpoints", () => {
await schedulesService.createUserSchedule(teammateOne.id, userSchedule);
await schedulesService.createUserSchedule(teammateTwo.id, userSchedule);
await schedulesService.createUserSchedule(teammateThree.id, {
...userSchedule,
availability: [
{
days: ["Monday", "Friday"],
startTime: "09:00",
endTime: "17:00",
},
],
});
app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication);
@@ -360,6 +396,79 @@ describe("Slots 2024-09-04 Endpoints", () => {
});
});
it("should get round robin team event without fixed hosts slots in UTC with subsetIds for teammateThree who has a smaller schedule", async () => {
return request(app.getHttpServer())
.get(
`/v2/slots?eventTypeId=${roundRobinEventTypeWithoutFixedHostsId}&start=2050-09-05&end=2050-09-09&rrHostSubsetIds[]=${teammateThree.id}`
)
.set(CAL_API_VERSION_HEADER, VERSION_2024_09_04)
.expect(200)
.then(async (response) => {
const responseBody: GetSlotsOutput_2024_09_04 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const slots = responseBody.data;
expect(slots).toBeDefined();
const days = Object.keys(slots);
expect(days.length).toEqual(2);
});
});
it("should get round robin team event without fixed hosts slots in UTC with subsetIds for teammateOne", async () => {
return request(app.getHttpServer())
.get(
`/v2/slots?eventTypeId=${roundRobinEventTypeWithoutFixedHostsId}&start=2050-09-05&end=2050-09-09&rrHostSubsetIds[]=${teammateOne.id}`
)
.set(CAL_API_VERSION_HEADER, VERSION_2024_09_04)
.expect(200)
.then(async (response) => {
const responseBody: GetSlotsOutput_2024_09_04 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const slots = responseBody.data;
expect(slots).toBeDefined();
const days = Object.keys(slots);
expect(days.length).toEqual(5);
expect(slots).toEqual(expectedSlotsUTC);
});
});
it("should get round robin team event with and without fixed hosts slots in UTC with subsetIds for teammateOne(fixed) and teammateThree(not fixed) ", async () => {
return request(app.getHttpServer())
.get(
`/v2/slots?eventTypeId=${roundRobinEventTypeWithFixedAndNonFixedHostsId}&start=2050-09-05&end=2050-09-09&rrHostSubsetIds[]=${teammateOne.id}&rrHostSubsetIds[]=${teammateThree.id}`
)
.set(CAL_API_VERSION_HEADER, VERSION_2024_09_04)
.expect(200)
.then(async (response) => {
const responseBody: GetSlotsOutput_2024_09_04 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const slots = responseBody.data;
expect(slots).toBeDefined();
const days = Object.keys(slots);
expect(days.length).toEqual(2);
});
});
it("should get round robin team event with and without fixed hosts slots in UTC with subsetIds for teammateOne(fixed) and teammateTwo(not fixed) ", async () => {
return request(app.getHttpServer())
.get(
`/v2/slots?eventTypeId=${roundRobinEventTypeWithFixedAndNonFixedHostsId}&start=2050-09-05&end=2050-09-09&rrHostSubsetIds[]=${teammateOne.id}&rrHostSubsetIds[]=${teammateTwo.id}`
)
.set(CAL_API_VERSION_HEADER, VERSION_2024_09_04)
.expect(200)
.then(async (response) => {
const responseBody: GetSlotsOutput_2024_09_04 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
const slots = responseBody.data;
expect(slots).toBeDefined();
const days = Object.keys(slots);
expect(days.length).toEqual(5);
expect(slots).toEqual(expectedSlotsUTC);
});
});
it("should not be able reserve a team event type slot with custom duration if no auth is provided", async () => {
await request(app.getHttpServer())
.post(`/v2/slots/reservations`)
@@ -748,6 +857,7 @@ describe("Slots 2024-09-04 Endpoints", () => {
afterAll(async () => {
await userRepositoryFixture.deleteByEmail(teammateOne.email);
await userRepositoryFixture.deleteByEmail(teammateTwo.email);
await userRepositoryFixture.deleteByEmail(teammateThree.email);
await userRepositoryFixture.deleteByEmail(outsiderEmail);
await teamRepositoryFixture.delete(team.id);
await bookingsRepositoryFixture.deleteById(collectiveBookingId);
@@ -64,7 +64,7 @@ export class SlotsController_2024_09_04 {
description: `
There are 4 ways to get available slots for event type of an individual user:
1. By event type id. Event type id can be of user and team event types. Example '/v2/slots?eventTypeId=10&start=2050-09-05&end=2050-09-06&timeZone=Europe/Rome'
1. By event type id. Example '/v2/slots?eventTypeId=10&start=2050-09-05&end=2050-09-06&timeZone=Europe/Rome'
2. By event type slug + username. Example '/v2/slots?eventTypeSlug=intro&username=bob&start=2050-09-05&end=2050-09-06'
@@ -74,7 +74,10 @@ export class SlotsController_2024_09_04 {
And 3 ways to get available slots for team event type:
1. By team event type id. Example '/v2/slots?eventTypeId=10&start=2050-09-05&end=2050-09-06&timeZone=Europe/Rome'
1. By team event type id. Example '/v2/slots?eventTypeId=10&start=2050-09-05&end=2050-09-06&timeZone=Europe/Rome'.
**Note for managed event types**: Managed event types are templates that create individual child event types for each team member. You cannot fetch slots for the parent managed event type directly. Instead, you must:
- Find the child event type IDs (the ones assigned to specific users)
- Use those child event type IDs to fetch slots as individual user event types using as described in the individual user section above.
2. By team event type slug + team slug. Example '/v2/slots?eventTypeSlug=intro&teamSlug=team-slug&start=2050-09-05&end=2050-09-06'
@@ -30,6 +30,7 @@ export type InternalGetSlotsQuery = {
timeZone: string | undefined;
orgSlug: string | null | undefined;
rescheduleUid: string | null;
rrHostSubsetIds?: number[];
};
export type InternalGetSlotsQueryWithRouting = InternalGetSlotsQuery & {
@@ -79,6 +80,7 @@ export class SlotsInputService_2024_09_04 {
timeZone,
orgSlug,
rescheduleUid,
rrHostSubsetIds: query.rrHostSubsetIds,
};
}
@@ -1,7 +1,7 @@
import { ApiProperty, ApiPropertyOptional, PartialType } from "@nestjs/swagger";
import { IsArray, IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
import { WebhookTriggerEvents } from "@calcom/platform-libraries";
import { WebhookTriggerEvents, WebhookVersion } from "@calcom/platform-libraries";
export class CreateWebhookInputDto {
@IsString()
@@ -48,6 +48,15 @@ export class CreateWebhookInputDto {
@IsOptional()
@ApiPropertyOptional()
secret?: string;
@IsOptional()
@IsEnum(WebhookVersion)
@ApiPropertyOptional({
description: "The version of the webhook",
example: WebhookVersion.V_2021_10_20,
enum: WebhookVersion,
})
version?: WebhookVersion;
}
export class UpdateWebhookInputDto extends PartialType(CreateWebhookInputDto) {}
@@ -28,21 +28,38 @@ export class FeaturesRepositoryFixture {
});
}
async enableFeatureForTeam(teamId: number, featureId: string, assignedBy = "test") {
await this.prismaWriteClient.teamFeatures.upsert({
where: {
teamId_featureId: {
async setTeamFeatureState(
teamId: number,
featureId: string,
state: "enabled" | "disabled" | "inherit",
assignedBy = "test"
) {
if (state === "enabled" || state === "disabled") {
await this.prismaWriteClient.teamFeatures.upsert({
where: {
teamId_featureId: {
teamId,
featureId,
},
},
create: {
teamId,
featureId,
assignedBy,
enabled: state === "enabled",
},
update: {
enabled: state === "enabled",
},
});
} else if (state === "inherit") {
await this.prismaWriteClient.teamFeatures.deleteMany({
where: {
teamId,
featureId,
},
},
create: {
teamId,
featureId,
assignedBy,
},
update: {},
});
});
}
}
async disableFeatureForTeam(teamId: number, featureSlug: string) {
@@ -13,6 +13,13 @@ import {
type PageProps as ClientPageProps,
} from "~/bookings/views/bookings-single-view.getServerSideProps";
export const metadata = {
robots: {
index: false,
follow: false,
},
};
const getEmbedData = withEmbedSsrAppDir<ClientPageProps>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: ServerPageProps) => {
@@ -16,13 +16,15 @@ import {
type PageProps as ClientPageProps,
} from "~/bookings/views/bookings-single-view.getServerSideProps";
const getData = withAppDirSsr<ClientPageProps>(getServerSideProps);
export const generateMetadata = async ({ params, searchParams }: _PageProps) => {
const { bookingInfo, eventType, recurringBookings, orgSlug } = await getData(
buildLegacyCtx(await headers(), await cookies(), await params, await searchParams)
);
const needsConfirmation = bookingInfo.status === BookingStatus.PENDING && eventType.requiresConfirmation;
return await _generateMetadata(
const metadata = await _generateMetadata(
(t) =>
t(`booking_${needsConfirmation ? "submitted" : "confirmed"}${recurringBookings ? "_recurring" : ""}`),
(t) =>
@@ -31,9 +33,15 @@ export const generateMetadata = async ({ params, searchParams }: _PageProps) =>
getOrgFullOrigin(orgSlug),
`/booking/${(await params).uid}`
);
};
const getData = withAppDirSsr<ClientPageProps>(getServerSideProps);
return {
...metadata,
robots: {
index: false,
follow: false,
},
};
};
const ServerPage = async ({ params, searchParams }: _PageProps) => {
const context = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
@@ -32,11 +32,7 @@ const ServerPage = async ({ params, searchParams }: ServerPageProps) => {
const eventLocale = props.eventData?.interfaceLanguage;
const ns = "common";
let translations;
if (eventLocale) {
const ns = "common";
translations = await loadTranslations(eventLocale, ns);
}
const translations = await loadTranslations(eventLocale ?? "en", ns);
if ((props as TeamTypePageProps)?.teamId) {
return eventLocale ? (
@@ -68,11 +68,7 @@ const ServerPage = async ({ params, searchParams }: PageProps) => {
const eventLocale = props.eventData?.interfaceLanguage;
const ns = "common";
let translations;
if (eventLocale) {
const ns = "common";
translations = await loadTranslations(eventLocale, ns);
}
const translations = await loadTranslations(eventLocale ?? "en", ns);
if ((props as TeamTypePageProps)?.teamId) {
return eventLocale ? (
@@ -13,7 +13,7 @@ import Page from "~/org/[orgSlug]/instant-meeting/team/[slug]/[type]/instant-mee
export const generateMetadata = async ({ params, searchParams }: _PageProps) => {
const context = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const { isBrandingHidden, eventData } = await getData(context);
const { isBrandingHidden, eventData, teamIsPrivate } = await getData(context);
const profileName = eventData?.profile.name ?? "";
const profileImage = eventData?.profile.image;
@@ -22,12 +22,15 @@ export const generateMetadata = async ({ params, searchParams }: _PageProps) =>
const meeting = {
title,
profile: { name: profileName, image: profileImage },
users: [
...(eventData?.users || []).map((user) => ({
name: `${user.name}`,
username: `${user.username}`,
})),
],
// Hide team member names in preview if team is private
users: teamIsPrivate
? []
: [
...(eventData?.users || []).map((user) => ({
name: `${user.name}`,
username: `${user.username}`,
})),
],
};
const decodedParams = decodeParams(await params);
const metadata = await generateMeetingMetadata(
@@ -91,15 +91,20 @@ export const generateMetadata = async ({ params, searchParams }: PageProps) => {
const profileName = enrichedEventType.profile.name ?? "";
const profileImage = enrichedEventType.profile.image;
const teamIsPrivate = teamData.isPrivate;
const meeting = {
title,
profile: { name: profileName, image: profileImage },
users: [
...(enrichedEventType?.subsetOfUsers || []).map((user) => ({
name: `${user.name}`,
username: `${user.username}`,
})),
],
// Hide team member names in preview if team is private
users: teamIsPrivate
? []
: [
...(enrichedEventType?.subsetOfUsers || []).map((user) => ({
name: `${user.name}`,
username: `${user.username}`,
})),
],
};
const { hideBranding, isSEOIndexable } = _getTeamMetadataForBooking(teamData, enrichedEventType.id);
@@ -0,0 +1,48 @@
// Added as a separate route for now to ease the testing of the audit logs feature
// It partially matches the figma design - https://www.figma.com/design/wleA2SR6rn60EK7ORxAfMy/Cal.com-New-Features?node-id=5641-6732&p=f
// TOOD: Move it to the booking page side bar later
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import type { PageProps } from "app/_types";
import { _generateMetadata, getTranslate } from "app/_utils";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import BookingLogsView from "~/booking/logs/views/booking-logs-view";
export const generateMetadata = async ({ params }: { params: Promise<{ uid: string }> }) =>
await _generateMetadata(
(t) => t("booking_history"),
(t) => t("booking_history_description"),
undefined,
undefined,
`/booking/${(await params).uid}/logs`
);
const Page = async ({ params }: PageProps) => {
const resolvedParams = await params;
const bookingUid = resolvedParams.uid;
if (!bookingUid || typeof bookingUid !== "string") {
redirect("/bookings/upcoming");
}
const t = await getTranslate();
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
redirect("/auth/login");
}
return (
<ShellMainAppDir heading={t("booking_history")} subtitle={t("booking_history_description")}>
<BookingLogsView bookingUid={bookingUid} />
</ShellMainAppDir>
);
};
export default Page;
@@ -1,64 +0,0 @@
"use client";
import { useQueryState } from "nuqs";
import { useEffect } from "react";
import { activeFiltersParser } from "@calcom/features/data-table/lib/parsers";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
import { ToggleGroup } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { viewParser, type BookingView } from "~/bookings/lib/viewParser";
export function ViewToggleButton() {
const { t } = useLocale();
const [view, setView] = useQueryState(
"view",
viewParser.withDefault("list").withOptions({ clearOnDefault: true })
);
const [, setActiveFilters] = useQueryState("activeFilters", activeFiltersParser);
const isMobile = !useMediaQuery("(min-width: 640px)");
useEffect(() => {
// Force list view on mobile
if (isMobile && view === "calendar") {
// Clear dateRange filter when forcing calendar to list view, same as manual toggle
setActiveFilters((prev) => prev?.filter((filter) => filter.f !== "dateRange") ?? []);
setView("list");
}
}, [isMobile, view, setView, setActiveFilters]);
return (
<div className="hidden sm:block">
<ToggleGroup
value={view}
onValueChange={(value) => {
if (!value) return;
const newView = value as BookingView;
// When switching from calendar to list view, remove the dateRange filter
if (view === "calendar" && newView === "list") {
setActiveFilters((prev) => prev?.filter((filter) => filter.f !== "dateRange") ?? []);
}
setView(newView);
}}
options={[
{
value: "list",
label: "",
tooltip: t("list_view"),
iconLeft: <Icon name="menu" className="h-4 w-4" />,
},
{
value: "calendar",
label: "",
tooltip: t("calendar_view"),
iconLeft: <Icon name="calendar" className="h-4 w-4" />,
},
]}
/>
</div>
);
}
@@ -16,8 +16,6 @@ import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { validStatuses } from "~/bookings/lib/validStatuses";
import BookingsList from "~/bookings/views/bookings-view";
import { ViewToggleButton } from "./ViewToggleButton";
const querySchema = z.object({
status: z.enum(validStatuses),
});
@@ -56,18 +54,16 @@ const Page = async ({ params }: PageProps) => {
canReadOthersBookings = teamIdsWithPermission.length > 0;
}
const userProfile = session?.user?.profile;
const orgId = userProfile?.organizationId ?? session?.user.org?.id;
const featuresRepository = new FeaturesRepository(prisma);
const bookingsV3Enabled = orgId
? await featuresRepository.checkIfTeamHasFeature(orgId, "bookings-v3")
const bookingsV3Enabled = session?.user?.id
? await featuresRepository.checkIfUserHasFeature(session.user.id, "bookings-v3")
: false;
return (
<ShellMainAppDir
heading={t("bookings")}
subtitle={t("bookings_description")}
CTA={bookingsV3Enabled ? <ViewToggleButton /> : null}>
headerClassName="bookings-shell-heading">
<BookingsList
status={parsed.data.status}
userId={session?.user?.id}
@@ -19,6 +19,7 @@ import useGetBrandingColours from "@calcom/lib/getBrandColours";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useTheme from "@calcom/lib/hooks/useTheme";
import { markdownToSafeHTMLClient } from "@calcom/lib/markdownToSafeHTMLClient";
import { navigateInTopWindow } from "@calcom/lib/navigateInTopWindow";
import { trpc } from "@calcom/trpc/react";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
@@ -208,7 +209,10 @@ function RoutingForm({ form, profile, ...restProps }: Props) {
<div className="mx-auto my-0 max-w-3xl md:my-24">
<div className="w-full max-w-4xl ltr:mr-2 rtl:ml-2">
<div className="main sm:border-subtle bg-default -mx-4 rounded-md border border-neutral-200 p-4 py-6 sm:mx-0 sm:px-8">
<div className="text-emphasis">{customPageMessage}</div>
<div
className="text-emphasis prose prose-sm dark:prose-invert max-w-none"
dangerouslySetInnerHTML={{ __html: markdownToSafeHTMLClient(customPageMessage) }}
/>
</div>
</div>
</div>
@@ -19,7 +19,7 @@ export const generateMetadata = async () => {
);
};
const ServerPage = async () => {
const ServerPage = async (props: { searchParams: Promise<{ fromTeamOnboarding?: string }> }) => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
@@ -28,8 +28,10 @@ const ServerPage = async () => {
const userEmail = session.user.email || "";
const userName = session.user.name || "";
const searchParams = await props.searchParams;
const fromTeamOnboarding = searchParams?.fromTeamOnboarding === "true";
return <PersonalSettingsView userEmail={userEmail} userName={userName} />;
return <PersonalSettingsView userEmail={userEmail} userName={userName} fromTeamOnboarding={fromTeamOnboarding} />;
};
export default ServerPage;
@@ -0,0 +1,150 @@
"use client";
import { useReactTable, getCoreRowModel, createColumnHelper } from "@tanstack/react-table";
import { useMemo } from "react";
import { ColumnFilterType, DateRangeFilter, DataTableProvider } from "@calcom/features/data-table";
import type { DateRangeFilterOptions } from "@calcom/features/data-table/lib/types";
type DemoRow = {
id: number;
name: string;
date: string;
};
const columnHelper = createColumnHelper<DemoRow>();
type ScenarioProps = {
id: string;
title: string;
description: string;
expected: string;
range: DateRangeFilterOptions["range"];
};
const scenarios: ScenarioProps[] = [
{
id: "past",
title: 'Range: "past"',
description: "Restricts date selection to past dates only. Shows presets that are past-compatible.",
expected:
"Presets visible: Today, Last 7 days, Last 30 days, Month to date, Year to date, Custom. Calendar maxDate = today.",
range: "past",
},
{
id: "future",
title: 'Range: "future"',
description: "Restricts date selection to future dates only. Shows only future-compatible presets.",
expected: "Presets visible: Custom only (presets with direction 'any'). Calendar minDate = today.",
range: "future",
},
{
id: "any",
title: 'Range: "any"',
description: "No date restrictions. Shows all presets.",
expected: "All presets visible. No calendar date restrictions.",
range: "any",
},
{
id: "customOnly",
title: 'Range: "customOnly"',
description: "Forces custom date picker only. Always hides presets dropdown.",
expected: "No presets dropdown. Only calendar picker visible when opened. No date restrictions.",
range: "customOnly",
},
];
function ScenarioCard({ scenario }: { scenario: ScenarioProps }) {
const columns = useMemo(
() => [
columnHelper.accessor("name", {
header: "Name",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("date", {
id: "dateRange",
header: "Date Range",
cell: (info) => info.getValue(),
enableColumnFilter: true,
meta: {
filter: {
type: ColumnFilterType.DATE_RANGE,
dateRangeOptions: {
range: scenario.range,
},
},
},
}),
],
[scenario.range]
);
const data = useMemo<DemoRow[]>(
() => [
{ id: 1, name: "Demo Item 1", date: "2024-01-15" },
{ id: 2, name: "Demo Item 2", date: "2024-02-20" },
],
[]
);
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
// Get the column definition to pass to DateRangeFilter
const dateRangeColumn = table.getAllColumns().find((col) => col.id === "dateRange");
const columnMeta = dateRangeColumn?.columnDef.meta as
| { filter?: { type: string; dateRangeOptions?: DateRangeFilterOptions } }
| undefined;
const dateRangeOptions = columnMeta?.filter?.dateRangeOptions;
return (
<div className="border-subtle mb-8 rounded-lg border p-6" data-testid={`drf-scenario-${scenario.id}`}>
<h3 className="text-emphasis mb-2 text-lg font-semibold">{scenario.title}</h3>
<p className="text-default mb-2 text-sm">{scenario.description}</p>
<p className="text-subtle mb-4 text-xs">
<strong>Expected:</strong> {scenario.expected}
</p>
<div className="mt-4">
<DataTableProvider tableIdentifier={`playground-date-range-${scenario.id}`}>
{dateRangeColumn && (
<DateRangeFilter
column={{
id: dateRangeColumn.id,
title: dateRangeColumn.columnDef.header as string,
type: "dr",
}}
options={dateRangeOptions}
showColumnName={false}
showClearButton={false}
/>
)}
</DataTableProvider>
</div>
</div>
);
}
export default function DateRangeFilterPlayground() {
return (
<div className="space-y-6">
<div>
<h1 className="text-emphasis text-2xl font-bold">DateRangeFilter Playground</h1>
<p className="text-default mt-2">
This page demonstrates the different <code>range</code> options for the DateRangeFilter component.
</p>
<p className="text-subtle mt-1 text-sm">
The <code>range</code> option controls both date restrictions and presets visibility. Presets
visibility is derived automatically based on compatible presets.
</p>
</div>
{scenarios.map((scenario) => (
<ScenarioCard key={scenario.id} scenario={scenario} />
))}
</div>
);
}
@@ -2,19 +2,32 @@ import { _generateMetadata, getTranslate } from "app/_utils";
import Link from "next/link";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { Icon } from "@calcom/ui/components/icon";
const LINKS = [
{
title: "Routing Funnel",
description: "Visualize booking conversion flow and routing patterns",
href: "/settings/admin/playground/routing-funnel",
icon: "filter" as const,
},
{
title: "Bookings by Hour",
description: "View booking distribution across different hours",
href: "/settings/admin/playground/bookings-by-hour",
icon: "chart-bar" as const,
},
{
title: "Weekly Calendar",
description: "Interactive weekly calendar view for scheduling",
href: "/settings/admin/playground/weekly-calendar",
icon: "calendar" as const,
},
{
title: "Date Range Filter",
description: "Test date range selection and filtering components",
href: "/settings/admin/playground/date-range-filter",
icon: "calendar-days" as const,
},
];
@@ -31,16 +44,27 @@ const Page = async () => {
const t = await getTranslate();
return (
<SettingsHeader title={t("playground")} description={t("admin_playground_description")}>
<div>
<ul className="mt-8">
<div className="mt-6">
<div className="bg-default border-subtle divide-subtle flex flex-col divide-y rounded-md border">
{LINKS.map((link) => (
<li key={link.title}>
<Link href={link.href} className="list-item list-disc font-medium underline">
{link.title} →
</Link>
</li>
<Link
key={link.title}
href={link.href}
className="hover:bg-muted group flex items-center gap-4 p-5 transition-colors">
<div className="bg-emphasis/10 group-hover:bg-emphasis/20 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-md transition-colors">
<Icon name={link.icon} className="text-emphasis h-5 w-5" />
</div>
<div className="min-w-0 flex-1">
<h3 className="text-emphasis text-sm font-semibold leading-none">{link.title}</h3>
<p className="text-subtle mt-2 text-sm">{link.description}</p>
</div>
<Icon
name="arrow-right"
className="text-subtle group-hover:text-emphasis h-4 w-4 flex-shrink-0 transition-colors"
/>
</Link>
))}
</ul>
</div>
</div>
</SettingsHeader>
);
@@ -6,7 +6,7 @@ import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequir
import { UsersEditView } from "@calcom/features/ee/users/pages/users-edit-view";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import prisma from "@calcom/prisma";
import { prisma } from "@calcom/prisma";
const userIdSchema = z.object({ id: z.coerce.number() });
@@ -41,6 +41,7 @@ const Page = async ({ params }: { params: Params }) => {
const userRepo = new UserRepository(prisma);
const user = await userRepo.adminFindById(input.data.id);
const t = await getTranslate();
return (
@@ -37,13 +37,41 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
href: "/settings/my-account",
icon: "user",
children: [
{ name: "profile", href: "/settings/my-account/profile", trackingMetadata: { section: "my_account", page: "profile" } },
{ name: "general", href: "/settings/my-account/general", trackingMetadata: { section: "my_account", page: "general" } },
{ name: "calendars", href: "/settings/my-account/calendars", trackingMetadata: { section: "my_account", page: "calendars" } },
{ name: "conferencing", href: "/settings/my-account/conferencing", trackingMetadata: { section: "my_account", page: "conferencing" } },
{ name: "appearance", href: "/settings/my-account/appearance", trackingMetadata: { section: "my_account", page: "appearance" } },
{ name: "out_of_office", href: "/settings/my-account/out-of-office", trackingMetadata: { section: "my_account", page: "out_of_office" } },
{ name: "push_notifications", href: "/settings/my-account/push-notifications", trackingMetadata: { section: "my_account", page: "push_notifications" } },
{
name: "profile",
href: "/settings/my-account/profile",
trackingMetadata: { section: "my_account", page: "profile" },
},
{
name: "general",
href: "/settings/my-account/general",
trackingMetadata: { section: "my_account", page: "general" },
},
{
name: "calendars",
href: "/settings/my-account/calendars",
trackingMetadata: { section: "my_account", page: "calendars" },
},
{
name: "conferencing",
href: "/settings/my-account/conferencing",
trackingMetadata: { section: "my_account", page: "conferencing" },
},
{
name: "appearance",
href: "/settings/my-account/appearance",
trackingMetadata: { section: "my_account", page: "appearance" },
},
{
name: "out_of_office",
href: "/settings/my-account/out-of-office",
trackingMetadata: { section: "my_account", page: "out_of_office" },
},
{
name: "push_notifications",
href: "/settings/my-account/push-notifications",
trackingMetadata: { section: "my_account", page: "push_notifications" },
},
// TODO
// { name: "referrals", href: "/settings/my-account/referrals" },
],
@@ -53,16 +81,34 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
href: "/settings/security",
icon: "key",
children: [
{ name: "password", href: "/settings/security/password", trackingMetadata: { section: "security", page: "password" } },
{ name: "impersonation", href: "/settings/security/impersonation", trackingMetadata: { section: "security", page: "impersonation" } },
{ name: "2fa_auth", href: "/settings/security/two-factor-auth", trackingMetadata: { section: "security", page: "2fa_auth" } },
{
name: "password",
href: "/settings/security/password",
trackingMetadata: { section: "security", page: "password" },
},
{
name: "impersonation",
href: "/settings/security/impersonation",
trackingMetadata: { section: "security", page: "impersonation" },
},
{
name: "2fa_auth",
href: "/settings/security/two-factor-auth",
trackingMetadata: { section: "security", page: "2fa_auth" },
},
],
},
{
name: "billing",
href: "/settings/billing",
icon: "credit-card",
children: [{ name: "manage_billing", href: "/settings/billing", trackingMetadata: { section: "billing", page: "manage_billing" } }],
children: [
{
name: "manage_billing",
href: "/settings/billing",
trackingMetadata: { section: "billing", page: "manage_billing" },
},
],
},
{
name: "developer",
@@ -70,9 +116,21 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
icon: "terminal",
children: [
//
{ name: "webhooks", href: "/settings/developer/webhooks", trackingMetadata: { section: "developer", page: "webhooks" } },
{ name: "api_keys", href: "/settings/developer/api-keys", trackingMetadata: { section: "developer", page: "api_keys" } },
{ name: "admin_api", href: "/settings/organizations/admin-api", trackingMetadata: { section: "developer", page: "admin_api" } },
{
name: "webhooks",
href: "/settings/developer/webhooks",
trackingMetadata: { section: "developer", page: "webhooks" },
},
{
name: "api_keys",
href: "/settings/developer/api-keys",
trackingMetadata: { section: "developer", page: "api_keys" },
},
{
name: "admin_api",
href: "/settings/organizations/admin-api",
trackingMetadata: { section: "developer", page: "admin_api" },
},
// TODO: Add profile level for embeds
// { name: "embeds", href: "/v2/settings/developer/embeds" },
],
@@ -97,13 +155,13 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
},
...(orgBranding
? [
{
name: "members",
href: `${WEBAPP_URL}/settings/organizations/${orgBranding.slug}/members`,
isExternalLink: true,
trackingMetadata: { section: "organization", page: "members" },
},
]
{
name: "members",
href: `${WEBAPP_URL}/settings/organizations/${orgBranding.slug}/members`,
isExternalLink: true,
trackingMetadata: { section: "organization", page: "members" },
},
]
: []),
{
name: "privacy_and_security",
@@ -146,31 +204,83 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
icon: "lock",
children: [
//
{ name: "features", href: "/settings/admin/flags", trackingMetadata: { section: "admin", page: "features" } },
{ name: "license", href: "/auth/setup?step=1", trackingMetadata: { section: "admin", page: "license" } },
{ name: "impersonation", href: "/settings/admin/impersonation", trackingMetadata: { section: "admin", page: "impersonation" } },
{ name: "apps", href: "/settings/admin/apps/calendar", trackingMetadata: { section: "admin", page: "apps" } },
{ name: "users", href: "/settings/admin/users", trackingMetadata: { section: "admin", page: "users" } },
{ name: "organizations", href: "/settings/admin/organizations", trackingMetadata: { section: "admin", page: "organizations" } },
{ name: "lockedSMS", href: "/settings/admin/lockedSMS", trackingMetadata: { section: "admin", page: "locked_sms" } },
{ name: "oAuth", href: "/settings/admin/oAuth", trackingMetadata: { section: "admin", page: "oauth" } },
{ name: "Workspace Platforms", href: "/settings/admin/workspace-platforms", trackingMetadata: { section: "admin", page: "workspace_platforms" } },
{ name: "Playground", href: "/settings/admin/playground", trackingMetadata: { section: "admin", page: "playground" } },
{
name: "features",
href: "/settings/admin/flags",
trackingMetadata: { section: "admin", page: "features" },
},
{
name: "license",
href: "/auth/setup?step=1",
trackingMetadata: { section: "admin", page: "license" },
},
{
name: "impersonation",
href: "/settings/admin/impersonation",
trackingMetadata: { section: "admin", page: "impersonation" },
},
{
name: "apps",
href: "/settings/admin/apps/calendar",
trackingMetadata: { section: "admin", page: "apps" },
},
{
name: "users",
href: "/settings/admin/users",
trackingMetadata: { section: "admin", page: "users" },
},
{
name: "organizations",
href: "/settings/admin/organizations",
trackingMetadata: { section: "admin", page: "organizations" },
},
{
name: "lockedSMS",
href: "/settings/admin/lockedSMS",
trackingMetadata: { section: "admin", page: "locked_sms" },
},
{
name: "oAuth",
href: "/settings/admin/oAuth",
trackingMetadata: { section: "admin", page: "oauth" },
},
{
name: "Workspace Platforms",
href: "/settings/admin/workspace-platforms",
trackingMetadata: { section: "admin", page: "workspace_platforms" },
},
{
name: "Playground",
href: "/settings/admin/playground",
trackingMetadata: { section: "admin", page: "playground" },
},
],
},
];
tabs.find((tab) => {
if (tab.name === "security" && !HOSTED_CAL_FEATURES) {
tab.children?.push({ name: "sso_configuration", href: "/settings/security/sso", trackingMetadata: { section: "security", page: "sso_configuration" } });
tab.children?.push({
name: "sso_configuration",
href: "/settings/security/sso",
trackingMetadata: { section: "security", page: "sso_configuration" },
});
// TODO: Enable dsync for self hosters
// tab.children?.push({ name: "directory_sync", href: "/settings/security/dsync" });
}
if (tab.name === "admin" && IS_CALCOM) {
tab.children?.push({ name: "create_org", href: "/settings/organizations/new", trackingMetadata: { section: "admin", page: "create_org" } });
tab.children?.push({
name: "create_org",
href: "/settings/organizations/new",
trackingMetadata: { section: "admin", page: "create_org" },
});
}
if (tab.name === "admin" && IS_CALCOM) {
tab.children?.push({ name: "create_license_key", href: "/settings/license-key/new", trackingMetadata: { section: "admin", page: "create_license_key" } });
tab.children?.push({
name: "create_license_key",
href: "/settings/license-key/new",
trackingMetadata: { section: "admin", page: "create_license_key" },
});
}
});
@@ -442,8 +552,9 @@ const TeamListCollapsible = ({ teamFeatures }: { teamFeatures?: Record<number, T
setTeamMenuState(newTeamMenuState);
}
}}
aria-label={`${team.name} ${teamMenuState[index].teamMenuOpen ? t("collapse_menu") : t("expand_menu")
}`}>
aria-label={`${team.name} ${
teamMenuState[index].teamMenuOpen ? t("collapse_menu") : t("expand_menu")
}`}>
<div className="me-3">
{teamMenuState[index].teamMenuOpen ? (
<Icon name="chevron-down" className="h-4 w-4" />
@@ -451,7 +562,7 @@ const TeamListCollapsible = ({ teamFeatures }: { teamFeatures?: Record<number, T
<Icon name="chevron-right" className="h-4 w-4" />
)}
</div>
{ }
{}
{!team.parentId && (
<Image
src={getPlaceholderAvatar(team.logoUrl, team.name)}
@@ -469,7 +580,7 @@ const TeamListCollapsible = ({ teamFeatures }: { teamFeatures?: Record<number, T
)}
</button>
</CollapsibleTrigger>
<CollapsibleContent className="stack-y-0.5" id={`team-content-${team.id}`}>
<CollapsibleContent className="flex flex-col space-y-1" id={`team-content-${team.id}`}>
{team.accepted && (
<VerticalTabItem
name={t("profile")}
@@ -494,9 +605,9 @@ const TeamListCollapsible = ({ teamFeatures }: { teamFeatures?: Record<number, T
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore this exists wtf?
(team.isOrgAdmin && team.isOrgAdmin)) && (
<>
{/* TODO */}
{/* <VerticalTabItem
<>
{/* TODO */}
{/* <VerticalTabItem
name={t("general")}
href={`${WEBAPP_URL}/settings/my-account/appearance`}
textClassNames="px-3 text-emphasis font-medium text-sm"
@@ -628,7 +739,7 @@ const SettingsSidebarContainer = ({
className="text-subtle h-[16px] w-[16px] stroke-[2px] ltr:mr-3 rtl:ml-3 md:mt-0"
/>
)}
{ }
{}
{!tab.icon && tab?.avatar && (
<Image
width={16}
@@ -647,7 +758,7 @@ const SettingsSidebarContainer = ({
</Skeleton>
</div>
</div>
<div className="stack-y-px">
<div className="flex flex-col space-y-1">
{tab.children?.map((child, index) => (
<div key={child.href} className="flex items-start gap-2">
<VerticalTabItem
@@ -772,10 +883,11 @@ const SettingsSidebarContainer = ({
setOtherTeamMenuState(newOtherTeamMenuState);
}
}}
aria-label={`${otherTeam.name} ${otherTeamMenuState[index].teamMenuOpen
? t("collapse_menu")
: t("expand_menu")
}`}>
aria-label={`${otherTeam.name} ${
otherTeamMenuState[index].teamMenuOpen
? t("collapse_menu")
: t("expand_menu")
}`}>
<div className="me-3">
{otherTeamMenuState[index].teamMenuOpen ? (
<Icon name="chevron-down" className="h-4 w-4" />
@@ -783,7 +895,7 @@ const SettingsSidebarContainer = ({
<Icon name="chevron-right" className="h-4 w-4" />
)}
</div>
{ }
{}
{!otherTeam.parentId && (
<Image
src={getPlaceholderAvatar(otherTeam.logoUrl, otherTeam.name)}
@@ -797,12 +909,16 @@ const SettingsSidebarContainer = ({
</button>
</CollapsibleTrigger>
<CollapsibleContent
className="stack-y-0.5"
className="flex flex-col space-y-1"
id={`other-team-content-${otherTeam.id}`}>
<VerticalTabItem
name={t("profile")}
href={`/settings/organizations/teams/other/${otherTeam.id}/profile`}
trackingMetadata={{ section: "other_team", page: "profile", teamId: otherTeam.id }}
trackingMetadata={{
section: "other_team",
page: "profile",
teamId: otherTeam.id,
}}
textClassNames="px-3 text-emphasis font-medium text-sm"
className="px-2! me-5 h-7 w-auto"
disableChevron
@@ -810,7 +926,11 @@ const SettingsSidebarContainer = ({
<VerticalTabItem
name={t("members")}
href={`/settings/organizations/teams/other/${otherTeam.id}/members`}
trackingMetadata={{ section: "other_team", page: "members", teamId: otherTeam.id }}
trackingMetadata={{
section: "other_team",
page: "members",
teamId: otherTeam.id,
}}
textClassNames="px-3 text-emphasis font-medium text-sm"
className="px-2! me-5 h-7 w-auto"
disableChevron
@@ -4,8 +4,8 @@ import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { PrismaApiKeyRepository } from "@calcom/features/ee/api-keys/repositories/PrismaApiKeyRepository";
import { APP_NAME } from "@calcom/lib/constants";
import { PrismaApiKeyRepository } from "@calcom/lib/server/repository/PrismaApiKeyRepository";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
@@ -1,7 +1,6 @@
import type { PageProps } from "app/_types";
import { _generateMetadata, getTranslate } from "app/_utils";
import { _generateMetadata } from "app/_utils";
import SettingsHeaderWithBackButton from "@calcom/features/settings/appDir/SettingsHeaderWithBackButton";
import { WebhookRepository } from "@calcom/features/webhooks/lib/repository/WebhookRepository";
import { EditWebhookView } from "@calcom/features/webhooks/pages/webhook-edit-view";
import { APP_NAME } from "@calcom/lib/constants";
@@ -16,21 +15,13 @@ export const generateMetadata = async ({ params }: { params: Promise<{ id: strin
);
const Page = async ({ params: _params }: PageProps) => {
const t = await getTranslate();
const params = await _params;
const id = typeof params?.id === "string" ? params.id : undefined;
const webhookRepository = WebhookRepository.getInstance();
const webhook = await webhookRepository.findByWebhookId(id);
return (
<SettingsHeaderWithBackButton
title={t("edit_webhook")}
description={t("add_webhook_description", { appName: APP_NAME })}
borderInShellHeader={true}>
<EditWebhookView webhook={webhook} />
</SettingsHeaderWithBackButton>
);
return <EditWebhookView webhook={webhook} />;
};
export default Page;
@@ -20,7 +20,7 @@ import SettingsLayoutAppDirClient from "./SettingsLayoutAppDirClient";
const getTeamFeatures = unstable_cache(
async (teamId: number) => {
const featuresRepository = new FeaturesRepository(prisma);
return await featuresRepository.getTeamFeatures(teamId);
return await featuresRepository.getEnabledTeamFeatures(teamId);
},
["team-features"],
{
@@ -29,7 +29,7 @@ async function handler(req: NextRequest) {
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: piiHasher.hash(ip),
identifier: `forgotPassword:${piiHasher.hash(ip)}`,
});
try {
@@ -10,7 +10,7 @@ import prisma from "@calcom/prisma";
import type { OAuthTokenPayload } from "@calcom/types/oauth";
async function handler(req: NextRequest) {
const { client_id, client_secret, grant_type, refresh_token, code_verifier } = await parseUrlFormData(req);
const { client_id, client_secret, grant_type, refresh_token } = await parseUrlFormData(req);
if (!process.env.CALENDSO_ENCRYPTION_KEY) {
return NextResponse.json({ message: "CALENDSO_ENCRYPTION_KEY is not set" }, { status: 500 });
@@ -62,11 +62,6 @@ async function handler(req: NextRequest) {
return NextResponse.json({ error: "invalid_grant" }, { status: 400 });
}
const pkceError = OAuthService.verifyPKCE(client, decodedRefreshToken, code_verifier);
if (pkceError) {
return NextResponse.json({ error: pkceError.error }, { status: pkceError.status });
}
const accessTokenExpiresIn = 1800; // 30 minutes
const payloadAuthToken: OAuthTokenPayload = {
@@ -83,11 +78,6 @@ async function handler(req: NextRequest) {
scope: decodedRefreshToken.scope,
token_type: "Refresh Token",
clientId: client_id,
// Preserve PKCE information for any client that used PKCE originally
...(decodedRefreshToken.codeChallenge && {
codeChallenge: decodedRefreshToken.codeChallenge,
codeChallengeMethod: decodedRefreshToken.codeChallengeMethod,
}),
};
const access_token = jwt.sign(payloadAuthToken, secretKey, {
+11 -2
View File
@@ -7,6 +7,9 @@ import { z } from "zod";
import { validPassword } from "@calcom/features/auth/lib/validPassword";
import { hashPassword } from "@calcom/lib/auth/hashPassword";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import getIP from "@calcom/lib/getIP";
import { piiHasher } from "@calcom/lib/server/PiiHasher";
import prisma from "@calcom/prisma";
import { IdentityProvider } from "@calcom/prisma/enums";
@@ -36,8 +39,14 @@ async function handler(req: NextRequest) {
// token verified, delete the cookie / a resubmit on failure requires a new csrf token.
cookieStore.delete("calcom.csrf_token");
// rate-limited there is a low, very low chance that a password request stays valid long enough
// to brute force 3.8126967e+40 options.
const remoteIp = getIP(req);
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: `api:reset-password:${piiHasher.hash(remoteIp)}`,
});
// Note: There is a low, very low chance that a password request stays valid long enough
// to brute force 3.8126967e+40 options, but rate limiting provides additional protection.
const maybeRequest = await prisma.resetPasswordRequest.findFirstOrThrow({
where: {
id: rawRequestId,
+8
View File
@@ -5,10 +5,12 @@ import { NextResponse, type NextRequest } from "next/server";
import calcomSignupHandler from "@calcom/feature-auth/signup/handlers/calcomHandler";
import selfHostedSignupHandler from "@calcom/feature-auth/signup/handlers/selfHostedHandler";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { IS_PREMIUM_USERNAME_ENABLED } from "@calcom/lib/constants";
import getIP from "@calcom/lib/getIP";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { piiHasher } from "@calcom/lib/server/PiiHasher";
import { checkCfTurnstileToken } from "@calcom/lib/server/checkCfTurnstileToken";
import { prisma } from "@calcom/prisma";
import { signupSchema } from "@calcom/prisma/zod-utils";
@@ -38,6 +40,12 @@ async function handler(req: NextRequest) {
const remoteIp = getIP(req);
// Use a try catch instead of returning res every time
try {
// Rate limit: 10 signups per 60 seconds per IP
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: `api:signup:${piiHasher.hash(remoteIp)}`,
});
const body = await parseRequestData(req);
await checkCfTurnstileToken({
token: req.headers.get("cf-access-token") as string,
@@ -7,6 +7,7 @@ import type { NextRequest } from "next/server";
import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { verifyPassword } from "@calcom/features/auth/lib/verifyPassword";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { symmetricDecrypt } from "@calcom/lib/crypto";
import { totpAuthenticatorCheck } from "@calcom/lib/totp";
import prisma from "@calcom/prisma";
@@ -27,6 +28,11 @@ async function handler(req: NextRequest) {
return NextResponse.json({ error: ErrorCode.InternalServerError }, { status: 500 });
}
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: `api:totp-disable:${session.user.id}`,
});
const user = await prisma.user.findUnique({ where: { id: session.user.id }, include: { password: true } });
if (!user) {
@@ -6,6 +6,7 @@ import type { NextRequest } from "next/server";
import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { symmetricDecrypt } from "@calcom/lib/crypto";
import { totpAuthenticatorCheck } from "@calcom/lib/totp";
import prisma from "@calcom/prisma";
@@ -25,6 +26,11 @@ async function postHandler(req: NextRequest) {
return NextResponse.json({ error: ErrorCode.InternalServerError }, { status: 500 });
}
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: `api:totp-enable:${session.user.id}`,
});
const user = await prisma.user.findUnique({ where: { id: session.user.id } });
if (!user) {
console.error(`Session references user that no longer exists.`);
@@ -10,6 +10,7 @@ import qrcode from "qrcode";
import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { verifyPassword } from "@calcom/features/auth/lib/verifyPassword";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { symmetricEncrypt } from "@calcom/lib/crypto";
import prisma from "@calcom/prisma";
import { IdentityProvider } from "@calcom/prisma/enums";
@@ -29,6 +30,11 @@ async function postHandler(req: NextRequest) {
return NextResponse.json({ error: ErrorCode.InternalServerError }, { status: 500 });
}
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: `api:totp-setup:${session.user.id}`,
});
const user = await prisma.user.findUnique({ where: { id: session.user.id }, include: { password: true } });
if (!user) {
+12
View File
@@ -5,6 +5,9 @@ import type { NextRequest } from "next/server";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import handleCancelBooking from "@calcom/features/bookings/lib/handleCancelBooking";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import getIP from "@calcom/lib/getIP";
import { piiHasher } from "@calcom/lib/server/PiiHasher";
import { bookingCancelWithCsrfSchema } from "@calcom/prisma/zod-utils";
import { validateCsrfToken } from "@calcom/web/lib/validateCsrfToken";
@@ -26,6 +29,15 @@ async function handler(req: NextRequest) {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
// Rate limit: 10 booking cancellations per 60 seconds per user (or IP if not authenticated)
const identifier = session?.user?.id
? `api:cancel-user:${session.user.id}`
: `api:cancel-ip:${piiHasher.hash(getIP(req))}`;
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier,
});
const result = await handleCancelBooking({
bookingData,
userId: session?.user?.id || -1,
@@ -8,7 +8,7 @@ import { CalendarCacheEventRepository } from "@calcom/features/calendar-subscrip
import { CalendarCacheEventService } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventService";
import { CalendarSyncService } from "@calcom/features/calendar-subscription/lib/sync/CalendarSyncService";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/SelectedCalendarRepository";
import { SelectedCalendarRepository } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository";
import { prisma } from "@calcom/prisma";
import { defaultResponderForAppDir } from "@calcom/web/app/api/defaultResponderForAppDir";
@@ -3,8 +3,8 @@ import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import dayjs from "@calcom/dayjs";
import { ScheduleRepository } from "@calcom/features/schedules/repositories/ScheduleRepository";
import prisma from "@calcom/prisma";
import { getDefaultScheduleId } from "@calcom/trpc/server/routers/viewer/availability/util";
const travelScheduleSelect = {
id: true,
@@ -40,7 +40,8 @@ async function postHandler(request: NextRequest) {
},
});
const defaultScheduleId = await getDefaultScheduleId(user.id, prisma);
const scheduleRepository = new ScheduleRepository(prisma);
const defaultScheduleId = await scheduleRepository.getDefaultScheduleId(user.id);
if (!user.defaultScheduleId) {
// set default schedule if not already set
@@ -0,0 +1,208 @@
import type { NextRequest } from "next/server";
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("app/api/defaultResponderForAppDir", () => ({
defaultResponderForAppDir:
(handler: (req: NextRequest) => Promise<Response>) =>
(req: NextRequest, _context: { params: Promise<Record<string, string>> }) =>
handler(req),
}));
vi.mock("next/headers", () => ({
headers: vi.fn().mockResolvedValue(new Headers()),
cookies: vi.fn().mockResolvedValue({ getAll: () => [] }),
}));
vi.mock("next/server", () => ({
NextResponse: {
redirect: vi.fn((url: string | URL, init?: { status?: number }) => {
const location = typeof url === "string" ? url : url.toString();
return {
status: init?.status ?? 302,
headers: {
get: (name: string) => (name.toLowerCase() === "location" ? location : null),
},
} as unknown as Response;
}),
},
}));
vi.mock("@calcom/lib/crypto", () => ({
symmetricDecrypt: vi.fn().mockReturnValue(
JSON.stringify({
bookingUid: "test-booking-uid",
userId: 1,
})
),
}));
vi.mock("@calcom/prisma", () => ({
default: {
booking: {
findUniqueOrThrow: vi.fn().mockResolvedValue({
id: 1,
uid: "test-booking-uid",
recurringEventId: null,
}),
},
user: {
findUniqueOrThrow: vi.fn().mockResolvedValue({
id: 1,
locale: "en",
}),
},
},
}));
vi.mock("@calcom/trpc/server/createContext", () => ({
createContext: vi.fn().mockResolvedValue({}),
}));
vi.mock("@calcom/trpc/server/routers/viewer/bookings/_router", () => ({
bookingsRouter: {},
}));
vi.mock("@calcom/trpc/server/trpc", () => ({
createCallerFactory: vi.fn().mockReturnValue(() => ({
confirm: vi.fn().mockResolvedValue({}),
})),
}));
vi.mock("@lib/buildLegacyCtx", () => ({
buildLegacyRequest: vi.fn().mockReturnValue({}),
}));
// Import after mocks are set up
import { GET } from "../route";
const createMockRequest = (url: string): NextRequest => {
const urlObj = new URL(url);
return {
method: "GET",
url,
nextUrl: {
searchParams: urlObj.searchParams,
},
} as unknown as NextRequest;
};
describe("link route", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("GET handler - redirect URL construction", () => {
it("should redirect to booking page with the same origin as the request", async () => {
const baseUrl = "https://app.example.com/api/link?action=accept&token=encrypted-token";
const req = createMockRequest(baseUrl);
const res = await GET(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe("https://app.example.com");
expect(redirectUrl.pathname).toBe("/booking/test-booking-uid");
});
it("should preserve custom domain origin in redirect URL", async () => {
const baseUrl = "https://custom-domain.company.com/api/link?action=accept&token=encrypted-token";
const req = createMockRequest(baseUrl);
const res = await GET(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe("https://custom-domain.company.com");
expect(location).not.toContain("localhost");
});
it("should preserve self-hosted domain origin in redirect URL", async () => {
const baseUrl = "https://calcom.internal.company.net/api/link?action=reject&token=encrypted-token";
const req = createMockRequest(baseUrl);
const res = await GET(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe("https://calcom.internal.company.net");
expect(location).not.toContain("localhost");
});
it("should construct redirect URLs relative to the request URL for various origins", async () => {
const testOrigins = [
"https://app.cal.com",
"https://acme.cal.com",
"https://calcom.company.internal",
"http://192.168.1.100:3000",
];
for (const origin of testOrigins) {
vi.clearAllMocks();
const baseUrl = `${origin}/api/link?action=accept&token=encrypted-token`;
const req = createMockRequest(baseUrl);
const res = await GET(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe(origin);
expect(redirectUrl.pathname).toBe("/booking/test-booking-uid");
}
});
});
describe("GET handler - error handling", () => {
it("should redirect with error message when TRPC throws an error", async () => {
const { TRPCError } = await import("@trpc/server");
// Mock createCallerFactory to throw a TRPCError
const { createCallerFactory } = await import("@calcom/trpc/server/trpc");
vi.mocked(createCallerFactory).mockReturnValue(() => ({
confirm: vi.fn().mockRejectedValue(new TRPCError({ code: "BAD_REQUEST", message: "Custom error" })),
}));
const baseUrl = "https://app.example.com/api/link?action=accept&token=encrypted-token";
const req = createMockRequest(baseUrl);
const res = await GET(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe("https://app.example.com");
expect(redirectUrl.pathname).toBe("/booking/test-booking-uid");
expect(redirectUrl.searchParams.get("error")).toBe("Custom error");
});
it("should preserve origin in error redirect URL", async () => {
const { TRPCError } = await import("@trpc/server");
// Mock createCallerFactory to throw a TRPCError
const { createCallerFactory } = await import("@calcom/trpc/server/trpc");
vi.mocked(createCallerFactory).mockReturnValue(() => ({
confirm: vi.fn().mockRejectedValue(new TRPCError({ code: "INTERNAL_SERVER_ERROR" })),
}));
const baseUrl = "https://self-hosted.company.org/api/link?action=accept&token=encrypted-token";
const req = createMockRequest(baseUrl);
const res = await GET(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe("https://self-hosted.company.org");
expect(location).not.toContain("localhost");
});
});
});
+2 -3
View File
@@ -59,7 +59,6 @@ const createSessionGetter = (userId: number) => async () => {
};
async function handler(request: NextRequest) {
const url = new URL(request.url);
const searchParams = request.nextUrl.searchParams;
const { action, token, reason } = querySchema.parse(Object.fromEntries(searchParams.entries()));
@@ -120,10 +119,10 @@ async function handler(request: NextRequest) {
} catch (e) {
let message = "Error confirming booking";
if (e instanceof TRPCError) message = (e as TRPCError).message;
return NextResponse.redirect(`${url.origin}/booking/${bookingUid}?error=${encodeURIComponent(message)}`);
return NextResponse.redirect(new URL(`/booking/${bookingUid}?error=${encodeURIComponent(message)}`, request.url));
}
return NextResponse.redirect(`${url.origin}/booking/${bookingUid}`);
return NextResponse.redirect(new URL(`/booking/${bookingUid}`, request.url));
}
export const GET = defaultResponderForAppDir(handler);
@@ -43,6 +43,7 @@ async function getHandler(req: NextRequest) {
// If onboarding-v3 is enabled AND organizationOnboardingId exists, redirect to onboarding flow
if (isOnboardingV3Enabled && organizationOnboardingId) {
params.append("fromTeamOnboarding", "true");
const redirectUrl = new URL(
`/onboarding/personal/settings?${params.toString()}`,
WEBAPP_URL
@@ -0,0 +1,222 @@
import type { NextRequest } from "next/server";
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("app/api/defaultResponderForAppDir", () => ({
defaultResponderForAppDir:
(handler: (req: NextRequest) => Promise<Response>) =>
(req: NextRequest, _context: { params: Promise<Record<string, string>> }) =>
handler(req),
}));
vi.mock("app/api/parseRequestData", () => ({
parseRequestData: vi.fn().mockResolvedValue({}),
}));
vi.mock("next/headers", () => ({
headers: vi.fn().mockResolvedValue(new Headers()),
cookies: vi.fn().mockResolvedValue({ getAll: () => [] }),
}));
vi.mock("next/server", () => ({
NextResponse: {
redirect: vi.fn((url: string | URL, init?: { status?: number }) => {
const location = typeof url === "string" ? url : url.toString();
return {
status: init?.status ?? 302,
headers: {
get: (name: string) => (name.toLowerCase() === "location" ? location : null),
},
} as unknown as Response;
}),
},
}));
vi.mock("@calcom/prisma", () => ({
default: {
booking: {
findUnique: vi.fn(),
update: vi.fn(),
},
user: {
findUniqueOrThrow: vi.fn(),
},
},
}));
vi.mock("@calcom/trpc/server/createContext", () => ({
createContext: vi.fn().mockResolvedValue({}),
}));
vi.mock("@calcom/trpc/server/routers/viewer/bookings/_router", () => ({
bookingsRouter: {},
}));
vi.mock("@calcom/trpc/server/trpc", () => ({
createCallerFactory: vi.fn().mockReturnValue(() => ({
confirm: vi.fn().mockResolvedValue({}),
})),
}));
vi.mock("@lib/buildLegacyCtx", () => ({
buildLegacyRequest: vi.fn().mockReturnValue({}),
}));
// Import after mocks are set up
import { GET, POST } from "../route";
const createMockRequest = (url: string, method: "GET" | "POST" = "GET"): NextRequest => {
const urlObj = new URL(url);
return {
method,
url,
nextUrl: {
searchParams: urlObj.searchParams,
},
} as unknown as NextRequest;
};
describe("verify-booking-token route", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("GET handler", () => {
it("should redirect to booking page with error when action is reject (requires POST)", async () => {
const baseUrl =
"https://app.example.com/api/verify-booking-token?action=reject&token=test-token&bookingUid=abc123&userId=42";
const req = createMockRequest(baseUrl, "GET");
const res = await GET(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe("https://app.example.com");
expect(redirectUrl.pathname).toBe("/booking/abc123");
expect(redirectUrl.searchParams.get("error")).toBe("Rejection requires POST method");
});
it("should redirect with error when query params are invalid (missing action)", async () => {
const baseUrl =
"https://app.example.com/api/verify-booking-token?token=test-token&bookingUid=abc123&userId=42";
const req = createMockRequest(baseUrl, "GET");
const res = await GET(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe("https://app.example.com");
expect(redirectUrl.pathname).toBe("/booking/abc123");
expect(redirectUrl.searchParams.get("error")).toBe("Error confirming booking");
});
it("should redirect with error when query params are invalid (missing token)", async () => {
const baseUrl =
"https://app.example.com/api/verify-booking-token?action=accept&bookingUid=abc123&userId=42";
const req = createMockRequest(baseUrl, "GET");
const res = await GET(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe("https://app.example.com");
expect(redirectUrl.pathname).toBe("/booking/abc123");
expect(redirectUrl.searchParams.get("error")).toBe("Error confirming booking");
});
it("should preserve the request origin in redirect URL (not hardcode localhost)", async () => {
const baseUrl =
"https://custom-domain.example.org/api/verify-booking-token?action=reject&token=t&bookingUid=booking-uid&userId=1";
const req = createMockRequest(baseUrl, "GET");
const res = await GET(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe("https://custom-domain.example.org");
expect(location).not.toContain("localhost");
});
it("should handle empty bookingUid in error case", async () => {
const baseUrl = "https://app.example.com/api/verify-booking-token?token=test-token&userId=42";
const req = createMockRequest(baseUrl, "GET");
const res = await GET(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.pathname).toBe("/booking/");
expect(redirectUrl.searchParams.get("error")).toBe("Error confirming booking");
});
});
describe("POST handler", () => {
it("should redirect with status 303 when query params are invalid", async () => {
const baseUrl =
"https://app.example.com/api/verify-booking-token?token=test-token&bookingUid=abc123&userId=42";
const req = createMockRequest(baseUrl, "POST");
const res = await POST(req, { params: Promise.resolve({}) });
expect(res.status).toBe(303);
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe("https://app.example.com");
expect(redirectUrl.pathname).toBe("/booking/abc123");
expect(redirectUrl.searchParams.get("error")).toBe("Error confirming booking");
});
it("should preserve the request origin in POST redirect URL", async () => {
const baseUrl =
"https://self-hosted.company.com/api/verify-booking-token?bookingUid=uid123&token=t&userId=1";
const req = createMockRequest(baseUrl, "POST");
const res = await POST(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe("https://self-hosted.company.com");
expect(location).not.toContain("localhost");
});
});
describe("redirect URL construction", () => {
it("should construct redirect URLs relative to the request URL, not hardcoded origins", async () => {
const testOrigins = [
"https://app.cal.com",
"https://acme.cal.com",
"https://calcom.company.internal",
"http://192.168.1.100:3000",
];
for (const origin of testOrigins) {
vi.clearAllMocks();
const baseUrl = `${origin}/api/verify-booking-token?action=reject&token=t&bookingUid=test-uid&userId=1`;
const req = createMockRequest(baseUrl, "GET");
const res = await GET(req, { params: Promise.resolve({}) });
const location = res.headers.get("location");
expect(location).toBeTruthy();
const redirectUrl = new URL(location!);
expect(redirectUrl.origin).toBe(origin);
expect(redirectUrl.pathname).toBe("/booking/test-uid");
}
});
});
});
+13 -11
View File
@@ -29,7 +29,6 @@ const querySchema = z.object({
});
async function getHandler(request: NextRequest) {
const url = new URL(request.url);
const queryParams = Object.fromEntries(request.nextUrl.searchParams.entries());
try {
@@ -38,21 +37,20 @@ async function getHandler(request: NextRequest) {
if (action === DirectAction.REJECT) {
// Rejections should use POST method
return NextResponse.redirect(
`${url.origin}/booking/${bookingUid}?error=${encodeURIComponent("Rejection requires POST method")}`
new URL(`/booking/${bookingUid}?error=${encodeURIComponent("Rejection requires POST method")}`, request.url)
);
}
return await handleBookingAction(action, token, bookingUid, userId, request, undefined);
} catch (error) {
} catch {
const bookingUid = queryParams.bookingUid || "";
return NextResponse.redirect(
`${url.origin}/booking/${bookingUid}?error=${encodeURIComponent("Error confirming booking")}`
new URL(`/booking/${bookingUid}?error=${encodeURIComponent("Error confirming booking")}`, request.url)
);
}
}
async function postHandler(request: NextRequest) {
const url = new URL(request.url);
const queryParams = Object.fromEntries(request.nextUrl.searchParams.entries());
try {
@@ -61,10 +59,11 @@ async function postHandler(request: NextRequest) {
const { reason } = z.object({ reason: z.string().optional() }).parse(body || {});
return await handleBookingAction(action, token, bookingUid, userId, request, reason);
} catch (error) {
} catch {
const bookingUid = queryParams.bookingUid || "";
return NextResponse.redirect(
`${url.origin}/booking/${bookingUid}?error=${encodeURIComponent("Error confirming booking")}`
new URL(`/booking/${bookingUid}?error=${encodeURIComponent("Error confirming booking")}`, request.url),
{ status: 303 }
);
}
}
@@ -77,14 +76,14 @@ async function handleBookingAction(
request: NextRequest,
reason?: string
) {
const url = new URL(request.url);
const booking = await prisma.booking.findUnique({
where: { oneTimePassword: token },
});
if (!booking) {
return NextResponse.redirect(
`${url.origin}/booking/${bookingUid}?error=${encodeURIComponent("Error confirming booking")}`
new URL(`/booking/${bookingUid}?error=${encodeURIComponent("Error confirming booking")}`, request.url),
{ status: 303 }
);
}
@@ -140,7 +139,10 @@ async function handleBookingAction(
} catch (e) {
let message = "Error confirming booking";
if (e instanceof TRPCError) message = (e as TRPCError).message;
return NextResponse.redirect(`${url.origin}/booking/${booking.uid}?error=${encodeURIComponent(message)}`);
return NextResponse.redirect(
new URL(`/booking/${booking.uid}?error=${encodeURIComponent(message)}`, request.url),
{ status: 303 }
);
}
await prisma.booking.update({
@@ -148,7 +150,7 @@ async function handleBookingAction(
data: { oneTimePassword: null },
});
return NextResponse.redirect(`${url.origin}/booking/${booking.uid}`);
return NextResponse.redirect(new URL(`/booking/${booking.uid}`, request.url), { status: 303 });
}
export const GET = defaultResponderForAppDir(getHandler);
@@ -11,7 +11,7 @@ import { CalendarCacheEventService } from "@calcom/features/calendar-subscriptio
import { CalendarSyncService } from "@calcom/features/calendar-subscription/lib/sync/CalendarSyncService";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import logger from "@calcom/lib/logger";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/SelectedCalendarRepository";
import { SelectedCalendarRepository } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository";
import { prisma } from "@calcom/prisma";
import { defaultResponderForAppDir } from "@calcom/web/app/api/defaultResponderForAppDir";

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