* feat: api-v2-event-types-ordering
* sort team and org event types
* revert: remove accidental changes to api-auth.strategy.ts
* docs: add ordering documentation and test for event types endpoints
- Added test assertion to verify event types are returned in descending order by ID (newest first)
- Added API documentation to user event types endpoint describing default ordering behavior
- Added API documentation to team event types endpoint describing default ordering behavior
- Added API documentation to organization event types endpoints describing default ordering behavior
Addresses PR feedback to document and test the ordering behavior introduced in the API v2 event types ordering feature.
* feat: add optional sortCreatedAt parameter to event types endpoints
- Add sortCreatedAt query parameter (SortOrderType: "asc" | "desc") to all event types endpoints
- Define SortOrder enum and SortOrderType in pagination.input.ts for reusability
- When not provided, no explicit ordering is applied (backward compatible)
- Update user, team, and organization event types endpoints
- Add comprehensive e2e tests for all sorting scenarios
- Fix circular dependency in platform-types import
- Thread sortCreatedAt through all service layers
- Use spread pattern for conditional orderBy to avoid empty array issues
Addresses PR feedback to make ordering opt-in rather than changing default behavior
* fix: preserve seatsPerTimeSlot during partial event type updates
When doing a partial update on the PATCH /v2/organizations/{orgId}/teams/{teamId}/event-types/{eventTypeId} endpoint, providing a partial body would reset seatsPerTimeSlot back to null because the transformSeatsApiToInternal function was always called even when seats was undefined.
This fix ensures that the seat options are only transformed when the seats field is explicitly provided in the update request, preserving existing values during partial updates.
Also adds e2e test to verify partial updates preserve seatsPerTimeSlot.
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: handle TypeScript union type narrowing for seatsPerTimeSlot
When seats is not provided in a partial update, the transformed body
may not have seatsPerTimeSlot property. This fix uses 'in' operator
to safely check for the property before accessing it.
Also fixes the e2e test to properly narrow the union type for seats
using type guards.
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* refactor: simplify seatsPerTimeSlot handling per review feedback
Per supalarry's suggestion, instead of using 'in' operator checks in
multiple validation calls, we now return {seatsPerTimeSlot: undefined}
when seats is not provided. This keeps the validation code unchanged
and only requires modifying one line in the transformation.
Co-Authored-By: morgan@cal.com <morgan@cal.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix: allow false for custom field 'fieldRequired' by using z.boolean()
* updated to z.boolean().optional()
---------
Co-authored-by: Pallav <90088723+Pallava-Joshi@users.noreply.github.com>
* 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>
* 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
* feat: add validation for null values in bookingFieldsResponses
- Add test case to verify 400 error when bookingFieldsResponses contains null values
- Create ValidateBookingFieldsResponses decorator to reject null values in booking field responses
- Apply validator to CreateBookingInput_2024_08_13.bookingFieldsResponses property
- Ensure all booking field response values are non-null strings
* feat: transform null values to empty strings in bookingFieldsResponses
- Remove ValidateBookingFieldsResponses validator that rejected null values
- Add Transform decorator to convert null values to empty strings in bookingFieldsResponses
- Update test to verify null values are transformed to empty strings instead of returning 400 error
* remove extra spaces
* test: add rescheduleReason null value test case
---------
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
* feat: add avatarUrl to /v2/me endpoint response
- Add avatarUrl field to userSchemaResponse schema in packages/platform/types/me.ts
- Update e2e tests to verify avatarUrl is returned in GET and PATCH /v2/me responses
- Field is nullable to match User model in Prisma schema
- Fix pre-existing lint warnings by removing 'as any' type assertions in test file
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* feat: add avatarUrl to MeOutput DTO for OpenAPI docs
- Add avatarUrl field to MeOutput class in apps/api/v2/src/ee/me/outputs/me.output.ts
- Field is nullable to match the Zod schema and Prisma model
- This ensures OpenAPI documentation will include avatarUrl when regenerated
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* feat: add bio field to /v2/me endpoint response
- Add bio field to userSchemaResponse Zod schema in packages/platform/types/me.ts
- Add bio field to MeOutput NestJS DTO in apps/api/v2/src/ee/me/outputs/me.output.ts
- Update e2e tests to verify bio is returned in both GET and PATCH responses
- Field is nullable to match the User model in Prisma schema
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: chauhan_s <somaychauhan98@gmail.com>
* Revert "fix: resolve flaky integration tests (#25030)"
This reverts commit 4e5d4f67d5.
* update
* test
* Remove connection pool setup in Prisma index
Set the connection pool to undefined, removing conditional pooling logic.
* update
* feat: add delegation credential error webhook trigger
- Add DELEGATION_CREDENTIAL_ERROR to WebhookTriggerEvents enum
- Create DelegationCredentialErrorDTO type for webhook payload
- Implement DelegationCredentialErrorWebhookService
- Add translation for delegation_credential_error
- Enable webhook for API v2 organization webhooks
This webhook will send delegation credential error data to configured URLs when errors occur during calendar authentication with delegation credentials.
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* fix: add delegation credential error payload type and type guards
- Add DelegationCredentialErrorPayloadType to sendPayload.ts
- Update WebhookPayloadType union to include new payload type
- Add isDelegationCredentialErrorPayload type guard function
- Update isEventPayload to exclude delegation credential errors
- Update template application logic to handle new payload type
- Add corresponding payload type to dto/types.ts for consistency
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* feat: add delegation credential error handling to WebhookNotificationHandler
- Add DELEGATION_CREDENTIAL_ERROR case to createPayload switch
- Return payload with error, credential, and user data
- Ensures exhaustive type checking passes for new trigger
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* feat: restrict DELEGATION_CREDENTIAL_ERROR to organization webhooks only
- Add validation in UserWebhooksService to reject DELEGATION_CREDENTIAL_ERROR
- Add validation in EventTypeWebhooksService to reject DELEGATION_CREDENTIAL_ERROR
- Ensures trigger is only available for API v2 organization webhooks as requested
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* feat: wire up delegation credential error webhook emission in calendar services
- Add webhook emission calls in CalendarAuth.ts for Google Calendar delegation errors
- Add webhook emission calls in Office365 CalendarService.ts for Azure AD delegation errors
- Implement actual webhook emission using WebhookRepository pattern
- Fix pre-existing lint warnings in Office365 CalendarService.ts (unused catch variables, unsafe optional chaining)
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* test: add e2e tests for DELEGATION_CREDENTIAL_ERROR webhook trigger
- Add comprehensive e2e tests for creating, retrieving, updating, and deleting webhooks with DELEGATION_CREDENTIAL_ERROR trigger
- Test combining DELEGATION_CREDENTIAL_ERROR with other triggers
- Fix import in triggerDelegationCredentialErrorWebhook.ts to use default import for sendPayload
- Tests follow existing patterns in organizations-webhooks.e2e-spec.ts
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* refactor: remove name field from webhook payload and delete unused service
- Remove name field from triggerDelegationCredentialErrorWebhook function signature and payload
- Update all call sites in GoogleCalendar and Office365 calendar services
- Update DelegationCredentialErrorDTO and DelegationCredentialErrorPayloadType to remove name field
- Delete unused DelegationCredentialErrorWebhookService.ts (dead code - not used anywhere)
- The helper function approach is more appropriate for app-store integrations without DI
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* refactor: make fire-and-forget intent explicit for webhook emission
- Add void cast to all triggerDelegationCredentialErrorWebhook calls
- Remove redundant .catch() handlers (helper already handles errors internally)
- This makes it clear that webhook emission is non-blocking by design
- Avoids delaying error propagation while webhook HTTP requests complete
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* feat: await webhook emission and add HTTP timeout for guaranteed delivery
- Change all triggerDelegationCredentialErrorWebhook calls from void to await
- Add 10-second timeout to webhook HTTP requests using AbortController
- Remove name field from DelegationCredentialErrorPayloadType to match payload
- Ensures webhooks are sent before error is thrown (per user requirement)
- Prevents indefinite hangs on unresponsive webhook endpoints
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* fix: make getAuthUrl async and await all call sites
- Make getAuthUrl async to support awaiting webhook emission
- Add await to all 3 getAuthUrl call sites (constructor, getAzureUserId, testDelegationCredentialSetup)
- Remove leftover name field from getAzureUserId webhook call
- Fixes TS1308 error about await in non-async function
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* docs: add JSDoc clarifying error handling guarantees for webhook trigger
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* Revert "docs: add JSDoc clarifying error handling guarantees for webhook trigger"
This reverts commit 3e33090197bfe2f2e3fb890402b32e04c44305e3.
* Revert "fix: make getAuthUrl async and await all call sites"
This reverts commit de28b7337149104412c861fd9b05e76fffc1fed7.
* Revert "feat: await webhook emission and add HTTP timeout for guaranteed delivery"
This reverts commit 9da7241f83a8373b4fadc03ccf34e097c28adf3a.
* Revert "refactor: make fire-and-forget intent explicit for webhook emission"
This reverts commit f4f7fa06b7dfa151bfbea29905b8783261d9f353.
* feat: await webhook emission to match standard pattern
- Updated all webhook call sites to await triggerDelegationCredentialErrorWebhook
- Made getAuthUrl async and updated all 3 call sites to await it
- Removed .catch() wrappers at call sites (error handling is in trigger function)
- Matches standard pattern used in WebhookService.sendPayload with Promise.allSettled
- Ensures webhooks are sent before delegation errors are thrown
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* fix: address PR feedback - add migration, remove 'as any', remove user.name
- Add Prisma migration for DELEGATION_CREDENTIAL_ERROR enum
- Replace 'as any' type casting with safe type-narrowing helper in CalendarAuth.ts
- Remove user.name field from DelegationCredentialErrorPayloadType (email is sufficient)
- Ensure all type definitions are consistent across sendPayload.ts and dto/types.ts
Addresses feedback from alishaz-polymath and morgan@cal.com
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* chore: cleanup type in CalendarAuth
* fix: missing DELEGATION_CREDENTIAL_ERROR in WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP constant
* fix: review
* fit: import webhook dto
* fit: type error
* feat: add delegation credential error webhook handling to Office365 video adapter
- Emit webhook before throwing delegation credential errors in Office365 video
- Added webhook emission in 4 locations:
1. Missing clientId/Secret in fetchNewTokenObject
2. Missing tenantId in getAuthUrl
3. Missing clientId/Secret in getAzureUserId
4. User doesn't exist in Azure AD
- Made getAuthUrl async to support webhook emission
- Follows same pattern as GoogleCalendar and Office365Calendar implementations
Co-Authored-By: morgan@cal.com <morgan@cal.com>
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* fixup! Merge branch 'devin/delegation-credential-errors-webhook-1762171203' of https://git-manager.devin.ai/proxy/github.com/calcom/cal.com into devin/delegation-credential-errors-webhook-1762171203
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: cal.com <morgan@cal.com>
* refactor: create team event type hosts
* refactor: update team event type hosts
* feat: allow switching between collective and round robin
* fix: make schedulingType optional when updating
* fix: e2e tests
* fix: e2e and add more tests
* test: only hosts update
* fix: remove test that makes no sense
* fix: update profile me ednpoint to include name of user
* fix: update user schema
* pass name for user
* implement PR feedback
* chore: implement PR feedback
---------
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-11-10 19:14:44 +00:00
Anik Dhabal BabuGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix: resolve flaky org-admin integration tests
- Fixed isAdminGuard Prisma query to use explicit 'is' filter for organizationSettings
- Fixed async describe with top-level awaits in _get.integration-test.ts
- Added global setup in setupVitest.ts to prevent race conditions
- Removed duplicate setup logic from individual test files
Root cause: Tests were running in parallel with independent beforeAll setups,
causing race conditions where organizationSettings weren't created before
tests executed. The async describe with top-level awaits made this worse by
executing queries before beforeAll hooks ran.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* fix: move org-admin setup to integration-only setup file
The global setup in setupVitest.ts was running for ALL test workspaces
(including unit tests), causing ECONNREFUSED errors because unit tests
don't have database access.
Changes:
- Created setupVitest.integration.ts with org-admin seeding logic
- Removed database seeding from setupVitest.ts
- Updated vitest.workspace.ts to use integration-only setup file
- Added DATABASE_URL guard to prevent errors when DB is unavailable
This fixes the unit test failures while preserving the fix for flaky
integration tests.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* fix: use globalSetup instead of setupFiles for org-admin seeding
The previous fix using setupFiles didn't work because setupFiles run
AFTER test modules are evaluated. This meant any top-level Prisma
queries in test files would execute before the org-admin seeding.
Changes:
- Moved org-admin seeding to tests/integration/global-setup.ts
- Updated vitest.workspace.ts to use globalSetup for IntegrationTests
- globalSetup runs BEFORE any test modules are loaded, ensuring org
settings exist before tests execute
- Added teardown function to properly disconnect Prisma after tests
This ensures org-admin state is seeded once before all integration
tests run, eliminating the race condition and ensuring tests have
the correct database state.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* debug: add logging to globalSetup to diagnose why tests are failing
Added console.log statements throughout the globalSetup to verify:
- Whether the globalSetup is running at all
- Whether DATABASE_URL is available
- Whether the org teams are found in the database
- Whether the upserts are executing successfully
This will help diagnose why the integration tests are still failing
with org-admin not being detected.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* fix: use absolute path for globalSetup in vitest.workspace.ts
Changed from relative path 'tests/integration/global-setup.ts' to
absolute path using new URL().pathname to ensure Vitest can properly
locate and load the globalSetup file.
This should fix the issue where the globalSetup wasn't being executed
at all (no logs appearing in CI).
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* fix: add serial execution to IntegrationTests workspace
Added sequence.concurrent: false to IntegrationTests workspace to eliminate
inter-file race conditions while stabilizing org-admin seeding. This ensures
tests run one at a time, preventing parallel execution issues that could
cause flaky test failures.
This is a temporary stabilizer that can be reverted once the globalSetup
seeding is confirmed working.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* refactor: use TeamRepository in globalSetup to follow architectural rule
Refactored globalSetup to use TeamRepository instead of direct Prisma
access, following the 'No prisma outside of repositories' architectural
rule.
Changes:
- Created TeamRepository class with methods for finding organizations
and upserting organization settings
- Updated globalSetup to use TeamRepository.withGlobalPrisma()
- Removed direct Prisma imports from globalSetup
This ensures proper separation of concerns and follows the repository
pattern established in the codebase.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* fix: use relative path import for TeamRepository in globalSetup
Changed from package-scoped import '@calcom/lib/server/repository/team'
to relative path import '../../packages/lib/server/repository/team' to
fix module resolution issue.
Added try/catch with logging around the import to surface any remaining
resolution issues in CI logs. This should allow the globalSetup to
execute properly and seed org-admin state before tests run.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* debug: add membership logging to globalSetup to diagnose test failures
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* fix: ensure owner1-acme membership exists in globalSetup
Root cause: CI database snapshot doesn't include the owner1-acme OWNER membership that exists in the current seed file, because cache-db action's cache key doesn't include scripts/seed.ts.
Solution: Add ensureMembership method to TeamRepository and call it in globalSetup to ensure the owner1-acme user has an accepted OWNER membership in the Acme org before tests run.
This fixes the 5 failing org-admin integration tests that depend on this membership.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* fix: ensure all 10 member{0-9}-acme users exist in globalSetup
Add ensureUser method to TeamRepository to create users if they don't exist.
Update ensureMembership to accept MEMBER role in addition to OWNER and ADMIN.
Ensure all 10 member{0-9}-acme users are created with MEMBER role and accepted: true in the Acme org.
This should fix the remaining 4 failing tests that expect multiple org members to exist.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* fix: use upsert instead of create in ensureUser to avoid unique constraint violations
The ensureUser method was using create which could fail if a user with that email already exists.
Switch to upsert to make the operation idempotent and avoid P2002 unique constraint errors.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* refactor: clean up debug code and move test repository to proper location
- Remove all console.log debug statements from global-setup.ts
- Remove serial execution from IntegrationTests workspace (restore parallel execution)
- Move TeamRepository to tests/lib/test-team-repository.ts and rename to TestTeamRepository
- Keep all actual fixes: isAdmin Prisma query fix, ensureUser/ensureMembership methods, globalSetup seeding
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* 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>
* feat: Pbac decorator and guard
* feat: v2 roles endpoints
* fix: test
* fix: starting v2
* fix: test error
* fix: test api keys
* fix fixture
* test permission creation
* feat: permissions endpoints
* refactors
* refactor: project structure
* test: role permissions crud
* test: permissions endpoint negative tests
* docs: org, team permissions swagger
* unit tests for validator
* Update roles.guard.ts
* fix type
* test: error messages
* refactor: dont throw error in pbac
* delete redundant test file
* feedback: logging error
* fix: persist role.permissions when updating role.otherProperty
* refactor: use output service to return permissions
* refactor: service functions return current permissions
* refactor: remove OrganizationsRepository from providers
* refactor: try catch possibly duplicate create
* refactor: require min length name if provided
* refactor: org role has orgId and team role teamId
* fix: pbac guard caching
* fix: e2e tests in parallel
* refactor: use IsTeamInOrg guard for orgs teams roles and permissions endpoints
* refactor: use redis service getter and setter
* refactor: invalidate team permissions cache when permissions change
* refactor: delete keys instead of versioning when caching
- Remove cal.cache query parameter parsing from booking and slots flows
- Set shouldServeCache to false for all booking availability checks
- Remove _shouldServeCache from schemas and type definitions
- Clean up all references in platform atoms and API endpoints
This ensures fresh Google Calendar data is always fetched for conflict checking,
preventing bookings when there are actual calendar conflicts.
2025-11-05 13:01:22 +00:00
MorganGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* feat: skip authentication check for reschedule bookings with validation
- Skip checkBookingRequiresAuthentication when rescheduleUid is present
- Add validation to ensure rescheduleUid points to a real booking
- Verify booking status is ACCEPTED (upcoming)
- Verify booking uses the same event-type
- Throw appropriate errors for invalid reschedule attempts
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* refactor: move reschedule validation logic into checkBookingRequiresAuthentication
- Refactor checkBookingRequiresAuthentication to accept optional rescheduleUid parameter
- Move reschedule booking validation logic inside the method
- Simplify createBooking method by removing duplicate validation code
- Maintain same validation logic: check booking exists, is ACCEPTED, and uses same event-type
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: allow PENDING bookings to be rescheduled
- Update status validation to allow both ACCEPTED and PENDING bookings
- Change error message to reflect both allowed statuses
- PENDING bookings can now be rescheduled without authentication check
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* refactor: separate reschedule validation from auth check
- Extract validateRescheduleBooking method to handle reschedule-specific validation
- Keep checkBookingRequiresAuthentication strictly for auth checks
- Use conditional logic in createBooking: validate reschedule OR check auth
- Improves code clarity by separating concerns per lauris's feedback
Co-Authored-By: morgan@cal.com <morgan@cal.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* refactor: move org admin related logic to org server
* fix: update cancellation logic to make sure org admin can cancel seated bookings of a team user
* fix: import path
* update bookings repository
* fix: update reschedule endpoint logic to let org admin reschedule bookings for a user
* refactor: make logic more simple
* chore: update platform libraries
* more refactors
* fix: add check to make sure org admin can reschedule booking
* chore: remove unused comments
* test: add e2e tests for org admin reschedule and cancel seated bookings
- Add seated event type creation for testing
- Add test for org admin rescheduling a seated booking for a managed user
- Add test for org admin canceling a full seated booking for a managed user
- Add test for org admin canceling a specific seat in a seated booking
These tests verify the functionality added in PR #24640 which allows
org admins to reschedule and cancel seated bookings for users in their
organization.
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
* chore: add cubic feedback
* fix: tests for seated booking management by org admin
* chore: implement PR feedback
* fixup
* chore: update docs
* fixup: get optional user from request and then pass it down to getBookingForReschedule
* fix: validate seatUid before checking booking cancellation status
Move canRescheduleBooking call to happen after input validation
(including seatUid validation for seated bookings) but before the
actual booking creation. This ensures that when trying to reschedule
a seated booking without providing seatUid, users get the proper
'seatUid required' error instead of 'booking has been cancelled' error.
Fixes failing e2e test: 'should not be able to reschedule seated
booking if seatUid is not provided'
Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix: Modified teamName to be null when host is not fixed
* feat: Added test cases for round robin bookings reassignment with fixed and non-fixed hosts
* feat: improve team name handling in round robin reassignment
* refactor: improve booking title validation in reassignment tests
* feat: add bookingRequiresAuthentication validation to 2024-04-15 booking controller
- Add checkBookingRequiresAuthentication method to validate authentication requirements
- Check if user is event type owner, host, team admin/owner, or org admin/owner
- Add comprehensive e2e tests for bookingRequiresAuthentication feature
- Ensure parity with 2024-08-13 controller implementation
- Fix type issue in setPlatformAttendeesEmails method
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* refactor: move Prisma calls to repository pattern
- Add findByIdIncludeHostsAndTeamMembers method to EventTypeRepository
- Inject PrismaEventTypeRepository and PrismaTeamRepository into controller
- Replace direct Prisma calls with repository methods in checkBookingRequiresAuthentication
- Use getTeamByIdIfUserIsAdmin for org admin/owner check
- Add repositories to BookingsModule_2024_04_15 providers
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* handle httpException in handleBookingErrors
* test: add test case for authenticated but unauthorized user booking
- Create second user who is not authorized to book the event type
- Verify that authenticated user without proper permissions receives 403 Forbidden
- Test validates that bookingRequiresAuthentication properly checks authorization levels
- Cleanup unauthorized user in afterAll hook
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: add accepted filter to team members and handle org-owned event types
Addresses PR comments from cubic-dev-ai and @ThyMinimalDev:
1. Add accepted: true filter to team.members query
- Prevents pending team invitations from being treated as authorized
- Also filter by role to only fetch ADMIN and OWNER roles
- Reduces payload size and improves query performance
2. Add isOrganization field to team select
- Enables proper handling of org-owned event types
3. Update authorization logic for org-owned event types
- Handle case where team.isOrganization is true with no parent
- Ensure org admins/owners are properly authorized for org-owned events
- Matches behavior of 2024-08-13 controller
Changes:
- packages/features/eventtypes/repositories/eventTypeRepository.ts:
* Add where clause to members query with accepted: true and role filter
* Add isOrganization: true to team select
- apps/api/v2/src/ee/bookings/2024-04-15/controllers/bookings.controller.ts:
* Update authorization logic to handle org-owned event types
* Check if team.isOrganization is true when no parentId exists
Co-Authored-By: morgan@cal.com <morgan@cal.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* feat: add seed-all command to run all seed scripts
- Add seed-all command to packages/prisma/package.json
- Create scripts/seed-all.ts to run seed.ts, seed-insights.ts, and seed-pbac-organization.ts in sequence
- Update Prisma configuration to use seed-all as the default seed command
- Add GitHub workflow to test seed-all command with a real PostgreSQL database
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* fix: use correct path resolution in seed-all script
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* fix: simplify database verification step in test workflow
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* refactor: use seed-all in cache-db action instead of separate workflow
- Update cache-db action to use seed-all command
- Remove test-seed-all.yml workflow as requested
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* fix error
* change command name
* fix integration tests
* run basic seed by default
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2025-10-28 10:56:52 +00:00
chauhan_sGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>Morgan
* feat: add endpoint to add attendees to existing bookings
- Created POST /v2/bookings/:bookingUid/attendees endpoint
- Added AddAttendeesInput_2024_08_13 for input validation
- Added AddAttendeesOutput_2024_08_13 for response format
- Created BookingAttendeesService_2024_08_13 for business logic
- Created BookingAttendeesController_2024_08_13 for API endpoint
- Added validation to check for duplicate attendee emails
- Integrated with existing booking and event type repositories
- Added validateAndTransformAddAttendeesInput method to InputBookingsService
- Fixed pre-existing ESLint no-prototype-builtins warnings
- Left placeholder for custom booking field validation logic
Co-Authored-By: somay@cal.com <somaychauhan98@gmail.com>
* refactor: move booking attendee operations to dedicated repository
* refactor: move repository files into dedicated repositories directory
* feat: validate guests field availability before adding attendees to booking
* feat: migrate addAttendees API to use existing addGuests handler
* refactor: remove unused validateAndTransformAddAttendeesInput method from InputBookingsService
* refactor: rename attendees to guests in booking API endpoints and types
* refactor: rename booking-attendees to booking-guests for consistency
* WIP: add e2e tests for add booking guests endpoint
* faet: improve guest booking tests
* refactor: extract getHtml method in email templates
* feat: add email toggle support for guest invites based on OAuth client settings
* refactor: addGuests handler
* feat: add SMS notifications when adding guests to existing bookings
* refactor: rename add-attendees to add-guests for consistent terminology
* refactor: added repository pattern in addGuests.handler
* test: add attendee scheduled email spy to booking guests tests
* fix: use event type team ID instead of user org ID for booking permission check
* Update BookingEmailSmsHandler.ts
* Remove comments
* refactor: rename booking guests to booking attendees
* refactor: rename guest-related methods to use attendees terminology for consistency
* update api docs
* refactor: restructure addGuests handler to top
* refactor: update guest email format to use object structure in booking tests
* docs: clarify API version header requirement for booking attendees endpoint
* docs: add email notification details to booking attendees API documentation
* refactor: rename booking attendees to guests for consistency
* refactor: rename attendees to guests in booking API endpoints
* feat: add email validation for guest invites
* feat: improve error handling for guest booking failures
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
The flaky test failures were caused by the tests depending on the database being properly seeded with the isAdminAPIEnabled flag set to true for the Acme organization. The tests would fail randomly when the database wasn't properly seeded or when the organization settings weren't configured correctly.
This fix adds beforeAll hooks to the failing integration tests to ensure that:
1. The Acme organization has isAdminAPIEnabled set to true
2. The Dunder Mifflin organization has isAdminAPIEnabled set to false
This ensures consistent test behavior regardless of the database state and prevents the flaky failures.
Fixes the following failing tests:
- isAdmin.integration-test.ts: Returns org-wide admin when user is set as such & admin API access is granted
- retrieveScopedAccessibleUsers.integration-test.ts: Returns members when admin user ID is supplied and members IDs are supplied
- retrieveScopedAccessibleUsers.integration-test.ts: Returns members when admin user ID is an admin of an org
- _get.integration-test.ts: Returns bookings for org users when accessed by org admin
- _patch.integration-test.ts: Allows PATCH when user is org-wide admin
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>