* feat(booking-audit): extract core audit system changes from PR 25125
This PR extracts core audit infrastructure changes without integration changes:
1. New action services introduced:
- SeatBookedAuditActionService
- SeatRescheduledAuditActionService
2. Simplification of ActionService interface:
- Streamlined IAuditActionService interface
- Reduced TypeScript burden with cleaner type definitions
3. ActionSource support:
- Added BookingAuditSource enum (API_V1, API_V2, WEBAPP, WEBHOOK, UNKNOWN)
- Added source and operationId fields to BookingAudit model
4. New AuditAction types:
- SEAT_BOOKED
- SEAT_RESCHEDULED
- APP actor type
5. New BookingAuditAccessService:
- Permission-based access control for audit logs
- Added readTeamAuditLogs and readOrgAuditLogs permissions
6. Fixes in the logs viewer flow:
- Enhanced BookingAuditViewerService with improved filtering
- Local AttendeeRepository for actor enrichment
Changes are contained within packages/features/booking-audit with minimal
outside changes (permission registry only).
Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>
* refactor(booking-audit): streamline action handling and enhance localization
- Replaced action icon retrieval with a mapping object for improved clarity and performance.
- Introduced constants for actor role labels to simplify role retrieval.
- Added new localization strings for audit log permission errors and organization requirements.
- Updated various service and repository interfaces to enhance type safety and clarity.
- Removed deprecated architecture documentation and adjusted related imports for consistency.
These changes aim to improve code maintainability and user experience in the booking audit system.
* fix(booking-audit): enhance actor role localization and operation ID tracking
- Updated actor role labels in the booking logs view to use lowercase for consistency.
- Improved localization by wrapping actor role display in a translation function.
- Added operationId field to audit logs for better correlation of actions across multiple bookings.
- Enhanced BookingAuditViewerService to include operationId in enriched audit logs.
- Updated integration tests to verify consistent operationId across related audit logs.
These changes aim to improve localization accuracy and facilitate better tracking of user actions in the booking audit system.
* feat: integrate credential repository and enhance app actor handling
- Added CredentialRepository to manage app credentials, including a method to find credentials by ID.
- Updated BookingAudit system to support app actors identified by credential ID, improving actor attribution and audit clarity.
- Introduced a new utility function to map app slugs to display names, enhancing the user experience in audit logs.
- Modified relevant interfaces and types to accommodate the new credential handling and app actor structure.
- Enhanced BookingAuditViewerService to display app names based on credentials, ensuring accurate representation in audit logs.
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-18 12:46:24 +00:00
Eunjae LeeGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* feat: add enabled column to UserFeatures and TeamFeatures for tri-state semantics
- Add enabled Boolean column to UserFeatures model with default true
- Add enabled Boolean column to TeamFeatures model with default true
- Update FeaturesRepository to use tri-state semantics:
- enabled=true: feature is explicitly enabled
- enabled=false: feature is explicitly disabled (blocks inheritance)
- No row: inherit from team/org level
- Update SQL queries to check enabled=true for feature access
- Add enableFeatureForTeam method to interface and implementation
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* update comments
* add integration tests
* add more test
* select enabled only
* no @default(true)
* fix types and tests
* add missing enabled
* add missing enabled
* rename enableFeatureForTeam to updateFeatureForTeam and support FeatureState
* refactor: rename updateFeatureForTeam to setTeamFeatureState
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* fix integration test
* fix tests
* add more tests
* add missing enabled
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* add webhook version schema
* version the code
* update version from numeric to date val
* migration
* update schema and build factory
* update string
* move version picker
* tooltip instead of infobadge
* --
* fix type
* --
* fix type
* fix type
* --
* fix messed up merge
* improvements to payloadfactory
* extract version off of DB and instead keep it in IWebhookRepository
* fix webhookform
* fix type safety and routing ambiguity
* scalable with easier factory extensions and base definition
* fix types
* --
* --
* clean up prisma/client type imports
* fix
* type fix
* type fix
* cleanup
* add tests and registry changes
* unintended file inclusion
* type-fix
* select in repo
* --
* explicit return type
* --
* fix type
* fixes
* feedback 1
* feedback 2
* use enum instead of string
* fixes
* refactor: migrate workflows utilities from trpc to features layer
Move workflow utility functions from packages/trpc/server/routers/viewer/workflows/util.ts
to packages/features/ee/workflows/lib/workflowUtils.ts to break circular dependencies.
Functions migrated:
- isAuthorized
- getAllWorkflowsFromEventType
- scheduleWorkflowNotifications
- scheduleBookingReminders
Changes:
- Created new workflowUtils.ts in features layer with migrated functions
- Added getBookingsForWorkflowReminders to WorkflowRepository (no prisma outside repositories)
- Updated all imports in features layer to use new location
- Updated trpc util.ts to re-export from features for backward compatibility
- Fixed pre-existing lint warning (any -> unknown) in handleMarkNoShow.ts
This is part of the effort to remove circular dependencies between
packages/features and packages/trpc.
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* refactor: remove re-exports from trpc util.ts, update imports to use features layer
Per user request, removed the backward compatibility re-exports from
packages/trpc/server/routers/viewer/workflows/util.ts and updated all
imports in the trpc package to import directly from the features layer.
Files updated to import from @calcom/features/ee/workflows/lib/workflowUtils:
- confirm.handler.ts (getAllWorkflowsFromEventType)
- delete.handler.ts (isAuthorized)
- update.handler.ts (isAuthorized, scheduleWorkflowNotifications)
- getAllActiveWorkflows.handler.ts (getAllWorkflowsFromEventType)
- get.handler.ts (isAuthorized)
- util.test.ts (isAuthorized)
- delete.handler.test.ts (isAuthorized)
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: update test imports to use features layer for workflow utilities
Updated test files to import scheduleBookingReminders and
scheduleWorkflowNotifications from @calcom/features/ee/workflows/lib/workflowUtils
instead of @calcom/trpc/server/routers/viewer/workflows/util.
Files updated:
- packages/features/ee/workflows/lib/test/workflows.test.ts
- packages/features/tasker/tasks/scanWorkflowBody.test.ts
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* refactor: split workflowUtils.ts into individual files
Split the monolithic workflowUtils.ts into separate files for each function:
- isAuthorized.ts - Authorization check for workflow access
- getAllWorkflowsFromEventType.ts - Get workflows for an event type
- scheduleWorkflowNotifications.ts - Schedule workflow notifications
- scheduleBookingReminders.ts - Schedule booking reminders
The workflowUtils.ts now re-exports from these individual files for
backward compatibility.
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix import
* fix more
* wip
* wip
* remove workflowUtils
* wip
* refactor deleteRemindersOfActiveOnIds
* fix
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* 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
* 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>
* feat: add hostSubsetIds parameter for round robin host filtering
Add support for filtering round robin event type hosts via API v2.
When hostSubsetIds is provided, only the specified hosts are considered
for availability calculation and booking assignment.
Changes:
- Add hostSubsetIds to slots API input (GET /slots/available)
- Add hostSubsetIds to booking API input (POST /bookings)
- Update _findQualifiedHostsWithDelegationCredentials to filter by hostSubsetIds
- Pass hostSubsetIds through all layers: API -> tRPC -> slots/booking services
This allows API consumers to request availability and create bookings
for a subset of hosts within a round robin event type.
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* chore: add e2e tests
* chore: add enableHostSubset team event-type setting
* fixup! chore: add enableHostSubset team event-type setting
* fix tests
* fix tests
* improve isWithinRRHostSubset
* rename to rrHost subset
* fix ai review
* fix: add booker platform wrapper rrHostSubsetIds prop
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-10 10:37:39 +00:00
MorganGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix: preserve metadata fields during partial event type updates
- Fix multipleDuration (lengthInMinutesOptions) being reset to undefined on partial updates
- Fix bookerLayouts being reset to undefined on partial updates
- Fix requiresConfirmationThreshold being reset to undefined on partial updates
- Add e2e test for lengthInMinutesOptions preservation
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* test: expand metadata preservation test to include bookerLayouts and confirmationPolicy
Co-Authored-By: morgan@cal.com <morgan@cal.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
## What does this PR do?
This PR adds user UUID plumbing from API v2 controllers through to packages/features functions. This is preparatory work extracted from PR #25125 to support future audit logging functionality.
**Key changes:**
- API v2 controllers (2024-04-15, 2024-08-13) now extract and pass `userUuid` to downstream functions
- `handleMarkNoShow` and `CancelBookingInput` types now accept optional `userUuid` parameter
- `UserRepository.findUnlockedUserForSession` now selects `uuid` field
- Session middleware now includes `uuid` in the returned user object
- Fixed lint warning: changed `PromiseSettledResult<any>` to `PromiseSettledResult<unknown>`
**Refactoring (optimization):**
- Renamed `getOwnerId` → `getOwner` and `getOwnerIdRescheduledBooking` → `getOwnerRescheduledBooking`
- These methods now return `{ id: number; uuid: string } | null` instead of just `number | undefined`
- This eliminates redundant database calls by fetching user id and uuid in a single query
**Important:** This is plumbing-only - packages/features receives the `userUuid` but does not use it directly (note the `_userUuid` prefix). The actual audit logging usage will come in a follow-up PR.
Requested by: @hariombalhara (hariom@cal.com)
Link to Devin run: https://app.devin.ai/sessions/545209189f6347cd807bf1b336f9ac40
## Mandatory Tasks (DO NOT REMOVE)
- [x] I have self-reviewed the code (A decent size PR without self-review might be rejected).
- [x] I have updated the developer docs in /docs if this PR makes changes that would require a [documentation change](https://cal.com/docs). N/A - no documentation changes needed.
- [x] I confirm automated tests are in place that prove my fix is effective or that my feature works. N/A - plumbing only, existing tests cover the functionality.
## How should this be tested?
1. Run type checks: `yarn type-check:ci --force`
2. Verify the changes compile without new type errors related to uuid
3. The `userUuid` parameters are optional, so existing functionality should work unchanged
## Checklist
- [x] My code follows the style guidelines of this project
- [x] I have checked if my changes generate no new warnings
## Human Review Checklist
- [ ] Verify the `userUuid` parameter is intentionally unused (prefixed with `_userUuid`) - this is plumbing for future audit logging
- [ ] Verify all callers of `getOwner` and `getOwnerRescheduledBooking` correctly handle the new `{ id, uuid } | null` return type
- [ ] Confirm the change from `undefined` to `null` as the "not found" return value is handled consistently
- [ ] Verify the `uuid` field exists in the User model schema
## 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) -->
* feat(api): PATCH Event Type V2 API to support all current locations
* docs(api): update locations documentation and add E2E tests for new integrations
- Updated locations property documentation in create-event-type.input.ts
and update-event-type.input.ts to clarify app installation requirements
- Explained that only Google Meet, MS Teams, and Zoom can be installed via API
- Noted that Cal Video is installed by default
- Added E2E tests for creating and updating event types with newly supported
integration locations (jitsi, zoom, google-meet, whereby, huddle, element-call)
- Regenerated openapi.json with updated API documentation
Addresses feedback from Lauris regarding platform API location support.
* fix(api): use supportedIntegrations list for app validation
Updated checkAppIsValidAndConnected to use the full supportedIntegrations
list from locations.input.ts instead of hardcoded array. This allows all
27 supported conferencing apps to be set as event type locations via API,
as long as they are already connected by the user.
* fix(api): add slug mapping for all conferencing integrations
Added comprehensive slug mapping to translate API integration names
(e.g., 'facetime-video', 'whereby-video') to actual app slugs
(e.g., 'facetime', 'whereby'). This ensures the app lookup works
correctly for all 27 supported conferencing integrations.
Addresses AI bot feedback about slug mismatches.
* fix(api): add missing huddle to huddle01 slug mapping
Added mapping for huddle -> huddle01. Other apps like tandem, jitsi,
cal-video, google-meet, and zoom don't need mapping as their API names
already match their app slugs (handled by the fallback || appSlug).
* update key
* update ket
* test(api): update E2E tests to validate newly supported integrations
Replaced end-to-end tests with validation-focused tests that follow
the existing pattern. The new test creates event types with various
newly supported integrations (jitsi, whereby-video, huddle, tandem,
element-call-video) directly in the database (bypassing app connection
checks) and verifies the API correctly returns them.
This approach tests that the input validation accepts all 27 supported
integration types without requiring actual app installations in the
test environment.
* fix(api): correct slug mappings for whatsapp, shimmer, and jelly integrations
- Fixed whatsapp-video mapping from 'whatsappvideo' to 'whatsapp'
- Fixed shimmer-video mapping from 'shimmer' to 'shimmervideo'
- Fixed jelly-conferencing mapping from 'jelly-conferencing' to 'jelly'
All slug mappings now correctly match the actual app slugs in
packages/app-store/*/config.json files. This ensures proper app
validation when users create/update event types with these locations.
Addresses feedback from @pedroccastro
* updated openapi.json file because of main branch code
* test(api): add negative test for unsupported integration locations
- Added E2E test to validate 400 error when creating event type with unsupported integration
- Test verifies exact error message listing all supported integrations
- Uses imported supportedIntegrations constant for maintainability
- Follows same pattern as booking fields validation tests
Addresses feedback from @supalarry
* test(api): add negative test for patching event type with unconnected integration
- Added E2E test to validate 400 error when user tries to PATCH event type with jitsi integration they haven't connected
- Test verifies exact error message 'jitsi not connected.'
- Follows existing test patterns with proper cleanup
* 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>