512002aaef4d5bc4b9b60f1e6a934b1c81ecd5bb
82
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
bd25cba89c |
refactor: OAuth 2.0 endpoints (#27442)
* refactor: combine exchange and refresh into token endpoint * refactor: controller error handling * refactor: use snake_case * refactor: use snake_case * refactor: use snake case * refactor: token endpoint accepts application/x-www-form-urlencoded * refactor: token endpoint accepts application/x-www-form-urlencoded * refactor: flat token response data * refactor: error structure * refactor: client_id in the body * fix: address Cubic AI review feedback on OAuth2 endpoints - Fix getClient endpoint to use proper REST API error format instead of OAuth token error format (confidence 9/10) - Add missing space after comma in error format string in token.input.pipe.ts (confidence 9/10) - Support both camelCase and snake_case inputs in authorize endpoint for backward compatibility (confidence 10/10) - Restore legacy /exchange and /refresh endpoints alongside new /token endpoint for backward compatibility (confidence 10/10) - Add OAuth2TokensResponseDto for legacy endpoint wrapped responses - Add OAuth2LegacyExchangeInput and OAuth2LegacyRefreshInput for legacy endpoints Co-Authored-By: unknown <> * fix: address additional Cubic AI feedback on OAuth2 endpoints - Log errors when status code >= 500 in handleClientError (confidence 9/10) - Add Cache-Control: no-store and Pragma: no-cache headers to legacy /exchange and /refresh endpoints (confidence 9/10) Co-Authored-By: unknown <> * docs * Revert "fix: address additional Cubic AI feedback on OAuth2 endpoints" This reverts commit 39cc4aa3ebb9e59a171541d7010398425995ed89. * Revert "fix: address Cubic AI review feedback on OAuth2 endpoints" This reverts commit 97bf593186db04c0859f9ca30950c9e3e524019d. * docs * fix: address Cubic AI review feedback on OAuth2 endpoints - Fix getClient to use handleClientError instead of handleTokenError (confidence 10) - Restore legacy /exchange and /refresh endpoints for backward compatibility (confidence 9) - Fix RFC 6749 error format: use human-readable messages in error_description (confidence 9) - Fix errorDescription in OAuthService to use OAUTH_ERROR_REASONS mapping (confidence 9) Co-Authored-By: unknown <> * fix: address additional Cubic AI feedback on OAuth2 endpoints - Fix security issue: Replace 'CALENDSO_ENCRYPTION_KEY is not set' with generic 'Internal server configuration error' message (confidence 10/10) - Fix backward compatibility: Create OAuth2LegacyTokensDto with camelCase properties for legacy /exchange and /refresh endpoints (confidence 9/10) - Skipped: RFC 6749 error field issue (confidence 8/10, below threshold) Co-Authored-By: unknown <> * e2e * Revert "fix: address additional Cubic AI feedback on OAuth2 endpoints" This reverts commit a080e93f07aaf5a7dcf81fe605012cb7ebcdc192. * Revert "fix: address Cubic AI review feedback on OAuth2 endpoints" This reverts commit 04986a16c981521ca97069152457bf521a9ee45f. * fix: re-apply Cubic AI review feedback on OAuth2 endpoints - Restore OAuth2LegacyExchangeInput and OAuth2LegacyRefreshInput classes - Restore legacy /exchange and /refresh endpoints in OAuth2Controller - Restore OAuth2LegacyTokensDto and OAuth2TokensResponseDto classes - Restore OAUTH_ERROR_DESCRIPTIONS mapping in oauth2-error.service.ts - Restore OAUTH_ERROR_REASONS lookup in OAuthService.ts mapErrorToOAuthError - Fix encryption_key_missing error to not expose internal env var name Addresses Cubic AI feedback with confidence >= 9/10: - Comment 32 (9/10): Legacy endpoints and input classes - Comment 34 (9/10): Error description mapping in OAuthService - Comment 35 (10/10): OAUTH_ERROR_DESCRIPTIONS in error service Skipped (confidence < 9/10): - Comment 33 (8/10): getClient handleTokenError vs handleClientError Co-Authored-By: unknown <> * Revert "fix: re-apply Cubic AI review feedback on OAuth2 endpoints" This reverts commit 416bef9c931d9a7ed78c65a70a3425550d61b151. * delete unused file * fix: e2e tests * address cubic review * fix: address Cubic AI review feedback on OAuth2 exception filter - Fix header case sensitivity: use lowercase 'x-request-id' instead of 'X-Request-Id' since Express lowercases all request headers - Redact request body in error logs to prevent exposing sensitive OAuth2 credentials like client_secret, password, and refresh_token Co-Authored-By: unknown <> * docs: api v2 oauth controller docs * chore: remove authorize endpoint * refactor: remove scope from docs --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
7ec8601bd6 |
chore: Integrate edit location booking audit (#26569)
## What does this PR do? Integrates booking audit logging for the edit location functionality, following the pattern established in PR #26046 (booking creation/rescheduling audit). This PR adds audit logging when a booking's location is changed through: 1. **Web app** (tRPC handler): `packages/trpc/server/routers/viewer/bookings/editLocation.handler.ts` 2. **API v2**: `apps/api/v2/src/ee/bookings/2024-08-13/services/booking-location.service.ts` ### Changes: - Added `actionSource` as a **required** parameter to `editLocationHandler` (no fallback) - Added optional `userUuid` parameter (defaults to logged-in user's uuid) - Added `ValidActionSource` type that excludes "UNKNOWN" for client-facing APIs - Captures old location before update for audit data - Calls `BookingEventHandlerService.onLocationChanged()` after successful location update - Web app uses `actionSource: "WEBAPP"`, API v2 uses `actionSource: "API_V2"` - Updated router to explicitly pass `actionSource: "WEBAPP"` - Updated test to pass `actionSource: "WEBAPP"` - **API v2**: Uses NestJS dependency injection pattern with `BookingEventHandlerService` injected via constructor ### Updates since last revision: - **Created `BookingEventHandlerModule`** (`apps/api/v2/src/lib/modules/booking-event-handler.module.ts`) to encapsulate `BookingEventHandlerService` and its dependencies (Logger, TaskerService, HashedLinkService, BookingAuditProducerService) - Updated both bookings modules (2024-04-15 and 2024-08-13) to import `BookingEventHandlerModule` instead of listing individual providers - This reduces code duplication and makes dependency management cleaner ## 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 - using existing audit infrastructure that is already tested. ## How should this be tested? 1. Update a booking's location through the web app 2. Update a booking's location through API v2 3. Verify audit logs are created with: - Correct `bookingUid` - Correct `actor` (user who made the change) - Correct `source` ("WEBAPP" or "API_V2") - Correct `auditData.location.old` and `auditData.location.new` values ## Checklist - [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 ## Human Review Checklist - [ ] Verify all callers of `editLocationHandler` pass `actionSource` (router updated, test updated) - [ ] Verify `organizationId` derivation is correct in both handlers (tRPC uses `booking.user?.profiles?.[0]?.organizationId`, API v2 uses `existingBookingHost.organizationId`) - [ ] Confirm audit call placement after location update is intentional (audit failures would fail the operation even though location was already updated) - [ ] Note: API v2 has its own implementation and does NOT reuse `editLocationHandler` - this is correct - [ ] Verify `BookingEventHandlerModule` properly exports `BookingEventHandlerService` and is imported in both bookings modules - [ ] Verify the `updateBookingLocationInDb` return value (`{ updatedLocation }`) is destructured and used correctly for audit data - [ ] Verify API v2 uses `bookingLocation` for audit `new` value, while tRPC uses `updatedLocation` from DB update --- Link to Devin run: https://app.devin.ai/sessions/fd1d439779674050a26ea3fa7d799943 Requested by: @hariombalhara |
||
|
|
c60addc528 |
feat: add PlatformOrganizationBillingTasker with sync and trigger.dev versions (#26803)
* feat: add PlatformOrganizationBillingTasker with sync and trigger.dev versions - Create PlatformOrganizationBillingTasker extending Tasker base class - Add sync tasker (PlatformOrganizationBillingSyncTasker) for synchronous execution - Add trigger.dev tasker (PlatformOrganizationBillingTriggerTasker) for async execution - Create trigger.dev task for incrementing subscription usage - Add PlatformOrganizationBillingTaskService with business logic - Add PlatformOrganizationBillingRepository for data access - Add createSubscriptionUsageRecord method to StripeBillingService - Follow BookingEmailAndSmsTasker pattern for consistency Co-Authored-By: morgan@cal.com <morgan@cal.com> * refactor: move repository methods per PR feedback - Move findPlatformOrgByUserId to OrganizationRepository - Create new PlatformBillingRepository for billing queries - Remove PlatformOrganizationBillingRepository (consolidated) - Update task service and trigger.dev task to use new repositories Co-Authored-By: morgan@cal.com <morgan@cal.com> * feat: add DI using @evyweb/ioctopus for platform billing tasker - Create di/tasker/ directory following BookingEmailAndSmsTasker pattern - Add tokens.ts with DI tokens for all billing tasker classes - Add module files for PlatformBillingRepository, TaskService, SyncTasker, TriggerTasker, Tasker - Add container files with getter functions - Update trigger.dev task to use DI container instead of manual instantiation Co-Authored-By: morgan@cal.com <morgan@cal.com> * refactor: add select statement to PlatformBillingRepository.findByTeamId Only select subscriptionId field since that's the only field used by the task service Co-Authored-By: morgan@cal.com <morgan@cal.com> * feat: add NestJS DI modules for platform billing tasker in API v2 - Add platform billing tasker exports to platform-libraries/organizations.ts - Export IBillingProviderService type from platform-libraries - Create StripeBillingProviderService wrapper implementing IBillingProviderService - Create PrismaPlatformBillingRepository extending PlatformBillingRepository - Create NestJS service wrappers for all platform billing tasker classes - Create PlatformBillingTaskerModule with all providers and exports - Update PlatformOrganizationBillingTaskService to use Pick<IBillingProviderService> Co-Authored-By: morgan@cal.com <morgan@cal.com> * feat: handle cancel and reschedule usage * fix: restore IsUserInBillingOrg to billing module providers Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore: add idempotency key * fix: just log error] * fix: logger and typo * fix: address Cubic AI review feedback (high confidence issues) - Fix grammar error: 'Delayed task are' -> 'Delayed tasks are' in PlatformOrganizationBillingSyncTasker.ts (3 occurrences) - Re-throw error after logging in increment-usage.ts to enable trigger.dev retry mechanism Co-Authored-By: unknown <> * fix: remove duplicate code and use DI instead * fix: remove orThrow on find first in findPlatformOrgByUserId * refactor: prevent usage increment task from re-throwing errors --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
62216f2db6 |
feat: add CalendarsTasker with sync and trigger.dev versions (#26854)
* feat: add CalendarsTasker with sync and trigger.dev versions This PR implements a CalendarsTasker following the same pattern as PlatformOrganizationBillingTasker to replace the logic in apps/api/v2/src/ee/calendars/processors/calendars.processor.ts New files created: - CalendarsTasker main orchestrator extending Tasker base class - CalendarsSyncTasker for sync execution - CalendarsTriggerTasker for async execution via trigger.dev - CalendarsTaskService with business logic for ensuring default calendars - trigger.dev task with queue config and retry settings - DI modules using @evyweb/ioctopus - NestJS DI modules for API v2 Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: import and deasync * style: format trigger.config.ts dirs array Co-Authored-By: unknown <> * refactor: move prisma query to UserRepository and set onboarding to true Co-Authored-By: morgan@cal.com <morgan@cal.com> * refactor: remove credential.key from UserRepository method Co-Authored-By: morgan@cal.com <morgan@cal.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
2227d990b6 |
refactor: replace loggedInUsersTz with timeZone property in busy-times API (#25440)
* refactor: replace loggedInUsersTz with timeZone in busy-times API - Add new timeZone parameter to CalendarBusyTimesInput - Mark loggedInUsersTz as deprecated - Update getBusyTimes endpoint to prioritize timeZone parameter - Maintain backward compatibility with loggedInUsersTz - Add validation to ensure at least one timezone parameter is provided - Update API documentation with new parameter example Fixes #25423 * fix: improve timezone validation in CalendarBusyTimesInput - Use custom ValidatorConstraint instead of problematic ValidateIf - Properly validate that at least one timezone parameter is provided - Improve code quality and clarity * fix: update DTOs for getBusyTimes * cleanup * fix: abstract normalize timezone logic into platform types util function * chore: update e2e tests * fixup * fixup --------- Co-authored-by: Ryukemeister <sahalrajiv6900@gmail.com> Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in> |
||
|
+47 |
a7a8c78494 |
chore: [Booking Cancellation Refactor - 2] Inject repositories and use them instead of Prisma in cancellation flow (#24159)
* chore: Inject repositories instead of Prisma in canellation flow * simplify * simplify * fix formatting issue * chore: resolve merge conflicts for PR #24159 (#26820) * matched colour of icons across website (#26394) * fix(auth): resolve session user by token subject ID (#26399) * fix(auth): align session user resolution with token subject * test(auth): add unit tests for getServerSession user resolution * chore: release v6.0.7 * fix: Custom time input for availability (#26373) * add custom time input * add unit test * add validation logic * feat(companion): Add DropdownMenu and Alert Dialog for Android (#26385) * feat(companion): add DropdownMenu for Android event types list Replace Alert.alert with react-native-reusables DropdownMenu component for Android event type list items, providing a native-feeling menu experience that matches iOS functionality. Changes: - Install react-native-reusables dropdown-menu component and dependencies (lucide-react-native, tailwindcss-animate, class-variance-authority, clsx, tailwind-merge) - Create EventTypeListItem.android.tsx with DropdownMenu implementation - Single ellipsis button triggers dropdown menu - Menu includes: Preview, Copy link, Edit, Duplicate, Delete - Delete action marked as destructive variant - Proper safe area insets handling - Add PortalHost to app/_layout.tsx for portal rendering support - Create lib/utils.ts with cn() helper for className merging - Update global.css with theme CSS variables (popover, border, accent, destructive, etc.) for dropdown menu styling - Update tailwind.config.js with theme colors and tailwindcss-animate plugin - Update metro.config.js with inlineRem: 16 for proper rem unit handling - Remove Android Alert.alert fallback from event types index.tsx - Fix lint issues in generated dropdown-menu.tsx (remove unnecessary fragments) The Android experience now matches iOS with a single menu button that opens a dropdown containing all event type actions, replacing the previous Alert.alert dialog and separate action buttons. Refs: https://reactnativereusables.com/docs/components/dropdown-menu * adjust with of menu * feat(companion): add DropdownMenu for Android booking and availability list items - Add BookingListItem.android.tsx with DropdownMenu for booking actions - Add BookingDetailScreen.android.tsx with DropdownMenu in header - Add AvailabilityListItem.android.tsx with DropdownMenu for schedule actions Actions include: Reschedule, Edit Location, Add Guests, View Recordings, Meeting Session Details, Mark as No-Show, Report Booking, Cancel Event for bookings; Set as Default, Duplicate, Delete for availability schedules. * fix lint issues * feat(android): replace native alerts with AlertDialog and Toast in event types - Install AlertDialog and Alert components from react-native-reusables - Create Android-specific event types screen (index.android.tsx) - Replace native Alert.alert() with AlertDialog for delete confirmation - Add inline validation errors (red border + error text) in create modal - Implement Toast snackbar for success/error notifications (no layout shift) - Auto-dismiss toast after 2.5 seconds - Fix React Compiler compatibility by removing animated refs This provides a more consistent and polished UI experience on Android, matching the design system used in other parts of the app. * feat(android): add AlertDialog for availability delete and booking cancel - Add index.android.tsx for availability with AlertDialog for delete confirmation - Add index.android.tsx for bookings with AlertDialog for cancel (with reason input) - Both screens include Toast snackbar for success/error notifications - Follows the same pattern as event types Android implementation * feat(companion): add DropdownMenu and AlertDialog for Android - Replace native Alert.alert context menus with DropdownMenu component for event types, bookings, and availability lists - Replace FullScreenModal with AlertDialog for create/delete/cancel flows - Add toast notifications for success/error feedback on Android - Set consistent 380px max-width for all AlertDialogs - Fix layout headers showing "index" text on event-types and availability - Create Android-specific More screen with AlertDialog logout confirmation Uses react-native-reusables components for polished Android UI * better code * fix cubics comments * refactor(android): revert delete confirmations to native Alert.alert() - Logout: reverted to native Alert.alert() (simple yes/no) - Event Types Delete: reverted to native Alert.alert() (simple yes/no) - Availability Delete: reverted to native Alert.alert() (simple yes/no) Keep AlertDialog only where user input is needed: - Event Types Create (has TextInput for title) - Availability Create (has TextInput for name) - Bookings Cancel (has TextInput for cancellation reason) * refactor(android): remove redundant index.android.tsx files The main index.tsx files already handle Android via Platform.OS checks. Android-specific behavior for actions is in the list item components: - EventTypeListItem.android.tsx - BookingListItem.android.tsx - AvailabilityListItem.android.tsx This consolidates the code and reduces duplication. * corrected the implementation both native and alert dialog * address cubics comments * fix lint issue and address cubic comments * chore: add logging in next-auth (#26404) * Add logging in next-auth * Add logging at other return * fix: Make incomplete booking form mobile-responsive (#26413) * fix: update bundle identifier (#26402) * fix: patch React 19 vulnerabilities by upgrading to 19.2.3 (#26411) * security: patch React 19 vulnerabilities by upgrading to 19.2.3 * chore: revert lingo.dev upgrade * refactor(companion): event type details screen improvements (#26415) * refactor(companion): move EventTypeDetail component to a new file and update routing * refactor(companion): format code for better readability in TabLayout and EventTypeDetail components * refactor(companion): improve code formatting and readability in EventTypeDetail component * refactor(companion): enhance code readability and formatting in EventTypeDetail component * refactor(companion): improve code formatting and readability in EventTypeDetail component * refactor(companion): enhance code formatting and readability in EventTypeDetail component * refactor(companion): improve code formatting and readability in TabLayout component * fix: add vertical spacing when hovered (#26419) * fix(seed): add missing Host entries for seeded round‑robin team events (#26426) * feat(companion): new availability detail and actions pages for ios (#26424) * version 1 * version 1.1 * better code * covered all edge cases * address cubics comments * address cubics comments * fix(auth): enhance SAML login handling by introducing userId field and updating JWT token structure (#26428) * fix(ci): delete old prod build caches on cache miss (#26437) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(ci): add yarn prisma generate before cache key generation (#26439) This ensures consistent cache keys between the Build Web App job and E2E shards by running yarn prisma generate before generating the cache key. The issue was that packages/prisma/enums/index.ts is: 1. Generated by yarn prisma generate 2. In .gitignore (not committed to git) 3. Included in the SOURCE_HASH (matches packages/**/**.[jt]s) 4. NOT excluded from the hash E2E jobs already run yarn prisma generate before cache-build, but the Build Web App job did not, causing different cache keys in the same workflow run. Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: show empty screen from event type availability tab (#26396) * fix * update * fix * Remove copying of App Store static files step Removed step to copy App Store static files from the workflow. * feat: queue or cancel payment reminder flow (#24889) Co-authored-by: Pallav <90088723+Pallava-Joshi@users.noreply.github.com> Co-authored-by: Ryukemeister <sahalrajiv6900@gmail.com> Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in> Co-authored-by: Peer Richelsen <peeroke@gmail.com> * feat: integrate BookingHistory with Bookings V3 design (#26301) * Integrate BookingHistory with Bookings V3 design * Enhance booking features by integrating booking audit functionality - Updated the booking page to retrieve user feature statuses for "bookings-v3" and "booking-audit". - Modified BookingDetailsSheet and BookingListContainer components to accept and utilize the new bookingAuditEnabled prop. - Adjusted the BookingHistory display logic to conditionally render based on the bookingAuditEnabled state. - Refactored SegmentedControl to support generic types for better type safety. This change improves the user experience by allowing conditional access to booking audit features based on user permissions. * Refactor BookingDetailsSheet to manage active segment state with Zustand store - Removed local state management for active segment in BookingDetailsSheet and integrated Zustand store for better state synchronization. - Introduced useActiveSegmentFromUrl hook to sync active segment with URL query parameters. - Updated BookingDetailsSheet to handle derived active segment logic based on bookingAuditEnabled state. - Adjusted SegmentedControl to ensure it defaults to "info" when activeSegment is null. This refactor enhances the maintainability and responsiveness of the booking details component. * refactor: rename useBiDirectionalSyncBetweenZustandAndNuqs to useBiDirectionalSyncBetweenStoreAndUrl Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> --------- Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat: create BookingHistoryViewerService to combine audit logs with routing form submissions (#26045) * feat: create BookingHistoryViewerService to combine audit logs with routing form submissions Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * refactor(booking): rename audit log query and enhance type safety - Updated the booking logs view to use the new getBookingHistory query instead of getAuditLogs. - Introduced DisplayBookingAuditLog type for improved clarity in BookingAuditViewerService. - Refactored BookingHistoryViewerService to utilize the new DisplayBookingAuditLog type and added sorting functionality for history logs. - Adjusted related types and methods to ensure consistency across services. * refactor(routing-forms): streamline imports and enhance type definitions - Consolidated type exports and imports from the features library for better organization. - Removed redundant type definitions and functions in zod.ts, findFieldValueByIdentifier.ts, getFieldIdentifier.ts, and parseRoutingFormResponse.ts. - Introduced new utility functions for handling field responses and parsing routing form responses. - Improved type safety and clarity across routing form response handling. * fix: remove double prefix from uniqueId in form submission entry Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * 1c97f9cc5d50416788c01876fe539bcc9750e9b2 (#26453) --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * chore: Ensure that uuid is available in server session[Booking Audit Prerequisite] (#25963) ## What does this PR do? Similar to #25721, adds uuid in session so that BookingAudit has it readily available Adds the user's UUID to the booking metadata by: 1. Extending the NextAuth `User` interface to include an optional `uuid` property from PrismaUser 2. Making `uuid` required on `Session.user` via intersection type (`User & { uuid: PrismaUser["uuid"] }`) 3. Adding `uuid` to the session user object in `getServerSession.ts` 4. Adding `uuid` to the `AdapterUser` transformation in `next-auth-custom-adapter.ts` 5. Passing `userUuid` from the session to the booking creation flow 6. Updating the API key verification flow to include `uuid` in the user data (repository, service, and type definitions) 7. Adding `req.userUuid` as a required field on the request object (like `req.userId`) 8. Adding `uuid` to mock session objects in web app routes and test context 9. Adding `uuid` to the `findByEmailAndIncludeProfilesAndPassword` query in UserRepository Also removes commented-out code that was placeholder for future work and fixes lint warnings for unused variables. ## 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. ## How should this be tested? 1. Verify that the NextAuth session callback is already populating the `uuid` field on the user object 2. Create a booking and confirm `userUuid` is included in the booking metadata 3. Test API v1 endpoints (`/api/invites` POST and `/api/teams/[teamId]/publish`) to verify they receive the uuid from the authenticated user 4. Check that the booking flow works correctly with the new parameter 5. Test SAML login flow to verify session still works correctly (uuid is resolved from database after authentication) ## Human Review Checklist - [ ] Verify the NextAuth session callback populates `uuid` - if not, this change will pass `undefined` at runtime - [ ] Confirm `userUuid` is consumed downstream in the booking service - [ ] Verify that `PrismaApiKeyRepository.findByHashedKey()` correctly fetches the user's uuid from the database - [ ] Verify the discriminated union type in `ApiKeyService.ts` ensures `result.user` is always defined when `result.valid` is true - [ ] Confirm all API v1 endpoints using `req.userUuid` go through the `verifyApiKey` middleware - [ ] Verify `UserRepository.findByEmailAndIncludeProfilesAndPassword()` includes `uuid` in the select clause - [ ] Verify SAML login still works correctly - uuid is now optional on User interface so SAML providers don't need to supply it at profile stage ## Updates since last revision - **Made uuid optional on User, required on Session**: Changed the type strategy so `uuid` is optional on the NextAuth `User` interface but required on `Session.user` via intersection type. This allows SAML providers to not supply uuid at the profile stage while ensuring uuid is always present on the session after the user is resolved from the database. - **Removed uuid from SAML functions**: Since uuid is now optional on User, the SAML profile and authorize functions no longer need to include it. --- Link to Devin run: https://app.devin.ai/sessions/97e5603b719a420b9b35041252c9db26 Requested by: hariom@cal.com (@hariombalhara) * fix: add @calcom/trpc#build dependency to @calcom/web#dev task (#26460) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(auth): make identityProviderId lookup case-insensitive (#26405) SAML IdPs may send NameIDs with different casing than stored, causing login failures. Aligns with the existing case-insensitive email lookup pattern * fix: cancel running CI workflow before re-triggering and allow trusted GitHub Apps (#26461) * fix: cancel running CI workflow before re-triggering and allow trusted bots Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: remove hardcoded bot allowlist, keep only cancel-and-rerun improvement Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: add app_id verification for trusted GitHub Apps (Graphite) Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: simplify trusted bot check to use sender type, login, and installation context Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * chore: remove unnecessary comments Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat: update translations via @LingoDotDev (#26445) Co-authored-by: Lingo.dev <support@lingo.dev> Co-authored-by: Keith Williams <keithwillcode@gmail.com> * fix: remove installation requirement from trusted bot check (#26466) * fix: remove installation requirement from trusted bot check The installation object is not present in the webhook payload when GitHub Apps add labels via pull_request_target events. This caused graphite-app[bot] to fail the authorization check and fall through to the human permission check, which doesn't work for bots. The fix removes the installation requirement and relies on: - sender.type === 'Bot' - sender.login matching the trusted bot list This is secure because the sender fields come from GitHub's webhook payload and cannot be forged by contributors. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * chore: add extra logging about sender type Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * chore: remove senderId from logging Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * Update run-ci.yml --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor: Move trpc-dependent components from features to web [2] (#26420) * fix * move event types components to web * update import paths * mv apps components * migrate form builder * fix * mv sso * fix * mv * update import paths * update import paths * mv * mv * mv * fix * update Booker * fix * fix * fix * fix * mv video * mv embed components to web * update import paths * mv calendar weekly view components * update import paths * fix * fixp * fix * fix * fix * fix: update FormBuilder imports to use @calcom/features/form-builder Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: update broken import paths after file migrations Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: correct import paths for platform atoms and moved components Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: apply CSS type fixes and add missing atoms exports Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: resolve type errors in test files after component migrations Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: resolve remaining type errors in test files Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix * migrate * fix: resolve type errors in test and mock files - Add missing bookingForm, bookerFormErrorRef, instantConnectCooldownMs to Booker.test.tsx bookings prop - Add all required BookerEvent properties to event.mock.ts - Add vi import from vitest to all mock files - Fix date parameter types in packages/dayjs/__mocks__/index.ts - Add verificationCode and setVerificationCode to test-utils.tsx mock store - Remove children.type access in Section.tsx mock to fix type error - Fix lint issues: remove unused React imports, use import type where needed, add return types - Add biome-ignore comments for pre-existing lint warnings in test files Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * migrate * migrate * migrate * update import paths * update import paths * update import paths * fix * migrate data table * migrate data table * fix * fix * fix * migrate insights components * migrate insights components * fix * mv * update import paths * fix * fix * fix * fix * fix * fix: resolve type errors in test mocks - Booker.test.tsx: Add all required UseFormReturn methods to bookingForm mock - event.mock.ts: Fix entity, subsetOfHosts, instantMeetingParameters, fieldTranslations, image types - dayjs/__mocks__/index.ts: Use Object.assign for proper typing of mock properties - Section.tsx: Change 'class' to 'className' in JSX with biome-ignore comment Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: add missing hasDataErrors and dataErrors to bookings.errors mock Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: add missing loadingStates properties to bookings mock Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: add missing slots properties (setTentativeSelectedTimeslots, tentativeSelectedTimeslots, slotReservationId) Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: update quickAvailabilityChecks to include utcEndIso and use valid status type Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: add missing bookerForm properties (formName, beforeVerifyEmail, formErrors) Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: add missing UseFormReturn properties to bookerForm.bookingForm mock Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: add hasFormErrors and formErrors to bookerForm.formErrors mock Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: add hasFormErrors and formErrors to bookerForm.errors mock Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: add missing isError property to mockEvent Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: use complete BookerEvent mock in Booker.test.tsx Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: use branded bookingFields type in event mock Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: add missing schedule mock properties (isError, isSuccess, isLoading, dataUpdatedAt) Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * revert * fix * fix * fix * fix build * fix * fix * fix * fix: correct AddMembersWithSwitch test wrapper to use initial assignAllTeamMembers value - Fixed test wrapper to initialize useState with componentProps.assignAllTeamMembers instead of hardcoded false, allowing tests to properly test different states - Updated test expectations for ALL_TEAM_MEMBERS_ENABLED_AND_SEGMENT_NOT_APPLICABLE state to match actual component behavior (toggle should be present and checked) - Fixed 'should show Segment when toggled on' test to start with assignAllTeamMembers: false to properly test the flow of enabling it - Added explicit types to satisfy biome lint requirements Co-Authored-By: benny@cal.com <sldisek783@gmail.com> * fix: use JSX.Element instead of React.JSX.Element for type compatibility Co-Authored-By: benny@cal.com <sldisek783@gmail.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * chore(deps): update dependencies and add version constraints (#26390) - Update sanitize-html to 2.17.0 - Remove unused Storybook dependencies from @calcom/ui - Add resolutions for consistent dependency versions - Clean up packageExtensions * feat: add lightweight E2E session warmup page (#26451) * feat: add lightweight E2E session warmup endpoint - Add /api/__e2e__/session-warmup endpoint that triggers NextAuth session loading - Update apiLogin fixture to use the new endpoint instead of navigating to /settings/my-account/profile - The endpoint is gated by NEXT_PUBLIC_IS_E2E=1 (already set in playwright.config.ts) - This reduces overhead in E2E tests by avoiding loading a full UI page just to warm up the session Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * refactor: move session warmup endpoint to App Router - Move /api/__e2e__/session-warmup from pages/api to app/api - Use App Router patterns (NextResponse, buildLegacyRequest) - Maintains same functionality for E2E session warming Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * rename path * refactor: switch from API route to minimal SSR page (Option 2) - Replace /api/e2e/session-warmup API route with /e2e/session-warmup page - Use App Router page pattern with getServerSession for session warmup - Update apiLogin fixture to navigate to the page instead of API request Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * revert users fixture but with a new url * render nothing on success * clean up * trying something * Revert "trying something" This reverts commit 2ae2f7dcb42612e54eb072a9f09857272020889a. --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Keith Williams <keithwillcode@gmail.com> * Disable noReactSpecificProps as we use react (#26479) * fix(auth): fix SAML tenant extraction and validation (#26482) - Extract tenant from userInfo in saml-idp (IdP-initiated) - Add profile.requested?.tenant fallback for OAuth (SP-initiated) - Block invalid tenant format in hosted (security) * fix: atoms build by updating import paths (#26489) * fix build * fix build * fix: "New" button sizing inconsistent between Workflows and Event Types pages (#26066) * fix: consistent button sizing between fab and button variants on desktop * fix: consistent button sizing between fab and button variants on desktop * fix(ui): align New button sizing across pages * fix: New button sizing inconsistent between Workflows and Event Types pages * Update Button.tsx * test: fix unit test flake (#25557) * fix: revalidate teams cache after accepting invite via token When a user accepts a team invite via token on the /teams page, the teams cache was not being invalidated. This caused the page to show stale data (empty list) while the sidebar correctly showed the teams. This fix adds a call to revalidateTeamsList() after processing an invite token, ensuring the cache is invalidated and fresh data is fetched immediately. Co-Authored-By: anik@cal.com <adhabal2002@gmail.com> * fix: revalidate teams cache after creating team in onboarding flow Co-Authored-By: anik@cal.com <adhabal2002@gmail.com> * Remove comments on teams cache revalidation Removed comments about revalidating teams cache after invite processing. * fix unit test flake * Remove unused import in useCreateTeam hook Removed unused import for revalidateTeamsList. * Remove unused import for revalidateTeamsList --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * chore: Add impersonation context support to booking audit (#26014) ## What does this PR do? Adds infrastructure to track impersonation context in booking audit records and displays it in the UI. When an admin impersonates another user and performs booking actions, the audit system now: - Records the **admin** as the actor (who actually performed the action) - Stores the **impersonated user's UUID** in a separate `context` field - Displays **"Impersonated By"** in the booking logs UI when viewing audit details This separation ensures audit trail integrity (the admin is accountable) while preserving full context about whose account was being used. ### Changes - Added `uuid` to `impersonatedBy` session object for actor identification - Added `uuid` to top-level `User` type in next-auth types for session enrichment - Added `context Json?` field to `BookingAudit` Prisma model - Added `BookingAuditContextSchema` for type-safe context handling with `actingAsUserUuid` field - Updated producer service interface and implementation to pass context through all queue methods - Updated consumer service to persist context to database - Updated repository to store and fetch context in BookingAudit records - Added `impersonatedBy` field to `EnrichedAuditLog` type in `BookingAuditViewerService` - Added `enrichImpersonationContext` method to resolve impersonated user details - Updated booking logs UI to display "Impersonated By" in expanded details - Added `impersonated_by` translation key Link to Devin run: https://app.devin.ai/sessions/3f1252527aef4ead9401bdf055c0817b Requested by: hariom@cal.com (@hariombalhara) ## 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 - internal infrastructure change - [ ] I confirm automated tests are in place that prove my fix is effective or that my feature works. ## How should this be tested? 1. Verify type checks pass: `yarn type-check:ci --force` 2. Verify existing audit tests still pass: `TZ=UTC yarn test` 3. To fully test impersonation context display: - Have an admin impersonate a user - Perform a booking action (create, cancel, reschedule) - Navigate to the booking's audit logs - Expand the details for the action - Verify "Impersonated By" row appears showing the impersonated user's name - Verify the BookingAudit record has: - `actorId` pointing to the admin's AuditActor - `context` containing `{ actingAsUserUuid: "<impersonated-user-uuid>" }` ## Human Review Checklist - [ ] Verify the `context` field schema design is appropriate for future extensibility - [ ] Confirm the `uuid` addition to User type in next-auth doesn't break existing auth flows - [ ] Check that the optional `context` parameter doesn't break existing queue method callers - [ ] Verify no migration file is needed (or if squashing is handled separately) - [ ] Verify the UI displays "Impersonated By" correctly when impersonation context is present - [ ] Confirm `enrichImpersonationContext` handles edge cases (null context, invalid context, deleted user) ## Checklist - [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 * perf: improve cal video webhook (#26495) * perf: improve cal video webhook * save format * refactor: use errorMs * chore: change API codeowner to Foundation (#26504) * chore(auth): add error logging for saml-idp silent failures (#26484) * chore(auth): add error logging for saml-idp silent failures * chore(auth): add warn-level logging for saml-idp silent failures * chore(auth): change 'No user found' log to warn level * chore(auth): add warn-level logging for silent auth failures - saml-idp authorize: credentials, code, token, userInfo, user lookup - callbacks:signIn: account type, email, name, catch-all - callbacks:jwt: unknown account type (info → warn) - saml:profile: missing email from IdP - getServerSession: user not found for valid token * feat(api): add team event-types webhooks controller (#26449) * feat(api): add team event-types webhooks controller - Add TeamsEventTypesWebhooksController for managing webhooks on team event types - Add IsTeamEventTypeWebhookGuard for authorization - Add TeamEventTypeWebhooksService for business logic - Register new controller in TeamsEventTypesModule - Enable unsafeParameterDecoratorsEnabled in biome.json for NestJS support Co-Authored-By: morgan@cal.com <morgan@cal.com> * test(api): add e2e tests for team event-types webhooks controller Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix(api): restrict team event-type webhooks to admins/owners only Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix(api): use regular imports instead of type imports for DI and DTOs Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix(api): use regular imports for DI in guard file Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: circular depndency in modules * delete teams in test * fix roles guard * fix biome * fix guard * resolve type import * resolve review feedback --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * chore: remove Mintlify AI chat from CMD+K widget (#26485) * chore: remove Mintlify AI chat from CMD+K widget - Remove MintlifyChat component and related state from Kbar.tsx - Delete packages/features/mintlify-chat directory (MintlifyChat.tsx, util.ts) - Delete apps/web/app/api/mintlify-chat API routes and tests - Delete packages/lib/server/mintlifyChatValidation.ts - Remove Mintlify-related env vars from .env.example and turbo.json - Refactor Kbar.tsx to fix lint issues (explicit types, exports at end) Co-Authored-By: peer@cal.com <peer@cal.com> * fix: use ReactNode import instead of JSX from react The JSX type is not exported from 'react' module. Use the global JSX.Element type (available in React projects) and import ReactNode for the children prop type. Co-Authored-By: peer@cal.com <peer@cal.com> * feat: add all event-types and upcoming bookings to KBar - Increase event types limit from 10 to 100 to show more event types - Add useUpcomingBookingsAction hook to fetch and display upcoming bookings - Bookings show title, date, and time in KBar search results - Navigate to booking details page when selecting a booking Co-Authored-By: peer@cal.com <peer@cal.com> * Revert "feat: add all event-types and upcoming bookings to KBar" This reverts commit 69d03397e3820e45e7207eb55b38117d269eae5e. --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat: update translations via @LingoDotDev (#26497) Co-authored-by: Lingo.dev <support@lingo.dev> * feat: implement FeatureOptInService (#25805) * feat: implement FeatureOptInService WIP * clean up * feat: consolidate feature repositories and add updateFeatureForUser - Implement updateFeatureForUser in FeaturesRepository (similar to updateFeatureForTeam) - Move getUserFeatureState and getTeamFeatureState from PrismaFeatureOptInRepository to FeaturesRepository - Update FeatureOptInService to use only FeaturesRepository - Add setUserFeatureState and setTeamFeatureState methods to FeatureOptInService - Update _router.ts to remove PrismaFeatureOptInRepository usage - Remove PrismaFeatureOptInRepository.ts and FeatureOptInRepositoryInterface.ts - Update features.repository.interface.ts and features.repository.mock.ts - Add integration tests for updateFeatureForUser, getUserFeatureState, getTeamFeatureState - Update service.integration-test.ts to use FeaturesRepository Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * refactor: rename updateFeatureForUser to setUserFeatureState Rename to match the convention used for setTeamFeatureState Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * refactor: return FeatureState type from getUserFeatureState and getTeamFeatureState * fix integration tests * clean up logics * update services and router * refactor: change getUserFeatureState and getTeamFeatureState to accept featureIds array - Renamed getUserFeatureState to getUserFeatureStates - Renamed getTeamFeatureState to getTeamFeatureStates - Changed parameter from featureId: string to featureIds: string[] - Changed return type from FeatureState to Record<string, FeatureState> - Updated FeatureOptInService to use the new batch methods - Added tests for querying multiple features in a single call - Optimized listFeaturesForTeam to fetch all feature states in one query Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * feat: add getFeatureStateForTeams for batch querying multiple teams - Added getFeatureStateForTeams method to query a single feature across multiple teams in one call - Updated FeatureOptInService.resolveFeatureStateAcrossTeams to use the new batch method - Replaces N+1 queries with a single database query for team states - Added comprehensive integration tests for the new method Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * refactor: combine org and team state queries into single call - Include orgId in the teamIds array passed to getFeatureStateForTeams - Extract org state and team states from the combined result - Reduces database queries from 3 to 2 in resolveFeatureStateAcrossTeams Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * refactor: use team.isOrganization and clarify computeEffectiveState comment Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * refactor: use MembershipRepository.findAllByUserId with isOrganization Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * feat: add featureId validation using isOptInFeature type guard Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * less queries * add fallback value * fix type error * move files * add autoOptInFeatures column * use autoOptInFeatures flag within FeatureOptInService * add setUserAutoOptIn and setTeamAutoOptIn * fix computeEffectiveState logic * rewrite computeEffectiveState * clean up integration tests * clean up in afterEach * fix type error * refactor: use FeaturesRepository methods instead of direct Prisma calls Replace all manual userFeatures and teamFeatures Prisma operations with the new setUserFeatureState and setTeamFeatureState repository methods. Changes include: - Admin handlers (assignFeatureToTeam, unassignFeatureFromTeam) - Test fixtures and integration tests - Playwright fixtures - Development scripts This ensures consistent feature flag management through the repository pattern and supports the new tri-state semantics (enabled/disabled/inherit). Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * clean up * fix the logic * extract some logic into applyAutoOptIn() * remove wrong code * refactor: convert setUserFeatureState and setTeamFeatureState to object params with discriminated union - Convert multiple positional parameters to single object parameter - Use discriminated union types: assignedBy required for enabled/disabled, omitted for inherit - Update all callers across repository, service, handlers, fixtures, and tests * fix type error * use Promise.all * fix --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat: add organization banner to user profile page (#26514) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat: Hubspot write to meeting object (#26039) * feat: Hubspot write to meeting object * fix: translate hardcoded strings and remove debug console.log Co-Authored-By: amit@cal.com <samit91848@gmail.com> * refactor * fix: improve static value detection for placeholder replacement - Changed condition from startsWith/endsWith to includes('{') to properly detect embedded placeholders - Strings like 'Hello {name}!' are now correctly processed for placeholder replacement - Pure placeholder tokens that can't be resolved return null - Partially resolved values are returned as-is Co-Authored-By: amit@cal.com <samit91848@gmail.com> * refactor: split WriteToObjectSettings into types and utils files - Extract interfaces, enums, and type definitions to WriteToObjectSettings.types.ts - Extract constants and utility functions to WriteToObjectSettings.utils.ts - Update main component to use the new utility functions - Improves code organization and maintainability Co-Authored-By: amit@cal.com <samit91848@gmail.com> * revert: restore original static value detection logic Per user request - the startsWith/endsWith check was intentional Co-Authored-By: amit@cal.com <samit91848@gmail.com> * test: add unit tests for HubSpot CRM service Tests cover: - ensureFieldsExistOnMeeting: field validation against HubSpot properties - getTextValueFromBookingTracking: UTM parameter extraction - getTextValueFromBookingResponse: placeholder replacement - getDateFieldValue: date field resolution for different date types - getFieldValue: main field value resolution for all field types - generateWriteToMeetingBody: write-to-meeting body generation - getContacts: contact search functionality Co-Authored-By: amit@cal.com <samit91848@gmail.com> * fix: correct type errors in HubSpot CRM service tests - Import WhenToWrite enum from crm-enums - Replace string literals with WhenToWrite.EVERY_BOOKING enum values - Add missing whenToWrite property to field config objects Co-Authored-By: amit@cal.com <samit91848@gmail.com> * fix: use type casting for intentional type errors in tests - Cast numeric fieldValue to string for testing non-string handling - Cast invalid field type string to CrmFieldType for testing unsupported types Co-Authored-By: amit@cal.com <samit91848@gmail.com> * fix: prevent unhandled promise rejections in HubSpot CRM tests - Re-apply mockGetAppKeysFromSlug implementation in beforeEach to ensure mock is always set correctly after clearAllMocks - Change vi.resetAllMocks() to vi.clearAllMocks() to preserve mock implementations between tests - Add explicit types to satisfy biome lint rules - This fixes the 'Cannot read properties of undefined (reading client_id)' errors that were causing CI to fail with exit code 1 Co-Authored-By: amit@cal.com <samit91848@gmail.com> * refactor: convert HubSpot tests to black-box testing through public methods Co-Authored-By: amit@cal.com <samit91848@gmail.com> * fix: properly type mock CalendarEvent in HubSpot tests Co-Authored-By: amit@cal.com <samit91848@gmail.com> * fix: properly type TFunction in mock CalendarEvent Co-Authored-By: amit@cal.com <samit91848@gmail.com> * chore: graceful owner fail test * refactor * fix: type check * fix: remove null fields * Update packages/app-store/hubspot/lib/CrmService.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> * docs: add DTO location and naming conventions to knowledge base (#26478) * docs: add DTO location and naming conventions to knowledge base Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * docs: clarify DTO location rules for new features vs refactored code Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> * docs: simplify DTO location - all DTOs go in packages/lib/dto/ Co-Authored-By: eunjae@cal.com <hey@eunjae.dev> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor: convert PrismaAttributeToUserRepository to accept Prisma as dependency (#26515) * refactor: convert PrismaAttributeToUserRepository to accept Prisma as dependency Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com> * fix: use Prisma types from generated client instead of custom types Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: handle existing users on invite token flow (#26217) * fix(auth): validate user before signup with invite token Validate if user already exists before creating account when signing up with team or organization invite tokens. Existing users are redirected to login to accept the invitation. - Add user existence check in signup handlers - Return 409 for existing users with redirect to login - Extract signup fetch logic to dedicated module - Add e2e test coverage * fix(auth): address code review feedback - Fix fetchSignup tests to use vi.spyOn for proper mock restoration - Add content-type validation before parsing JSON response - Guard against undefined error in Stripe callback - Use t() for localized error message - Fix race condition in handlers by catching P2002 on create * fix(auth): address additional code review feedback - Add INVALID_SERVER_RESPONSE constant to follow established pattern - Check error.meta.target includes email before returning USER_ALREADY_EXISTS to avoid false positives from other unique constraint violations - Add select: { id: true } to user.create calls since downstream functions only need the user id * test: add unit tests for P2002 handling in signup handlers - Add shared test suite covering all P2002 edge cases - Ensure 409 only for email constraint violations - Fix non-token paths to use atomic create + catch pattern * fix: update error message copy per review feedback * fix(auth): address code review feedback and prevent orphan Stripe customers - Add user existence check before Stripe customer creation (token flow) - Add select clause to user.create for consistency - Fix showToast argument order (pre-existing bug) - Use toHaveURL instead of waitForURL in E2E tests * fix(auth): resolve 500 errors by fixing Prisma error detection across module boundaries The instanceof check for PrismaClientKnownRequestError fails when different Prisma client instances are loaded. Added fallback check by constructor name * fix(auth): validate invitedTo before upsert on team invite signup * test(auth): update P2002 tests for new invite flow P2002 tests now use non-token flow since token flow uses upsert Added tests for invitedTo validation on invite signup * fix(auth): add guards and P2002 handling per review feedback - Guard existingUser check with if (foundToken?.teamId) - Guard username check with if (username) for premium flow - Add `select` clause to findFirst/findUnique queries - Add try-catch on upsert for race condition P2002 errors * fix(auth): narrow P2002 handling to email/username targets * chore: release v6.0.8 * fix: Support 10-digit phone numbers for Ivory Coast (+225) (#26465) * fix: update ivory coast mask to 10 digits * update formating for Benin numbers --------- Co-authored-by: Dhairyashil Shinde <93669429+dhairyashiil@users.noreply.github.com> Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com> * fix(ci): use env vars for input interpolation in workflow run steps (#26520) Co-authored-by: Alex van Andel <me@alexvanandel.com> * refactor: use structured logger in video adapters (#26285) - Remove debug console.log/console.error statements - Add logger.debug for observability (meeting lifecycle events) - Add logger.error with safe error pattern (message + name only) - Fix error messages to avoid exposing response details - Remove redundant try/catch blocks (errors propagate naturally) * fix: validate owner email on platform org creation (#26286) Remove isPlatform bypass from owner verification to ensure users can only create organizations where they are the designated owner. Add test coverage for create and intentToCreateOrg handlers: - Regression tests for isPlatform bypass fix - Happy path for admin creating org for another user * perf: batch booking queries in output service (#25900) Replace N sequential queries with single batch queries in: - getOutputRecurringBookings - getOutputRecurringSeatedBookings Uses existing batch repository methods. Reduces database roundtrips from O(n) to O(1) for recurring booking lookups Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> * Make booking-audit integration test utils reusable (#26526) * fix: generate compliant passwords using meeting_password_requirement (#26148) * fix(zoomvideo): generate compliant passwords using meeting_password_requirement - Add meetingPasswordRequirementSchema to parse Zoom's password policy settings - Implement validatePasswordAgainstRequirements() to check if a password meets the policy - Implement generateCompliantPassword() to create passwords that comply with the policy - Update translateEvent() to use getCompliantPassword() which validates the default password or generates a new compliant one based on meeting_password_requirement - Add meeting_password_requirement to the settings API filter - Improve error handling for non-JSON responses in OAuthManager (XML validation errors) This fixes the frequent 'Error in JSON parsing Zoom API response' errors caused by Zoom returning XML validation errors when the password doesn't comply with the account's password policy (e.g., numeric-only requirement). Co-Authored-By: anik@cal.com <adhabal2002@gmail.com> * refactor: use cleaner single-pass consecutive character check - Replace nested-loop O(n*k) implementation with single-pass O(n) helper - Add proper guard for consecutiveLength < 4 (Zoom allows 0, 4-8) - Move consecutive check before only_allow_numeric to apply it for all cases - Fix edge-case bug where consecutiveLength 1-3 could incorrectly reject passwords Co-Authored-By: anik@cal.com <adhabal2002@gmail.com> * Optimize OAuth response handling Refactor OAuth response validation to read body only once. * Improve error handling in Zoom API response parsing Refactor error handling for Zoom API response parsing to improve logging and clarity. * Improve compliant password generation logic Enhance password generation to avoid consecutive characters when numeric only is required. * Remove password requirement handling from VideoApiAdapter Removed meeting password requirement schema and related functions for password validation and generation. --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor: Clean up the /tests in the root (#26525) * refactor: Delete mockTRPCContext and mockData, and relocate mockStripeSubscription to stripe mock. * chore: Delete unused Stripe, video client, and reminder scheduler mock files. * feat(companion): UI Enhancements for Android and Extension (#26434) * feat: companion-android-ui-upgrade version 1 * recurrings and unconfirmed booking filter and page implementation * add badge and links to event type list page * address cubics comments * feat(companion): unify dropdown menu for Android and extension (#26486) * feat(companion): unify dropdown menu for Android and extension - Merge Android-specific dropdown implementations into base component files - EventTypeListItem: Add DropdownMenu with Preview, Copy link, Edit, Duplicate, Delete actions - BookingListItem: Add DropdownMenu with booking actions (reschedule, edit location, add guests, etc.) - RecurringBookingListItem: Add DropdownMenu with recurring booking actions - AvailabilityListItem: Add DropdownMenu with Set as Default, Duplicate, Delete actions - BookingDetailScreen: Add DropdownMenu in header for Android with AlertDialog for cancel confirmation - Delete all .android.tsx files as implementations are now unified * fix(companion): fix typecheck errors after dropdown unification - Remove unused props from EventTypeListItem.ios.tsx (copiedEventTypeId, handleEventTypeLongPress) - Remove unused onActionsPress prop from BookingListItem.ios.tsx - Remove copiedEventTypeId and handleEventTypeLongPress props from index.ios.tsx and index.tsx - Remove onLongPress and onActionsPress props from BookingListScreen.tsx - Remove handleScheduleLongPress, setSelectedSchedule, setShowActionsModal props from AvailabilityListScreen.tsx - Fix BookingDetailScreen.tsx to use correct action property names (reschedule.visible instead of canReschedule, etc.) * fix(companion): remove unused code after dropdown unification - Remove unused handleEventTypeLongPress function and ActionSheetIOS import from index.ios.tsx - Remove unused copiedEventTypeId state, handleEventTypeLongPress function, and ActionSheetIOS import from index.tsx - Prefix unused setSelectedBooking with underscore in BookingListScreen.tsx - Remove unused handleScheduleLongPress function and ActionSheetIOS import from AvailabilityListScreen.tsx * feat(companion): unify booking filter UI for Android and extension - Remove SegmentedControl from web/extension booking list page - Use Header dropdown for booking status filter on both Android and web - Use unified event type filter dropdown for both platforms - Remove unused showFilterModal state and related code - Pass filterOptions, activeFilter, and onFilterChange to Header for all platforms * fix(companion): add header padding for web/extension to prevent button clipping - Add headerLeftContainerStyle and headerRightContainerStyle with 12px padding for web platform - Applied to root Stack and all nested tab Stack layouts - Fixes issue where header buttons were touching edges and getting chopped off on extension/web - Android remains unaffected as the fix is web-only * fix(companion): add HeaderButtonWrapper for web-only header padding - Create HeaderButtonWrapper component that adds 12px margin on web only - Wrap all header buttons with HeaderButtonWrapper to prevent clipping - Revert invalid screenOptions changes that caused typecheck errors - Apply fix to all screens with native header buttons: - reschedule.tsx, edit-location.tsx, add-guests.tsx - mark-no-show.tsx, view-recordings.tsx, meeting-session-details.tsx - event-type-detail.tsx, BookingDetailScreen.tsx, profile-sheet.tsx - edit-availability-day.tsx, edit-availability-name.tsx, edit-availability-override.tsx * update more ui-ux * address cubics comments * address cubics comments & open event type list page first for inttial render of app * chore: Integrate booking cancellation audit (#26458) ## What does this PR do? > **⚠️ Note: This PR does not enable booking audit in production.** The `BookingAuditTaskerProducerService` has an [`IS_PRODUCTION` guard](https://github.com/calcom/cal.com/blob/integrate-booking-creation-reschedule-audit/packages/features/booking-audit/lib/service/BookingAuditTaskerProducerService.ts#L106-L108) that skips audit task queueing in production environments. This allows the integration to be tested in development before enabling it in production. Integrates audit logging for booking cancellations, following the pattern established in PR #26046 for booking creation/rescheduling audit. - Related to #25125 (Booking Audit Infrastructure) ### Changes: - Add audit logging for single booking cancellation via `onBookingCancelled` - Add audit logging for bulk recurring booking cancellation via `onBulkBookingsCancelled` - Pass `userUuid` and `actionSource` from webapp cancel route (WEBAPP) - Pass `userUuid` and `actionSource` from API-v2 bookings service (API_V2) - Create `getAuditActor` helper to derive actor from userUuid or create synthetic guest actor - Add `getUniqueIdentifier` helper for generating unique actor identifiers - Add warning log when `actionSource` is "UNKNOWN" for observability - Add integration tests for booking cancellation audit ### Audit Data Captured: - `cancellationReason` (simple string value) - `cancelledBy` (simple string value) - `status` (old → new, e.g., "ACCEPTED" → "CANCELLED") ### Updates since last revision: - Simplified `CancelledAuditActionService` schema: `cancellationReason` and `cancelledBy` are now stored as simple nullable strings instead of change objects (old/new), since cancellation is a one-time event where tracking previous values doesn't apply - Added integration tests for cancelled booking audit in `booking-audit-cancelled.integration-test.ts` - Added `getUniqueIdentifier` helper function in actor.ts for generating unique identifiers with prefixes ## 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. - [ ] I confirm automated tests are in place that prove my fix is effective or that my feature works. ## How should this be tested? 1. Cancel a single booking via the webapp - verify audit record is created with actor and actionSource="WEBAPP" 2. Cancel a single booking via API v2 - verify audit record is created with actionSource="API_V2" 3. Cancel all remaining bookings in a recurring series - verify bulk audit records are created with shared operationId 4. Cancel via unauthenticated cancel link - verify guest actor is created with synthetic email (prefixed with "param-" or "fallback-") 5. Run integration tests: `yarn test packages/features/booking-audit/lib/service/__tests__/booking-audit-cancelled.integration-test.ts` ## Human Review Checklist - [ ] Verify `onBookingCancelled` and `onBulkBookingsCancelled` methods exist in `BookingEventHandlerService` - [ ] Review the `getAuditActor` fallback logic - creates synthetic email with "fallback-" or "param-" prefix when no userUuid available - [ ] Confirm the simplified schema for `cancellationReason`/`cancelledBy` (no longer tracking old→new) is intentional - [ ] Note: Audit logging calls are awaited directly - if audit service fails, the cancellation will fail. Confirm this is the desired behavior. - [ ] Verify `CancelledAuditDisplayData` type no longer includes `previousReason` and `previousCancelledBy` fields --- Link to Devin run: https://app.devin.ai/sessions/42404e76a66946fe9e46fa07fb12e779 Requested by: @hariombalhara (hariom@cal.com) * feat: OAuth2 controller api v2 + refactor oAuth Trpc handlers (#25989) * feat(api-v2): add OAuth2 controller skeleton for auth module - Add new OAuth2 module under /auth with controller, service, repository, and DTOs - Implement skeleton endpoints: - GET /v2/auth/oauth2/clients/:clientId - Get OAuth client info - POST /v2/auth/oauth2/clients/:clientId/authorize - Generate authorization code - POST /v2/auth/oauth2/clients/:clientId/exchange - Exchange code for tokens - POST /v2/auth/oauth2/clients/:clientId/refresh - Refresh access token - Create input DTOs for authorize, exchange, and refresh operations - Create output DTOs for client info, authorization code, and tokens - Register OAuth2Module in endpoints.module.ts Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore: add missing functions to platform libraries * feat(api-v2): integrate OAuthService from platform-libraries into OAuth2 controller - Add OAuthService export to platform-libraries - Refactor OAuth2Service to use OAuthService.validateClient() and OAuthService.verifyPKCE() - Remove duplicate local implementations of validateClient and verifyPKCE methods Co-Authored-By: morgan@cal.com <morgan@cal.com> * feat(api-v2): use local validateClient and verifyPKCE implementations - Remove OAuthService export from platform-libraries (will be deprecated) - Reimplement validateClient and verifyPKCE methods locally in OAuth2Service - Use verifyCodeChallenge and generateSecret from platform-libraries directly Co-Authored-By: morgan@cal.com <morgan@cal.com> * refactor(api-v2): separate repositories for OAuth2, access codes, and teams - Create AccessCodeRepository for access code Prisma operations - Add findTeamBySlugWithAdminRole method to TeamsRepository - Move generateAuthorizationCode, createTokens, verifyRefreshToken to OAuth2Service - Update OAuth2Repository to only contain OAuth client operations - Update OAuth2Module to import TeamsModule and provide AccessCodeRepository Addresses PR review comments to properly separate concerns Co-Authored-By: morgan@cal.com <morgan@cal.com> * feat(api-v2): implement JWT token creation and verification for OAuth2 - Implement createTokens method using jsonwebtoken to sign access and refresh tokens - Implement verifyRefreshToken method to verify JWT refresh tokens - Add ConfigService injection for CALENDSO_ENCRYPTION_KEY access - Import ConfigModule in OAuth2Module for dependency injection Based on logic from apps/web/app/api/auth/oauth/token/route.ts and apps/web/app/api/auth/oauth/refreshToken/route.ts Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: refactor and dayjs import fix * feat(api-v2): add ApiAuthGuard to getClient endpoint and e2e tests for OAuth2 - Add @UseGuards(ApiAuthGuard) to getClient endpoint for authentication - Add comprehensive e2e tests for all OAuth2 endpoints: - GET /v2/auth/oauth2/clients/:clientId - POST /v2/auth/oauth2/clients/:clientId/authorize - POST /v2/auth/oauth2/clients/:clientId/exchange - POST /v2/auth/oauth2/clients/:clientId/refresh - Tests cover happy paths and error cases (invalid client, invalid code, etc.) Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore(api-v2): hide OAuth2 endpoints from Swagger documentation Co-Authored-By: morgan@cal.com <morgan@cal.com> * hide endpoints from doc * fix(api-v2): address PR feedback for OAuth2 controller - Fix P0 critical bug: token_type field name mismatch in DecodedRefreshToken interface - Add @Equals('authorization_code') validation to exchange.input.ts grantType - Add @Equals('refresh_token') validation to refresh.input.ts grantType - Add @IsNotEmpty() validation to get-client.input.ts clientId - Add @Expose() decorators to all output DTOs for proper serialization - Add security test assertion to verify clientSecret is not returned in response Co-Authored-By: morgan@cal.com <morgan@cal.com> * feat(api-v2): implement redirect behavior for OAuth2 authorize endpoint - Update authorize endpoint to return HTTP 303 redirect with authorization code - Add exact match validation for redirect URI (security requirement) - Implement error handling with redirect to redirect URI and error query params - Add state parameter support for CSRF protection - Update e2e tests to verify redirect behavior (303 status, Location header, error redirects) Co-Authored-By: morgan@cal.com <morgan@cal.com> * refactor(api-v2): address PR feedback for OAuth2 authorize endpoint - Make redirectUri a required input parameter (remove optional fallback) - Move buildRedirectUrl and mapErrorToOAuthError to oauth2Service - Add return statements to res.redirect() calls - Simplify controller by delegating redirect URL building to service Co-Authored-By: morgan@cal.com <morgan@cal.com> * wip move code outside of api v2 * feat(oauth): wire up dependency injection for OAuthService and repositories Co-Authored-By: morgan@cal.com <morgan@cal.com> * refactor: oAuthService used in routes * fix imports * fix(api-v2): return 404 for invalid client ID instead of redirect in authorize endpoint Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix(api-v2): fix E2E test URL paths and remove bootstrap() in authenticated section - Remove bootstrap() call in authenticated section to match working test pattern - Change URL paths from /api/v2/... to /v2/... in authenticated section - Keep bootstrap() and /api/v2/... paths in unauthenticated section Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix(api-v2): mock getToken from next-auth/jwt for E2E tests - Add jest.mock for next-auth/jwt getToken function - Mock returns null for unauthenticated tests - Mock returns { email: userEmail } for authenticated tests - Remove withNextAuth helper since ApiAuthGuard uses ApiAuthStrategy which calls getToken directly, not NextAuthStrategy Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix tests and code review * cleanup generate secrets * cleanup controller * chore: remove console.log from OAuthService.validateClient Co-Authored-By: morgan@cal.com <morgan@cal.com> * Update apps/web/app/api/auth/oauth/refreshToken/route.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> * fix(api-v2): add bootstrap() to authenticated E2E tests and update URL paths to /api/v2/ Co-Authored-By: morgan@cal.com <morgan@cal.com> * Merge remote-tracking branch 'origin/devin/oauth2-controller-skeleton-1765988792' and remove console.log from token route Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore: remove dead code * refactor * refactor: generateAuthCode trpc handler and getClient trpc handler * remove pkce check for refreshToken endpoint * Update packages/trpc/server/routers/viewer/oAuth/getClient.handler.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> * refactor: error handling * refactor: error handling * refactor: error handling * remove console log * provide redirectUri in generateAuthCodeHandler * provide redirectUri in authorize view * refactor: replace HttpError with ErrorWithCode in OAuth files - Update OAuthService to use ErrorWithCode instead of HttpError - Update mapErrorToOAuthError to check ErrorCode instead of status codes - Update token/route.ts and refreshToken/route.ts to use ErrorWithCode - Add ErrorWithCode export to platform-libraries - Use getHttpStatusCode to map ErrorCode to HTTP status codes Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: update generateAuthCode handler to use ErrorWithCode instead of HttpError The handler was still checking for HttpError in its catch block, but OAuthService now throws ErrorWithCode. This caused the error messages to be lost and replaced with 'server_error' instead of the specific error messages. Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: update OAuth2 controller to use ErrorWithCode instead of HttpError The controller was still checking for HttpError in its catch blocks, but OAuthService now throws ErrorWithCode. This caused all errors to return 500 Internal Server Error instead of the correct HTTP status codes (400, 401, 404). Also added getHttpStatusCode export to platform-libraries. Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: add explicit unknown type annotation to catch blocks in OAuth2 controller Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: change NotFoundException to HttpException in authorize endpoint Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: handle err with ErrorWithCode in authorize endpoint catch block Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: move errorWithCode * fix: error code rfc * fix: no need to handle errors there is a middleware * refactor errors * refactor errors * refactor redirecturi and state from api * refactor: address PR comments for OAuth2 controller - Remove unused GetOAuth2ClientInput class - Change API tag from 'Auth / OAuth2' to 'OAuth2' - Move OAuthClientFixture to separate fixture file (oauth2-client.repository.fixture.ts) - Add 'type' property to OAuth2ClientDto for confidential/public client type - Rename 'clientId' to 'id' in OAuth2ClientDto (using @Expose mapping) - Clean up duplicate provider declaratio… * fix: remove duplicate onBookingCancelled call Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> --------- Signed-off-by: Bandhan Majumder <bandhanmajumder16@gmail.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Ram Shukla <codewithrex@gmail.com> Co-authored-by: Pedro Castro <pedro@cal.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Manas Kenge <man.kng02@gmail.com> Co-authored-by: Dhairyashil Shinde <93669429+dhairyashiil@users.noreply.github.com> Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com> Co-authored-by: Eesh Midha <72607015+eeshm@users.noreply.github.com> Co-authored-by: Beto <43630417+betomoedano@users.noreply.github.com> Co-authored-by: shashank-100 <shashank.telkhade@gmail.com> Co-authored-by: Kartik Labhshetwar <kartik.labhshetwar@gmail.com> Co-authored-by: Abhay Mishra <grabhaymishra@gmail.com> Co-authored-by: Keith Williams <keithwillcode@gmail.com> Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com> Co-authored-by: Pallav <90088723+Pallava-Joshi@users.noreply.github.com> Co-authored-by: Ryukemeister <sahalrajiv6900@gmail.com> Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in> Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com> Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com> Co-authored-by: cal-com-ci[bot] <247290566+cal-com-ci[bot]@users.noreply.github.com> Co-authored-by: Lingo.dev <support@lingo.dev> Co-authored-by: Benny Joo <sldisek783@gmail.com> Co-authored-by: Eunjae Lee <hey@eunjae.dev> Co-authored-by: Volnei Munhoz <volnei@cal.com> Co-authored-by: Anshumancanrock <109489361+Anshumancanrock@users.noreply.github.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> Co-authored-by: Amit Sharma <74371312+Amit91848@users.noreply.github.com> Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> Co-authored-by: Kartik <103111467+kartik-212004@users.noreply.github.com> Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com> Co-authored-by: Volnei Munhoz <volnei.munhoz@gmail.com> Co-authored-by: Adarsh Tiwari <adarshtiwari797023@gmail.com> Co-authored-by: Dylan Tarre <timecreepsby@gmail.com> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> Co-authored-by: Amin Jaoui <101276751+aminjaoui@users.noreply.github.com> Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com> Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Anik Dhabal Babu <adhabal2002@gmail.com> Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com> Co-authored-by: Mehmet Sungur <mehmetsungurmutlu@gmail.com> Co-authored-by: xDipzz <155362028+xDipzz@users.noreply.github.com> Co-authored-by: Pasquale Vitiello <pasqualevitiello@gmail.com> Co-authored-by: pasquale@cal.com <pasquale@cal.com> Co-authored-by: cal.com <morgan@cal.com> Co-authored-by: Anas Najam <129951478+anzz14@users.noreply.github.com> Co-authored-by: Bandhan Majumder <133476557+bandhan-majumder@users.noreply.github.com> Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com> Co-authored-by: Kartik Saini <41051387+kart1ka@users.noreply.github.com> Co-authored-by: Abhishek <abhiifour@gmail.com> Co-authored-by: susan@cal.com <susan@cal.com> Co-authored-by: Bailey Pumfleet <bailey@pumfleet.co.uk> Co-authored-by: simiondolha <34995943+simiondolha@users.noreply.github.com> Co-authored-by: simiondolha <simiondolha@users.noreply.github.com> Co-authored-by: Kirankumar Ambati <kiran.chinna12520@gmail.com> |
||
|
|
75d611c2e8 |
chore: Integrate creation/rescheduling booking audit for Recurring/regular booking/seated bookings (#26046)
* Integrate creation/rescheduling booking audit * fix: add missing hostUserUuid to booking audit test data Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * fix-ci * feat: enhance booking audit with seat reference - Added support for seat reference in booking audit actions. - Updated localization for booking creation to include seat information. - Modified relevant services to pass attendee seat ID during booking creation. * fix: update test data to match schema requirements - Add seatReferenceUid: null to default mock audit log data - Add seatReferenceUid: null to multiple audit logs test case - Convert SEAT_RESCHEDULED test data to use numeric timestamps instead of ISO strings Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * Allow nullish seatReferenceUid * feat: enhance booking audit to support rescheduledBy information - Updated booking audit actions to include rescheduledBy details, allowing tracking of who rescheduled a booking. - Refactored related services to accommodate the new rescheduledBy parameter in booking events. - Adjusted type definitions and function signatures to reflect the changes in the booking audit context. * Avoid possible run time issue * Fix imoport path * fix failing test due to merge from main\ * Pass useruuid --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
f7dee536d7 | fix: dont import directly from @calcom/trpc or @calom/features (#26734) | ||
|
|
3e7e376100 |
chore: Some minor fixes and follow up to #26446 (#26587)
* init * DI and other improvements * type fix --------- Co-authored-by: Volnei Munhoz <volnei@cal.com> |
||
|
|
61a932f8f5 |
feat: OAuth2 controller api v2 + refactor oAuth Trpc handlers (#25989)
* feat(api-v2): add OAuth2 controller skeleton for auth module - Add new OAuth2 module under /auth with controller, service, repository, and DTOs - Implement skeleton endpoints: - GET /v2/auth/oauth2/clients/:clientId - Get OAuth client info - POST /v2/auth/oauth2/clients/:clientId/authorize - Generate authorization code - POST /v2/auth/oauth2/clients/:clientId/exchange - Exchange code for tokens - POST /v2/auth/oauth2/clients/:clientId/refresh - Refresh access token - Create input DTOs for authorize, exchange, and refresh operations - Create output DTOs for client info, authorization code, and tokens - Register OAuth2Module in endpoints.module.ts Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore: add missing functions to platform libraries * feat(api-v2): integrate OAuthService from platform-libraries into OAuth2 controller - Add OAuthService export to platform-libraries - Refactor OAuth2Service to use OAuthService.validateClient() and OAuthService.verifyPKCE() - Remove duplicate local implementations of validateClient and verifyPKCE methods Co-Authored-By: morgan@cal.com <morgan@cal.com> * feat(api-v2): use local validateClient and verifyPKCE implementations - Remove OAuthService export from platform-libraries (will be deprecated) - Reimplement validateClient and verifyPKCE methods locally in OAuth2Service - Use verifyCodeChallenge and generateSecret from platform-libraries directly Co-Authored-By: morgan@cal.com <morgan@cal.com> * refactor(api-v2): separate repositories for OAuth2, access codes, and teams - Create AccessCodeRepository for access code Prisma operations - Add findTeamBySlugWithAdminRole method to TeamsRepository - Move generateAuthorizationCode, createTokens, verifyRefreshToken to OAuth2Service - Update OAuth2Repository to only contain OAuth client operations - Update OAuth2Module to import TeamsModule and provide AccessCodeRepository Addresses PR review comments to properly separate concerns Co-Authored-By: morgan@cal.com <morgan@cal.com> * feat(api-v2): implement JWT token creation and verification for OAuth2 - Implement createTokens method using jsonwebtoken to sign access and refresh tokens - Implement verifyRefreshToken method to verify JWT refresh tokens - Add ConfigService injection for CALENDSO_ENCRYPTION_KEY access - Import ConfigModule in OAuth2Module for dependency injection Based on logic from apps/web/app/api/auth/oauth/token/route.ts and apps/web/app/api/auth/oauth/refreshToken/route.ts Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: refactor and dayjs import fix * feat(api-v2): add ApiAuthGuard to getClient endpoint and e2e tests for OAuth2 - Add @UseGuards(ApiAuthGuard) to getClient endpoint for authentication - Add comprehensive e2e tests for all OAuth2 endpoints: - GET /v2/auth/oauth2/clients/:clientId - POST /v2/auth/oauth2/clients/:clientId/authorize - POST /v2/auth/oauth2/clients/:clientId/exchange - POST /v2/auth/oauth2/clients/:clientId/refresh - Tests cover happy paths and error cases (invalid client, invalid code, etc.) Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore(api-v2): hide OAuth2 endpoints from Swagger documentation Co-Authored-By: morgan@cal.com <morgan@cal.com> * hide endpoints from doc * fix(api-v2): address PR feedback for OAuth2 controller - Fix P0 critical bug: token_type field name mismatch in DecodedRefreshToken interface - Add @Equals('authorization_code') validation to exchange.input.ts grantType - Add @Equals('refresh_token') validation to refresh.input.ts grantType - Add @IsNotEmpty() validation to get-client.input.ts clientId - Add @Expose() decorators to all output DTOs for proper serialization - Add security test assertion to verify clientSecret is not returned in response Co-Authored-By: morgan@cal.com <morgan@cal.com> * feat(api-v2): implement redirect behavior for OAuth2 authorize endpoint - Update authorize endpoint to return HTTP 303 redirect with authorization code - Add exact match validation for redirect URI (security requirement) - Implement error handling with redirect to redirect URI and error query params - Add state parameter support for CSRF protection - Update e2e tests to verify redirect behavior (303 status, Location header, error redirects) Co-Authored-By: morgan@cal.com <morgan@cal.com> * refactor(api-v2): address PR feedback for OAuth2 authorize endpoint - Make redirectUri a required input parameter (remove optional fallback) - Move buildRedirectUrl and mapErrorToOAuthError to oauth2Service - Add return statements to res.redirect() calls - Simplify controller by delegating redirect URL building to service Co-Authored-By: morgan@cal.com <morgan@cal.com> * wip move code outside of api v2 * feat(oauth): wire up dependency injection for OAuthService and repositories Co-Authored-By: morgan@cal.com <morgan@cal.com> * refactor: oAuthService used in routes * fix imports * fix(api-v2): return 404 for invalid client ID instead of redirect in authorize endpoint Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix(api-v2): fix E2E test URL paths and remove bootstrap() in authenticated section - Remove bootstrap() call in authenticated section to match working test pattern - Change URL paths from /api/v2/... to /v2/... in authenticated section - Keep bootstrap() and /api/v2/... paths in unauthenticated section Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix(api-v2): mock getToken from next-auth/jwt for E2E tests - Add jest.mock for next-auth/jwt getToken function - Mock returns null for unauthenticated tests - Mock returns { email: userEmail } for authenticated tests - Remove withNextAuth helper since ApiAuthGuard uses ApiAuthStrategy which calls getToken directly, not NextAuthStrategy Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix tests and code review * cleanup generate secrets * cleanup controller * chore: remove console.log from OAuthService.validateClient Co-Authored-By: morgan@cal.com <morgan@cal.com> * Update apps/web/app/api/auth/oauth/refreshToken/route.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> * fix(api-v2): add bootstrap() to authenticated E2E tests and update URL paths to /api/v2/ Co-Authored-By: morgan@cal.com <morgan@cal.com> * Merge remote-tracking branch 'origin/devin/oauth2-controller-skeleton-1765988792' and remove console.log from token route Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore: remove dead code * refactor * refactor: generateAuthCode trpc handler and getClient trpc handler * remove pkce check for refreshToken endpoint * Update packages/trpc/server/routers/viewer/oAuth/getClient.handler.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> * refactor: error handling * refactor: error handling * refactor: error handling * remove console log * provide redirectUri in generateAuthCodeHandler * provide redirectUri in authorize view * refactor: replace HttpError with ErrorWithCode in OAuth files - Update OAuthService to use ErrorWithCode instead of HttpError - Update mapErrorToOAuthError to check ErrorCode instead of status codes - Update token/route.ts and refreshToken/route.ts to use ErrorWithCode - Add ErrorWithCode export to platform-libraries - Use getHttpStatusCode to map ErrorCode to HTTP status codes Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: update generateAuthCode handler to use ErrorWithCode instead of HttpError The handler was still checking for HttpError in its catch block, but OAuthService now throws ErrorWithCode. This caused the error messages to be lost and replaced with 'server_error' instead of the specific error messages. Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: update OAuth2 controller to use ErrorWithCode instead of HttpError The controller was still checking for HttpError in its catch blocks, but OAuthService now throws ErrorWithCode. This caused all errors to return 500 Internal Server Error instead of the correct HTTP status codes (400, 401, 404). Also added getHttpStatusCode export to platform-libraries. Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: add explicit unknown type annotation to catch blocks in OAuth2 controller Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: change NotFoundException to HttpException in authorize endpoint Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: handle err with ErrorWithCode in authorize endpoint catch block Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: move errorWithCode * fix: error code rfc * fix: no need to handle errors there is a middleware * refactor errors * refactor errors * refactor redirecturi and state from api * refactor: address PR comments for OAuth2 controller - Remove unused GetOAuth2ClientInput class - Change API tag from 'Auth / OAuth2' to 'OAuth2' - Move OAuthClientFixture to separate fixture file (oauth2-client.repository.fixture.ts) - Add 'type' property to OAuth2ClientDto for confidential/public client type - Rename 'clientId' to 'id' in OAuth2ClientDto (using @Expose mapping) - Clean up duplicate provider declarations in oauth2.module.ts - Update e2e tests to use new fixture and verify type property Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Volnei Munhoz <volnei.munhoz@gmail.com> Co-authored-by: Volnei Munhoz <volnei@cal.com> |
||
|
|
a1e5384859 | Prefix node protocol (#26391) | ||
|
|
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> |
||
|
|
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
|
||
|
|
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> |
||
|
|
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) --> |
||
|
|
a050ccb4ee |
feat: Booking EmailAndSms Notifications Tasker (#24944)
* wip * wip * feature: Booking Tasker without DI yet * feature: Booking Tasker with DI * fix type check 1 * fix type check 2 * fix * comment booking tasker for now * fix: DI regularBookingService api v2 * fix: convert trigger.dev SDK imports to dynamic imports to fix unit tests The unit tests were failing because BookingEmailAndSmsTriggerTasker.ts had static imports of trigger files that depend on @trigger.dev/sdk. This caused Vitest to try to resolve the SDK at module load time, even though it should be optional. Changed all imports in BookingEmailAndSmsTriggerTasker.ts from static to dynamic (using await import()) so the trigger files are only loaded when the tasker methods are actually called, not at module load time during tests. This fixes the 'Failed to load url @trigger.dev/sdk' errors that were causing 28+ test failures. Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix unit tests * keep inline smsAndEmailHandler.send calls * chore: add team feature flag * add satisfies ModuleLoader * fix type check app flags * move trigger in feature * fix: add trigger.dev prisma generator * fix: email app statuses * fix: CalEvtBuilder unit test * chore: improvements, schema, config, retry * fixup! chore: improvements, schema, config, retry * chore: cleanup code * chore: cleanup code * chore: clean code and give full payload * remove log * add booking notifications queue * add attendee phone number for sms * bump trigger to 4.1.0 * add missing booking seat data in attendee * update config * fix logger regular booking service * fix: prisma as external deps of trigger * fix yarn.lock * revert change to example app booking page * fix: resolve circular dependencies and improve cold start performance in trigger tasks - Convert BookingRepository import to type-only in CalendarEventBuilder.ts to eliminate circular dependency risk - Convert EventNameObjectType, CalendarEvent, and JsonObject imports to type-only in BookingEmailAndSmsTaskService.ts - Use dynamic imports in all trigger notification tasks (confirm, request, reschedule, rr-reschedule) to reduce cold start time - Move heavy imports (BookingEmailSmsHandler, BookingRepository, prisma, TriggerDevLogger, BookingEmailAndSmsTaskService) inside run functions - Eliminates module-level prisma import which violates repo guidelines and adds cold start overhead - Reduces initial module dependency graph by deferring heavy imports (email templates, workflows, large repositories) until task execution Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: improve cold start performance in reminderScheduler with dynamic imports - Remove module-level prisma import (violates 'No prisma outside repositories' guideline) - Use dynamic imports for UserRepository (1,168 lines) - only loaded when needed in EMAIL_ATTENDEE action - Use dynamic imports for twilio provider (386 lines) - only loaded in cancelScheduledMessagesAndScheduleEmails - Use dynamic imports for all manager functions by action type: - scheduleSMSReminder (387 lines) - loaded only for SMS actions - scheduleEmailReminder (459 lines) - loaded only for Email actions - scheduleWhatsappReminder (266 lines) - loaded only for WhatsApp actions - scheduleAIPhoneCall (478 lines) - loaded only for AI phone call actions - Use dynamic imports for sendOrScheduleWorkflowEmails in cancelScheduledMessagesAndScheduleEmails - Significantly reduces cold start time by deferring heavy module loading until execution paths need them - Eliminates module-level prisma import that violated repository pattern guidelines Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: improve cold start performance in BookingEmailSmsHandler with dynamic imports - Remove module-level imports of all email-manager functions (653 LOC + 30+ email templates) - Add dynamic imports in each method (_handleRescheduled, _handleRoundRobinRescheduled, _handleConfirmed, _handleRequested, handleAddGuests) - Defer heavy email-manager loading until method execution - Verified no circular dependencies between email-manager and bookings - Significantly reduces cold start time for RegularBookingService and BookingEmailAndSmsTaskService Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: use dynamic imports * update yarn lock * code review * trigger config project ref in env * update yarn lock * add .env.example trigger variables * add .env.example trigger variables * fix: cleanup error handling and loggin * fix: trigger config from env * fix: small typo fix * fix: ai review comments * fix: ai review comments * ai review * prettier --------- Co-authored-by: hbjORbj <sldisek783@gmail.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
cbc8d3d7a8 | Add DI for BookingAudit (#25123) | ||
|
|
ae7fd0cae2 |
refactor: Remove all code related to the old cache system (#25284)
* chore: Remove all code related to the old cache system * Removed some redundant tests, some type fixes * Further type fixes * More type fixes re. tests * Next iteration, couple of fixes remaining * Remove cache from CredentialActionsDropdown * Fix tests by mocking credential, instead of db queries * Remove Cache DI wiring from v2 * Make sure apiv2 build passes * Remove another cache cron * Remove old tokens for calendar-cache v1 |
||
|
|
bc665cbeab |
fix: APIV2 team membership - Member not getting added to event-type automatically (#24780)
* fix: APIV2 team membership addition * feat: Add trimming for email domain and orgAutoAcceptEmail in auto-accept logic - Trim whitespace from both user email domain and orgAutoAcceptEmail - Ensures consistent matching even with accidental whitespace - Addresses feedback from PR review Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * simplify * feat: Use shared OrganizationMembershipService in TRPC for consistent auto-accept logic - Create OrganizationMembershipService.container.ts for DI in TRPC - Update getOrgConnectionInfo to apply trimming + case-insensitive comparison - Precompute auto-accept decisions in createNewUsersConnectToOrgIfExists using the service - Use service in handleNewUsersInvites for consistent auto-accept determination - Ensures both API v2 and TRPC paths use identical trimming and normalization logic Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * Revert "feat: Use shared OrganizationMembershipService in TRPC for consistent auto-accept logic" This reverts commit 0b2bd28b6e32e8c1d3dea139ca8ff9cbf402ac00. * refactor: Unify OrganizationRepository and remove duplicate PrismaOrganizationRepository (#24869) * refactor: Convert OrganizationRepository from static to instance methods - Add constructor accepting deps object with prismaClient - Convert all static methods to instance methods - Add getOrganizationAutoAcceptSettings method - Create singleton instance export in repository barrel file - Update API v2 OrganizationsRepository to extend from OrganizationRepository - Update all call sites to use singleton instance - Add platform-libraries organizations.ts export - Fix mock imports to use repository barrel - Fix unsafe optional chaining in next-auth-options.ts - Fix any types in test files with proper type inference Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * fix: Update all imports to use OrganizationRepository barrel export - Update imports from direct OrganizationRepository file to barrel export - This ensures mocks work correctly in tests - Fixes 202 failing tests related to organizationRepository mock Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * fix: Update test mocks to use partial mock pattern - Convert organizationMock to partial mock that preserves real class - Add proper prisma mocks to failing test files - Remove old OrganizationRepository mocks from test files - This fixes test failures related to mock interception Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * fix: Export mocked singleton and update tests to use it directly - Export mockedSingleton as organizationRepositoryMock from organizationMock - Update delegationCredential.test.ts to import and use the exported mock - This fixes 'vi.mocked(...).mockResolvedValue is not a function' errors Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * fix: Use platform-libraries import for API v2 OrganizationRepository API v2 should import shared features through @calcom/platform-libraries instead of directly from @calcom/features to maintain proper architectural boundaries and packaging/licensing separation. Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * refactor: Implement DI pattern for OrganizationRepository - Create OrganizationRepository.module.ts and .container.ts for DI - Replace singleton pattern with getOrganizationRepository() across 20 files - Update platform-libraries to export getOrganizationRepository - Delete duplicate PrismaOrganizationRepository.ts - Remove singleton export file (repositories/index.ts) - Update test mocks to use DI container pattern - All type checks and unit tests passing Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * fix: Implement read/write client separation in OrganizationRepository - Updated OrganizationRepository constructor to accept optional prismaWriteClient parameter - Routed all write operations (create, update) through prismaWrite client - Routed all read operations (find, get) through prismaRead client - Updated API v2 OrganizationsRepository to pass both dbRead.prisma and dbWrite.prisma to super() - Optimized getOrganizationRepository() calls by storing in local variables to avoid repeated function calls - This fixes the critical issue where API v2 was passing read-only client to base class with write methods Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * fix: Fix mock setup and optimize getOrganizationRepository() calls - Fixed verify-email.test.ts mock to return mocked repository instance instead of scenario helper object - Added mockReset to organizationMock.ts beforeEach to properly reset mock implementations between tests - Added local variables in page.tsx to store getOrganizationRepository() result for consistency This fixes the issue where getOrganizationRepository() was returning organizationScenarios.organizationRepository (scenario helper) instead of the actual mocked repository instance, causing findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail to be undefined. Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * refactor: Simplify OrganizationRepository to use single prismaClient - Updated base OrganizationRepository constructor to accept only { prismaClient } instead of { prismaClient, prismaWriteClient? } - Replaced this.prismaRead and this.prismaWrite with single this.prismaClient property - Updated API v2 OrganizationsRepository to pass only dbWrite.prisma as prismaClient - Removed unused PrismaReadService import from API v2 - All read and write operations now use the same client instance This simplifies the architecture as requested - API v2 uses write client for all operations, and apps/web uses the client from DI container. Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: Match OrganizationsRepository.findById signature with base class The findById method in OrganizationsRepository was using a different signature than the base OrganizationRepository class, causing type errors in CI. Changed from: findById(organizationId: number) Changed to: findById({ id }: { id: number }) This matches the base class signature and resolves the CI unit test failures. Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * fix: Update all findById call sites to use object parameter Fixed 6 call sites in API v2 that were calling findById with a number instead of the required { id: number } object parameter: - is-org.guard.ts - is-admin-api-enabled.guard.ts - is-webhook-in-org.guard.ts - organizations.service.ts - managed-organizations.service.ts (2 call sites) This resolves the API v2 build failure caused by the signature change in OrganizationsRepository.findById to match the base class. Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * fix: Remove redundant findById override from OrganizationsRepository The findById method was duplicating the base class OrganizationRepository implementation. Both methods had identical logic (filtering by isOrganization: true), so the override was unnecessary. Since OrganizationsRepository extends OrganizationRepository and passes dbWrite.prisma to the base constructor, the base class method already provides the exact same functionality. This resolves the API v2 build failure by eliminating the duplicate method that was causing conflicts. Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * Remove unncessary changes * Store in variable * Revert "Remove unncessary changes" This reverts commit af9351786a21616c9508c441191c17f2374fb2cc. * Revert dbRead/dbWrite changes * Add organizations library to tsconfig.json --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> |
||
|
|
82951cd04e |
chore: [Booking Flow Refactor - 5] Move post booking things to separate service BookingEventHandlerService starting with HashedLink usage handling (#24025)
* chore: Move post booking stuff to separate service * refactor: improve ISP compliance in BookingEventHandlerService - Refactor updatePrivateLinkUsage to only accept hashedLink parameter instead of full payload - Remove shouldProcess function and inline isDryRun check for better clarity - Addresses feedback from PR #24025 Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> * define only what is used * Define hashed-link-service as well in api-v2 * fix: export HashedLinkService through platform-libraries - Add HashedLinkService to platform-libraries/private-links.ts - Update API V2 to import from platform library instead of direct path - Fixes MODULE_NOT_FOUND error in API V2 build Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> |
||
|
|
6923b97cd2 |
feat: upgrade Prisma to 6.16.0 with no-rust engine (#23816)
* feat: upgrade Prisma to 6.16.0 with no-rust engine - Update Prisma packages to 6.16.0 - Add PostgreSQL adapter dependency - Configure engineType: 'client' and provider: 'prisma-client' in schema - Update Prisma client instantiation with PostgreSQL adapter - Remove binaryTargets from generators (not needed with library engine) - Fix schema view issue by removing @id decorator from BookingTimeStatusDenormalized - Fix ESLint warning by removing non-null assertion Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * Web app running but types wrecked * web app running but build and type issues * Removed the connection pool * Fixed zod type issue * Fixed types in booking reference extension * Fixed test issues * Type checks passing it seems * Using cjs as moduleFormat * Fixing Prisma undefined * fix: update prismock initialization for Prisma 6.16 compatibility - Add @prisma/internals dependency for getDMMF() - Restructure prismock initialization to use createPrismock() with DMMF - Create Proxy that's returned from mock factory for proper spy support - Fixes 89 failing unit tests with 'Cannot read properties of undefined (reading datamodel)' error - Based on workaround from prismock issue #1482 All unit tests now pass (375 test files, 3323 tests passed) Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: cast serviceAccountKey to Prisma.InputJsonValue in bookingScenario.ts - Apply type cast at lines 2493 and 2535 - Fixes type errors from Prisma 6.16 upgrade - Follows established pattern from delegationCredential.ts - Add eslint-disable for pre-existing any types - Rename unused appStoreLookupKey parameter to satisfy lint - All 3323 tests passing Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * chore: remove whitespace-only lines from bookingScenario.ts - Remove blank lines where eslint-disable comments were replaced - Cleanup from pre-commit hook formatting Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * Update is-prisma-available-check.ts * fix: remove datasources config when using Prisma Driver Adapters - Update customPrisma to create new adapter when datasources URL is provided - Remove datasources config from API v2 Prisma services (already in adapter) - Fixes 'Custom datasource configuration is not compatible with Prisma Driver Adapters' error Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: use Pool instances for PrismaPg adapters in index.ts - Create Pool instance before passing to PrismaPg adapter - Update customPrisma to create Pool for custom connection strings - Matches working pattern from API v2 services - Fixes 'Invalid `prisma.$queryRawUnsafe()` invocation' error Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * Not using queryRawUnsafe * Trying anything at this point * Make sure the DB is ready first * Don't auto run migrations in CI mode * Revert "Make sure the DB is ready first" This reverts commit 2b20bd45c974f3d7e07d8b904bc7fcdae37cce03. * Dynamic import of prisma * Commenting where it seems to break * Backwards compatability for API v2 * fix: add explicit type annotations for map callbacks in API v2 - Add type annotation for map parameter in memberships.repository.ts - Add type annotation for map parameter in stripe.service.ts - Fixes implicit 'any' type errors from stricter Prisma 6.16.0 type inference Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: add explicit type annotations for API v2 map callbacks - users.repository.ts:292: add Profile & { user: User } type - memberships.service.ts:19-20: add Membership type to filter callbacks Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: add explicit type annotation for attributeToUser in organizations-users.repository.ts - organizations-users.repository.ts:63: add AttributeToUser with nested relations type Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: add explicit Membership type annotations in teams.repository.ts Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: use API v2 dedicated Prisma client to support adapter in PrismaClientOptions Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * Running API v2 build commands together so they all get the space size var * Fixing Maximum call depth exceeded error * fixed type issues * Trying to make the seed more stable * Revert "Trying to make the seed more stable" This reverts commit 1fd4495e6af7acd7981cda7dedec3168979b0e9d. * Fixed path to prisma client * Fixed type check * Fix eslint warnings * fix: externalize @prisma/adapter-pg and pg in platform-libraries Vite config - Add @prisma/adapter-pg and pg to external dependencies list - Add corresponding globals for these packages - Fix Prisma client aliases to point to packages/prisma/client instead of node_modules - Add Node.js resolve conditions to prefer Node.js exports - Keep commonjsOptions.include for proper CommonJS transformation - Add eslint-disable for __dirname in Vite config file - Remove problematic prettier/prettier eslint comment This fixes the 'Extensions.defineExtension is unable to run in this browser environment' error when running yarn generate-swagger in apps/api/v2 after upgrading to Prisma v6.16 with the no-rust engine approach. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: update Prisma imports in API v2 services to use package path - Change imports from '../../../generated/prisma/client' to '@calcom/prisma/client' - Fixes CI error: Cannot find module '../../../../../packages/prisma/generated/prisma/client.ts' - Aligns with backwards compatibility re-export structure after Prisma v6.16 upgrade Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: remove .ts extension from Prisma client path mapping in tsconfig - Remove file extension from @calcom/prisma/client path mapping - Fixes runtime error: Cannot find module '../../../../../packages/prisma/generated/prisma/client.ts' - TypeScript path mappings should not include file extensions per best practices - Allows Node.js to correctly resolve to .js files at runtime Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: resolve Prisma 6.16.0 type incompatibilities in bookingScenario tests - Changed InputPayment.data type from PaymentData to Prisma.InputJsonValue - Changed createCredentials key parameter from JsonValue to InputJsonValue - Removed unused PaymentData type definition - Resolves type errors at lines 709 and 1088 without using 'as any' casts Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: remove non-existent Watchlist fields from test fixtures - Remove createdById from isLockedOrBlocked.test.ts (lines 15, 20) - Remove severity and createdById from _post.test.ts (line 110) - These fields don't exist in Watchlist model schema after Prisma 6.16.0 upgrade - Resolves TS2353 errors without using 'as any' casts Relates to PR #23816 Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: api v2 imports generated prisma and platform libraries * fix: resolve type errors from Prisma 6.16 upgrade - Add missing markdownToSafeHTML import in AppCard.tsx - Fix organizationId null handling in fresh-booking.test.ts - Remove non-existent createdById field from Watchlist test utils Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * Put back some external rollups * Added back the resolve conditions * Stop using Pool directly * chore: remove prisma bookingReferenceExtension and update calls * fix: organizations-admin-not-team-member-event-types.e2e-spec.ts * chore: bring back POOL in api v2 prisma clients * chore: remove Pool but await connect * fixup! chore: remove Pool but await connect * chore: bring back Pool on all clients * chore: end pool manually * chore: test with pool max 1 * chore: e2e test prisma max pool of 1 connection * chore: give more control over pool for prisma module with env * remove pool from base prisma client * chore: prisma client in libraries use pool * Fixed types * chore: log pool events and improve pooling * Fixing some types and tests * Changing the parsing of USE_POOL * fix: ensure Prisma client is connected before seeding to prevent transaction errors Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * chore: adjust pools * chore: add process.env.USE_POOL to libraries vite config * fix: v1 _patch reference check bookingRef on the booking find * fix: v1 get references deleted null for system admin * test: add integration tests for bookingReference soft-delete behavior - Add bookingReference.integration-test.ts to test repository methods - Add handleDeleteCredential.integration-test.ts to test credential deletion cascade - Add booking-references.integration-test.ts for API v1 integration tests - All tests verify soft-delete behavior without using mocks - Tests use real database operations to ensure soft-deleted records persist - Cover scenarios: replacing references, credential deletion, querying with filters Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * refactor: convert booking-references test to actual API endpoint testing - Modified _get.ts to export handler function for testing - Refactored integration test to call API handler instead of directly testing Prisma - Added timestamps to test data to avoid conflicts - Tests now verify API layer correctly filters soft-deleted references - All 4 tests passing Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: add explicit prisma.$connect() call to seed-insights script With Prisma 6.16 and the PostgreSQL adapter, scripts need to explicitly call $connect() before running database operations to ensure the connection pool is properly initialized. This prevents 'Transaction already closed' errors. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: add $connect() to main() execution in seed-insights Both main() and createPerformanceData() entry points need explicit prisma.$connect() calls with the Prisma 6.16 PostgreSQL adapter. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: always use connection pool for Prisma PostgreSQL adapter Enable connection pooling by default for the Prisma adapter to prevent transaction state issues during seed operations. Without a pool, each operation creates a new connection which can lead to 'Transaction already closed' errors during heavy database operations like seeding. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * Revert "fix: always use connection pool for Prisma PostgreSQL adapter" This reverts commit 6724bb08e42bc0a94846069de83b04db0aeb8e8b. * fix: enable connection pool for db-seed in cache-db action Set USE_POOL=true when running yarn db-seed to use connection pooling with the Prisma PostgreSQL adapter. This prevents 'Transaction already closed' errors during seeding by maintaining stable database connections. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: add safety check for undefined ownerForEvent in seed script Prevent 'Cannot read properties of undefined' error when orgMembersInDBWithProfileId is empty. This can happen if organization members fail to create or when there's a duplicate constraint violation causing early return. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: v1 _patch reference check bookingRef * fix: increase pool size and add timeout settings to prevent transaction errors - Increase max connections from 5 to 10 - Add connectionTimeoutMillis: 30000 (30 seconds) - Add statement_timeout: 60000 (60 seconds) These settings help prevent 'Unknown transaction status' errors during heavy database operations like seeding by giving transactions more time to complete and allowing more concurrent connections. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * Revert "fix: increase pool size and add timeout settings to prevent transaction errors" This reverts commit 148264f1f1861dfb09a082937a3e2b49e78fc41a. * fix: remove standalone execution in seed-app-store to prevent premature disconnect The seed-app-store.ts file had a standalone main() call at the bottom that would execute immediately when imported, including a prisma.$disconnect() in its .finally() block. This caused issues because: 1. seed.ts imports and calls mainAppStore() 2. The import triggers the standalone main() execution 3. This standalone execution disconnects prisma after completion 4. seed.ts then tries to call mainHugeEventTypesSeed() but prisma is disconnected 5. This leads to 'Unknown transaction status' errors Fixed by removing the standalone execution since mainAppStore() is already called programmatically from seed.ts which manages the connection lifecycle. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: use require.main check to prevent premature disconnect when imported Added require.main === module check so seed-app-store.ts: - Runs standalone with proper connection management when executed directly via 'yarn seed-app-store' or 'ts-node seed-app-store.ts' - Does NOT run standalone when imported as a module by seed.ts, preventing premature prisma disconnect This fixes 'Unknown transaction status' errors while maintaining backward compatibility for direct execution. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: seed apps before creating users to prevent foreign key constraint violation Reordered seeding operations to call mainAppStore() before main() because: - main() creates users with credentials that reference apps via appId foreign key - mainAppStore() seeds the App table with app records - Apps must exist before credentials can reference them This fixes the 'Foreign key constraint violated on Credential_appId_fkey' error that occurred when creating credentials before the apps they reference existed. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * Apply suggestion from @cubic-dev-ai[bot] Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> * Removing functional changes of deleted: null * Apply suggestion from @keithwillcode * refactor: move seedAppData call to bottom of main() in seed.ts Moved seedAppData() call from seed-app-store.ts to the bottom of main() in seed.ts to ensure the 'pro' user is created before attempting to create routing form data for them. Changes: - Exported seedAppData function from seed-app-store.ts - Removed seedAppData() call from the main() export in seed-app-store.ts - Added seedAppData() call at the bottom of main() in seed.ts - Updated standalone execution in seed-app-store.ts to still call seedAppData() when run directly via 'yarn seed-app-store' This ensures proper ordering: apps seeded → users created → routing form data created for existing users. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * refactor: move routing form seeding from seed-app-store.ts to seed.ts Moved the routing form seeding logic (previously in seedAppData function) from seed-app-store.ts to be inline at the bottom of main() in seed.ts. This ensures the 'pro' user is created before attempting to create routing form data for them. Changes: - Removed seedAppData function and seededForm export from seed-app-store.ts - Removed import of seedAppData from seed.ts - Added routing form seeding logic inline at bottom of main() in seed.ts Seeding order: apps → users (including 'pro') → routing forms Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * fix: add deleted: null filter to bookingReference update operations - Add deleted: null filter to API v1 PATCH endpoint to prevent updating soft-deleted booking references - Add deleted: null filter to DailyVideo updateMeetingTokenIfExpired and setEnableRecordingUIAndUserIdForOrganizer - Add comprehensive test coverage for PATCH endpoint soft-delete behavior - Tests verify that soft-deleted booking references cannot be updated - Tests verify that only active booking references can be updated successfully Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * revert: remove deleted: null filters to preserve existing functionality Per @keithwillcode's feedback, reverting the soft-delete filtering changes to preserve existing functionality in this PR. This PR should focus only on the Prisma upgrade itself. - Reverted API v1 PATCH endpoint change - Reverted DailyVideo adapter changes (updateMeetingTokenIfExpired and setEnableRecordingUIAndUserIdForOrganizer) - Removed test file that was added for soft-delete behavior testing Addresses comments: - https://github.com/calcom/cal.com/pull/23816#discussion_r2448854197 - https://github.com/calcom/cal.com/pull/23816#discussion_r2448860594 - https://github.com/calcom/cal.com/pull/23816#discussion_r2448860833 Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * test: restore and update booking reference tests to match existing functionality Updated tests to verify existing behavior where PATCH endpoint can update booking references regardless of their deleted status. This matches the current implementation after reverting the deleted: null filters. Changes: - Restored test file that was previously deleted - Updated PATCH tests to expect successful updates of soft-deleted references - Renamed test suite to 'Existing functionality' to clarify intent - Tests now verify that the PATCH endpoint preserves existing behavior Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> * test: rename booking-references test to integration-test The test requires a database connection and should run in the integration test job, not the unit test job. Renamed from .test.ts to .integration-test.ts to match the repository's testing conventions. Co-Authored-By: keith@cal.com <keithwillcode@gmail.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> |
||
|
|
870ad57a7e | Rename handleNewBooking to BookingCreateService (#23682) | ||
|
|
5e5e77236a | chore: Add skeleton for BookingCancelService (#24038) | ||
|
|
3bcce02b92 |
chore: [Booking flow refactor - 2] Integrate Booking services (#23156)
* Integrate booking services * Fix imports --------- Co-authored-by: Volnei Munhoz <volnei.munhoz@gmail.com> |
||
|
|
c28eb90928 |
chore: Upgrade prisma to 6.7.0 (#21264)
* chore: Upgrade prisma to 6.7.0 * Build fixes * type fixes Signed-off-by: Omar López <zomars@me.com> * Update schema.prisma * Patching * Revert "Update schema.prisma" This reverts commit 47d8618bf89ef4d007b30084df766f17281e21a1. * Revert "Patching" This reverts commit a1d2e3040e71690a44d4324db95d73b4d68c6adb. * Revert schema changes Signed-off-by: Omar López <zomars@me.com> * WIP Signed-off-by: Omar López <zomars@me.com> * Update getPublicEvent.ts * Update imports Signed-off-by: Omar López <zomars@me.com> * Update gitignore Signed-off-by: Omar López <zomars@me.com> * update remaining imports Signed-off-by: Omar López <zomars@me.com> * Delete .cursor/config.json * Discard changes to packages/features/eventtypes/lib/getPublicEvent.ts * Update _get.ts * Update user.ts * Update .gitignore * update * Update WorkflowStepContainer.tsx * Update next-auth-custom-adapter.ts * Update getPublicEvent.ts * Update workflow.ts * Update next-auth-custom-adapter.ts * Update next-auth-options.ts * Update bookingScenario.ts * fix missing imports * upgrades prismock Signed-off-by: Omar López <zomars@me.com> * patches prismock Signed-off-by: Omar López <zomars@me.com> * Update reschedule.test.ts * Update prisma.ts * patch prismock Signed-off-by: Omar López <zomars@me.com> * fix enums imports Signed-off-by: Omar López <zomars@me.com> * Revert "Update prisma.ts" This reverts commit 64edcf8db54171ff4456c209d563b5d431d99619. * Revert "patch prismock" This reverts commit e95819113dc9d88e7130947aa120cd42710977c8. * fix patch * Fix test that overrun the boundary, it shouldn't test too much * Move prisma import to changeSMSLockState * Bring back broken test without illegal imports * Merge with main and fix filter hosts by same round robin host * Fixed buildDryRunBooking fn tests * Fix and move ooo create or update handler test * Fix packages/features/eventtypes/lib/isCurrentlyAvailable.test.ts * Fix packages/trpc/server/routers/viewer/organizations/listMembers.handler.test.ts * Mock @calcom/prisma * Fix: verify-email.test.ts * fix: Moved WebhookService test and fixed default import mock * Fix: Added missing prisma mock, handleNewBooking uses that of course * We're not testing createContext here * fix: Prisma mock fix for listMembers.test.ts * More fixes to broken testcases * Forgot to remove borked test * Prevent the need to mock a lot of dependencies by moving out buildBaseWhereCondition to its own file * Temporarily skip getCalendarEvents, needs a rewrite * Fix: turns out you can access protected in testcases * fix further mocks * Added packages/features/insights/server/buildBaseWhereCondition.ts, types * Always great to have a mock and then not use it * And one less again. * fix: confirm.handler.test, didn't mock prisma * fix: Address minor nit by @eunjae & fix ImpersonationProvider test * Updated isPrismaAvailableCheck that doesn't crash on import * fix: Get Prisma directly from the client, it usually involves the Validator and does not need 'local' inclusion * Add zod-prisma-types without the generator enabled (commented out) * Uncomment and see what happens * Change method of import as imports did not work in Input Schemas * Remove custom 'zod' booking model, it does not belong with Prisma * Fix all other global Model imports * Rewrite most schema includes AND remove barrel file * Add bookingCreateBodySchema to features/bookings * Flurry of type fixes for compatibility with new zod gen * Refactor out the custom prisma type createEventTypeInput * Work around nullable eventTypeLocations * HandlePayment type fix * More fixes, final fix remaining is CompleteEventType * Should fix a bunch more booking related type errors * Missed one * Some props missing from BookingCreateBodySchema * Fix location type in handleChildrenEventTypes * Little bit hacky imo but it works * Final type error \o/ * Forgot to include Prisma * Do not include zod-utils in booker/types * Oops, was already including Booker/types * Fix membership type, also disallow updating createdAt/updatedAt, make part of patch/post * Fix api v1 type errors * Fix EventTypeDescription typings * Remove getParserWithGeneric, use userBodySchema with UserSchema * use centralized timeZoneSchema * Implement feedback by @zomars * Couple of WIP pushes * Fix tests * Type fixes in `handleChildrenEventTypes` test * Try and parse metadata before use * Change zod-prisma-types configuration for optimal performance * Fix prisma validator error in `prisma/selects/credential` * Disable seperate relations model, hits a bug * Import absolute - this makes rollup work in @platform/libraries * Attempt at removing resolutions override * Refactor using `Prisma.validator` to `satisfies` * Build atoms using @calcom/prisma/client * Build atoms using @calcom/prisma/client * fixes * Update eventTypeSelect.ts * Adjust `eventTypeMetaDataSchemaWithUntypedApps` from `unknown` to `record(any)` * `EventTypeDescription` rely on `descriptionAsSafeHTML` instead of `description` * Add `seatsPerTimeSlot` to event type public select * Fix typing in `users-public-view` getServerSide props * Add missing `schedulingType` to prop * chore: bump platform libraries * Function return type is illegal, not sure how this passed eslint (#21567) * Merged with main * Update updateTokenObject.ts * Update handleResponse.ts * Update index.ts * Update handleChildrenEventTypes.ts * Update booking-idempotency-key.ts * Update WebhookService.test.ts * Update events.test.ts * Update queued-response.test.ts * Update events.test.ts * Update getRoutedUrl.test.ts * fix: type checks Signed-off-by: Omar López <zomars@me.com> * fixes Signed-off-by: Omar López <zomars@me.com> * chore: bump platform libraries * Update yarn.lock * more fixes Signed-off-by: Omar López <zomars@me.com> * fixes Signed-off-by: Omar López <zomars@me.com> * biuld fixes * chore: bump platform libraries * Update conferencing.repository.ts * Update conferencing.repository.ts * Update getCalendarsEvents.test.ts * Update vite.config.js * chore: bump platform libraries * Update users.ts * Discard changes to docs/api-reference/v2/openapi.json * Update vite.config.ts * updated platform libraries * Update get.handler.test.ts * Update get.handler.test.ts * Update schema.prisma * Discard changes to docs/api-reference/v2/openapi.json * Update next-auth-custom-adapter.ts * Update team.ts * Flurry of type fixes * Fix majority of insight related type errors * Type fixes for unlink of account * Make user nullable again * Fixed a bunch of unit tests and one type error * Attempted mock fix * Attempted fix for Attribute type * Ensure default import becomes prisma, but not direct usage * Import default as prisma in prisma.module * Add attributeOption to attribute type * Fix calcom/prisma mock * Refactor Prisma client imports to @calcom/prisma/client Updated all imports from '@prisma/client' to '@calcom/prisma/client' across tests and repository files for consistency and to use the correct Prisma client package. This change improves maintainability and ensures the correct client is referenced throughout the codebase. * Undo removal of max-warnings=0 to get main to merge * Remove unit tests for e2e fixtures, provide new prisma mock * Mock @calcom/prisma in event manager * Mock @calcom/prisma in event manager * Add correct format even with --no-verify * Mock prisma in CalendarManager * Add mock for permission-check.service * Better injection in PrismaApiKeyRepository imports * More mock fixes :) * Fix listMembers.handler.test * Fix User import * Appropriately adjust all types to be imported as types, there were a lot of types imported as normal deps * Why was this a thing? * Strictly speaking; Not using prismock anymore * Ditched patch file for prismock * Fix output.service.ts platform type imports, need concrete for plainToClass * Better typing and tests for unlinkConnectedAccount.handler * Small type fix * Disable calendar cache tests as they are dependent on prismock * chore: bump platform lib * getRoutedUrl test remove of unused import * Extract select to external const on getEventTypesFromDB * Direct select of userSelect from selects/user * fix type error from merging 23653 * Fixed integration tests by removing hardcoded values that were possible due to mocking, but as its now directly hitting the db no longer * fix: vite config atoms prisma client type location * revert: example app prisma client * revert: example app prisma client * bump platform libs * fix: use class instead of type for DI of PlatformBookingsService * update platform libs * remove unused variable * chore: generate prisma client for api v2 * fix: api v2 e2e * fix: atoms e2e * fix: atoms e2e * fix: atoms e2e * fix: api v2 e2e * fix: tsconfig apiv2 enums * publish libraries * Simplify check for existence teamId --------- Signed-off-by: Omar López <zomars@me.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com> Co-authored-by: supalarry <laurisskraucis@gmail.com> Co-authored-by: cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> Co-authored-by: Benny Joo <sldisek783@gmail.com> |
||
|
|
0bf95ec568 |
fix: Update prisma enums to platform libs (#23604)
* fix: Cant import from prisma/enums, import requires platform-libraries * Bumped @calcom/prisma-libraries * Migrate a leftover @calcom/prisma/client import * Added missing WorkflowTriggerEvents |
||
|
|
7bf5d9cf64 |
perf: import enums from @calcom/prisma/enums (#23582)
* wip * fix imports in the rest * rest * fix mistake |
||
|
|
ba8cca55e8 |
refactor: convert lucky user to service class (#23329)
* refactor: lucky user to service class with DI * fix: unit test filterHostsByLeadThreshold.test.ts * fixup! fix: unit test filterHostsByLeadThreshold.test.ts * fix: get lucky user test missing mocks * fix: get lucky user hosts not within interval * chore: bump platform library * chore: bump platform library * chore: add DAILY_API_KEY to turborepo.json db seed * chore: add DAILY_API_KEY to cache-db action * fixup! chore: add DAILY_API_KEY to cache-db action * chore: remove log in fixture * chore: bump platform library * chore: refactor test team-emails.e2e * only failing test * run all api v2 tests * chore: bump platform library * revert change to turbo.json and action in cache-db * chore: use inPerson location in team-emails.e2e |
||
|
|
13e2e340ac |
refactor: convert handleNotificationWhenNoSlots to service class with DI (#23055)
* refactor: convert handleNotificationWhenNoSlots to service class with DI - Convert standalone handleNotificationWhenNoSlots function to NoSlotsNotificationService class - Add INoSlotsNotificationService interface following existing patterns - Create NoSlotsNotification DI module and add to container - Add NO_SLOTS_NOTIFICATION_SERVICE tokens to DI_TOKENS - Inject service into AvailableSlotsService dependencies - Update AvailableSlotsService to use injected service instead of direct function call - Update all test cases to use service class pattern - Follows existing DI patterns used by other services like BusyTimesService and CheckBookingLimitsService Co-Authored-By: morgan@cal.com <morgan@cal.com> * refactor: move Prisma calls to repositories and create dedicated DI container - Add findOrganizationSettingsBySlug and findTeamSlugById methods to TeamRepository - Add findTeamAdminsByTeamId method to MembershipRepository - Create MembershipRepository DI module and tokens - Update NoSlotsNotificationService to inject TeamRepository, MembershipRepository, and Redis client - Create dedicated DI container for NoSlotsNotificationService - Update AvailableSlots DI container to include MembershipRepository - Replace direct Prisma and Redis calls with repository methods and injected client - Update tests to use DI container instead of direct service instantiation - Fix Redis interface import path Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore: DI noSlotsNotification service * chore: bump library --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: morgan@cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> |
||
|
|
211b958c58 |
refactor: move isRestrictionScheduleEnabled into AvailableSlotsService with DI (#23015)
* refactor: move isRestrictionScheduleEnabled into AvailableSlotsService with DI - Remove external isRestrictionScheduleEnabled function call from AvailableSlotsService - Add IFeaturesRepository to IAvailableSlotsService interface dependencies - Implement checkRestrictionScheduleEnabled private method within AvailableSlotsService - Update DI module to inject featuresRepo dependency - Update API v2 service to pass featuresRepository to base service - Resolves TODO comment about implementing DI for isRestrictionScheduleEnabled Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore: bump platform libs * fix: api v2 di for qualifiedHostsService * chore: bump platform libs * fix unit test --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: morgan@cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> |
||
|
|
29314cde75 |
refactor: convert getBusyTimes to service class with dependency injection (#22949)
* refactor: convert getBusyTimes to service class with dependency injection - Create BusyTimesService following UserAvailabilityService pattern - Add DI tokens, module, and container setup for BusyTimesService - Update all usage locations to use service instead of direct function calls - Maintain existing function signatures for backward compatibility - Add legacy exports to ensure smooth transition - Update type references in trpc util to use service prototype - Fix linting issues by making legacy exports async with proper imports - All tests pass and type checking succeeds Co-Authored-By: morgan@cal.com <morgan@cal.com> * refactor: busy time service * fix: api v2 eslint plugins version mismatch * chore: bump platform libs * chore: bump platform libs * fix: missing di busyTimesModule in slots service --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: morgan@cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> |
||
|
|
e4baf15b53 |
feat: Sync timezone for users having delegation credentials for google/outlook (#22904)
* feat: sync timezone with google/outlook for delegated credentials users * chore: dynamic sync timezone in get availble slots * redis cache for get delegated timezone * Update packages/lib/getUserAvailability.ts --------- Co-authored-by: Alex van Andel <me@alexvanandel.com> |
||
|
|
b71d8baccc |
chore: Implement short-lived redis cache for slots (#22787)
* chore: Implement short-lived redis cache for slots * chore: adapt apiv2 redis service to match with upstash redis * chore: safer redis service and ms ttl * fixup! chore: safer redis service and ms ttl * Wrap with timeout, currently doesn't work yet * Updated @upstash/redis for better signal support * Fix type errors, remove ts value * Inject NoopRedisService for NODE_ENV test * chore: bump platform libs * chore: bump platform libs * Upstash Redis upgrade no longer resulted in expected hard crash on init, so updated factory and our Upstash Redis Adapter to mimick old behaviour * Add SLOTS_CACHE_TTL variable for configurable ttl on slots cache * Update parseInt to use right types * chore: bump platform libs * chore: bump platform libs * chore: bump platform libs * update e2e api v2 action * set SLOTS_CACHE_TTL env var api v2 e2e --------- Co-authored-by: cal.com <morgan@cal.com> |
||
|
|
c3634b3aba |
refactor: getUserAvailability into service with DI (#22881)
* refactor: getUserAvailability into service with DI * chore: bump platform libs * disable bull queue in e2e for bookings * chore: bump platform libs * chore: bump platform libs * fix: should update event type bookingFields test --------- Co-authored-by: Alex van Andel <me@alexvanandel.com> |
||
|
|
1d1a242a72 |
refactor: convert getShouldServeCache to CacheService with dependency injection (#22814)
* refactor: convert getShouldServeCache to CacheService with dependency injection - Create CacheService class following AvailableSlotsService DI pattern - Add FeaturesRepository and CacheService to DI tokens and modules - Create cache container with proper dependency injection setup - Update handleNewBooking.ts and slots/util.ts to use new service - Maintain backward compatibility with error-throwing wrapper function - Follow established service patterns for clean architecture Co-Authored-By: morgan@cal.com <morgan@cal.com> * feat: inject CacheService into AvailableSlotsService via dependency injection - Add cacheService to IAvailableSlotsService interface - Update available-slots container to load cache modules - Update available-slots module to inject CacheService dependency - Replace direct getShouldServeCache call with injected service method - Add CacheService import to util.ts for proper typing Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore: DI api v2 cache service * refactor: convert FeaturesRepository to use factory pattern in DI - Change from constructor injection to factory pattern to avoid PRISMA_CLIENT binding issues in tests - FeaturesRepository now uses default prisma instance instead of DI injection - Resolves test failures while maintaining DI container compatibility - Tests reduced from 123+ failures to only 5 unrelated failures Co-Authored-By: morgan@cal.com <morgan@cal.com> * revert: use direct FeaturesRepository instantiation in most usage points - Revert getFeaturesRepository() calls back to new FeaturesRepository() - Tests require direct instantiation for mocking compatibility - Keep DI container for specific use cases that need dependency injection - Resolves test failures while maintaining both DI and direct usage patterns Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: resolve FeaturesRepository DI container issues - Update cache module to use factory pattern with proper ICacheService interface - Remove featuresModule loading from cache and available-slots containers - Use direct FeaturesRepository instantiation via getFeaturesRepository() - Resolves 'No binding found for key: Symbol(FeaturesRepository)' errors - Reduces test failures from 125 to 7 (remaining failures appear unrelated) Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: update all FeaturesRepository instantiations to include prisma parameter - Add prisma parameter to all new FeaturesRepository() calls across the codebase - Update API v2 services to match main repo interfaces - Fix PrismaFeaturesRepository to implement IFeaturesRepository directly - Update CacheService in API v2 to expose required dependencies and getShouldServeCache - Implement CheckBookingLimitsService in API v2 with proper interface - Resolves type assignment errors between API v2 and main repo implementations Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: add prisma parameter to remaining FeaturesRepository instantiations in apps/web/lib - Update getServerSideProps files to pass prisma parameter to FeaturesRepository - Ensures all FeaturesRepository instantiations follow the new constructor pattern - Completes the refactoring to use direct instantiation with prisma parameter Co-Authored-By: morgan@cal.com <morgan@cal.com> * refactor clean and fix devin issues * chore: bump platform libs * chore: bump platform libs * chore: bump platform libs * chore: bump platform libs * fix: missing di * fix workflow test * fix workflow test * fix integration test --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: morgan@cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> |
||
|
|
82063cc9a1 |
refactor: convert checkBookingLimits to class service with dependency injection (#22768)
* refactor: convert checkBookingLimits to class service with dependency injection - Create CheckBookingLimitsService class following AvailableSlotsService pattern - Add countBookingsByEventTypeAndDateRange method to BookingRepository - Move direct prisma calls from service to repository layer - Implement dependency injection with proper DI tokens and modules - Update all usage points to use the new service through DI - Maintain backward compatibility with error-throwing wrapper functions - Update tests to use the new service pattern - Resolve TODO comment in AvailableSlotsService for DI integration Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore: DI CheckBookingLimitsService in v2 slots service * chore: bump libraries * chore: create getCheckBookingLimitsService * refactor: convert checkBookingAndDurationLimits to service class with DI - Create CheckBookingAndDurationLimitsService class following DI pattern - Add DI tokens and module for the new service - Update booking-limits container to provide the new service - Refactor handleNewBooking.ts to use service through DI - Maintain backward compatibility with deprecated function export - Preserve all existing functionality while improving code organization Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore: CheckBookingAndDurationLimitsService * chore: bump platform libs --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: morgan@cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> |
||
|
|
d1bd05a791 | chore: hash rate limit trackers api v2 (#22767) | ||
|
|
fde1d671fb |
refactor: rename SelectedSlotsRepository to PrismaSelectedSlotRepository (#22705)
* refactor: rename SelectedSlotsRepository to PrismaSelectedSlotRepository - Rename class from SelectedSlotsRepository to PrismaSelectedSlotRepository for consistency - Update all imports and type references throughout the codebase - Update DI module bindings and variable names - Maintain type safety without breaking changes Co-Authored-By: alex@cal.com <me@alexvanandel.com> * refactor: complete PrismaSelectedSlotRepository rename - Update DI module binding property name from selectedSlotsRepo to selectedSlotRepo - Update test mock to use PrismaSelectedSlotRepository class name - Ensure all references are consistently updated Co-Authored-By: alex@cal.com <me@alexvanandel.com> * fix: rename file to prismaSelectedSlotRepository.ts and fix plural variable references - Rename apps/api/v2/src/lib/repositories/prisma-selected-slots.repository.ts to prismaSelectedSlotRepository.ts - Update class name from PrismaSelectedSlotsRepository to PrismaSelectedSlotRepository - Fix plural variable reference selectedSlotsRepository to selectedSlotRepository in service - Update all import paths to reference the new file name - Maintain consistency with camelCase naming convention Co-Authored-By: alex@cal.com <me@alexvanandel.com> * fix: rename SelectedSlotsRepositoryFixture to SelectedSlotRepositoryFixture for consistency - Rename test fixture class from SelectedSlotsRepositoryFixture to SelectedSlotRepositoryFixture (singular) - Update all import statements in test files to use the renamed class - Resolves naming mismatch between fixture class and variable declarations - Fixes TypeScript compilation errors in CI tests Co-Authored-By: alex@cal.com <me@alexvanandel.com> * feat: add SelectedSlotRepositoryInterface and update DI to use interface Co-Authored-By: alex@cal.com <me@alexvanandel.com> * refactor: rename selectedSlots.ts to selectedSlot.ts and update all imports Co-Authored-By: alex@cal.com <me@alexvanandel.com> * fix: update test mock import path after file rename Co-Authored-By: alex@cal.com <me@alexvanandel.com> * Update apps/api/v2/src/lib/modules/available-slots.module.ts * Update apps/api/v2/src/lib/modules/available-slots.module.ts * Implement DTO * dont declare dependencies locally, duplicating * Small DTO/token fix * chore: bump @calcom/platform-libraries from 0.0.266 to 0.0.267 * oops. * Update fixture names also * Omg these vscode actions preventing saves * Final fix, hopefully --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com> |
||
|
|
13cb99b7fe |
feat: inject required repositories into AvailableSlotsService using dependency injection (#22413)
* feat: inject all repositories into AvailableSlotsService using dependency injection - Create DI modules for SelectedSlotsRepository, TeamRepository, UserRepository, BookingRepository, EventTypeRepository, RoutingFormResponseRepository - Update available-slots DI module to bind all 6 repositories - Update DI container to load all new repository modules - Replace all 10 direct repository instantiations with injected dependencies - Add missing DI tokens for repository modules - Expand IAvailableSlotsService interface to include all repository dependencies This follows the same dependency injection pattern established in previous repository refactoring PRs and enables better testability and modularity by making all dependencies explicit and configurable. Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore: DI available slots repo on api v2 * chore: bump platform libs --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: morgan@cal.com <morgan@cal.com> |
||
|
|
5c508bce6d |
chore: DI repositories in AvailableSlotsService class (#22356)
* chore: DI available slots service repositories * remove configService from worker module * register scheduleRepo in availableSlotsModule * chore: bump platform libs * remove useless comment from prisma module * fix: availableSlotsModule to class deps * fix: repositoriesModule deps * chore: container pattern * refactor: move modules in DI folder * fixup! refactor: move modules in DI folder |
||
|
|
db84343581 |
chore: new auth strategy for third party access tokens (#21867)
* chore: new auth strategy for third party access tokens * chore: throw error earlier if Bearer token is invalid * fix: check apikey and access token before third party token |
||
|
|
27dce7374b | feat: Add Bengali Language Support. This fixes #17717 (#20567) | ||
|
|
b21295f268 | chore: add user org id to user context apiv2 axiom (#22236) | ||
|
|
d04c7f58a1 | chore: stringify user context ids apiv2 axiom (#22234) | ||
|
|
21422fe027 |
feat: enhance API v2 exception filters with user context for improved Axiom observability (#22157)
* feat: enhance API v2 exception filters with user context for improved Axiom observability - Add extractUserContext utility to safely extract user/org/team context from request - Enhance all 5 exception filters (HTTP, TRPC, Prisma, Zod, Calendar) with user context - Include userId, userEmail, organizationId, teamId in Axiom logs when available - Improve observability for debugging and monitoring authenticated requests Co-Authored-By: morgan@cal.com <morgan@cal.com> * chore: update yarn.lock from lint-staged hooks Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: use request.organization instead of request.organizationId - Address GitHub comment feedback from ThyMinimalDev - Extract organization ID from organization object for consistency - Follows same pattern as user and team extraction Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: revert to using request.organizationId as requested in GitHub comment - Change back from request.organization to request.organizationId - This aligns with how auth strategies actually populate the request object - Addresses GitHub comment from ThyMinimalDev Co-Authored-By: morgan@cal.com <morgan@cal.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: morgan@cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> |
||
|
|
493c4f89dc | Remove redundant logging (#22108) | ||
|
|
2aafa1c163 |
feat: v2 managed organizations pagination (#21359)
* feat: getPagination helper * refactor: bookings use getPagination helper * feat: getPagination helper * refactor: group pagination inputs and outputs in types/pagination * feat: paginated managed orgs * fix tests * swagger |
||
|
|
0f0c2b8b92 |
feat: verified resources endpoint [v2] (#21006)
* feat: verified resources endpoint [v2] * add tests and fixes * chore: add endpoint throttler decorator and handling * chore: code review comments * chore: code review comments * chore: code review comments * bump platform libraries * chore: add tests and fix issues |
||
|
|
7f02464fed |
refactor: forbidden 403 v2 guard messages (#20794)
* refactor: delete unused proxy guard * refactor: roles.guard.ts * refactor: is-org.guard.ts * refactor: permissions.guard.ts * refactor: oauth-client-guard.ts * refactor: is-user-event-type-webhook-guard.ts * refactor: platform-plan.guard.ts * refactor: roles.guard.ts * refactor: cache guard result if canAccess=true * refactor: is-admin-api-enabled.guard.ts * refactor: is-team-in-org.guard.ts * refactor: platform-plan.guard.ts * refactor: is-webhook-in-org.guard.ts * refactor: is-user-in-org.guard.ts * refactor: is-user-webhook-guard.ts * refactor: is-user-in-org-team.guard.ts * refactor: is-membership-in-org.guard.ts * refactor: is-oauth-client-webhook-guard.ts * refactor: is-routing-form-in-team.guard.ts * refactor: is-managed-org-in-manager-org.guard.ts * fill the gaps * refactor: api-auth.strategy.ts * fix: test * implement feedback * fix: tests * fix: refactor * fix: test |
||
|
|
2e0f4d3176 | fix: use real ip in throttler [v2] (#20606) |