Compare commits
167
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3630399ee | ||
|
|
5375c656af | ||
|
|
1792d49634 | ||
|
|
de98578fdd | ||
|
|
c0a59a2837 | ||
|
|
29201006d5 | ||
|
|
7a1c780088 | ||
|
|
550f34c128 | ||
|
|
d6b17b76db | ||
|
|
c42e803cfa | ||
|
|
0233c3a11a | ||
|
|
71a2b6956f | ||
|
|
8282557ebe | ||
|
|
083a162d0e | ||
|
|
60487ea02e | ||
|
|
60a8841439 | ||
|
|
184d1eb751 | ||
|
|
9fea30a44d | ||
|
|
04efcbcdb6 | ||
|
|
2b29b5607d | ||
|
|
20f19c2509 | ||
|
|
5d0e66763e | ||
|
|
bcfbc24e93 | ||
|
|
37d805b007 | ||
|
|
6a246e6c57 | ||
|
|
3a0229f60d | ||
|
|
0bf95ec568 | ||
|
|
6f05142447 | ||
|
|
e02108d535 | ||
|
|
b7e668217d | ||
|
|
472ffef5cf | ||
|
|
5acdb208f5 | ||
|
|
7bf5d9cf64 | ||
|
|
34a80180ef | ||
|
|
3bbba9c6cb | ||
|
|
b052c2e029 | ||
|
|
4eb884e2a6 | ||
|
|
3f8ce8ff50 | ||
|
|
67a2371c05 | ||
|
|
80250d32bd | ||
|
|
0fadbe1ce9 | ||
|
|
9c3ee262b4 | ||
|
|
b62eba8128 | ||
|
|
ef114d7727 | ||
|
|
be7d127c9e | ||
|
|
1209150785 | ||
|
|
31940b919e | ||
|
|
c3c990db43 | ||
|
|
84a742336c | ||
|
|
ada8ffd3b9 | ||
|
|
2277d90326 | ||
|
|
cbc27a78ee | ||
|
|
a2189643bd | ||
|
|
a6101b3da9 | ||
|
|
216fb2141b | ||
|
|
afb54ca048 | ||
|
|
f4b23b3a03 | ||
|
|
d6cd593b95 | ||
|
|
2d9c1b3fd9 | ||
|
|
f2f10a06d9 | ||
|
|
e1def884f3 | ||
|
|
fd61c00ad1 | ||
|
|
d8f422f98d | ||
|
|
7f200df1ac | ||
|
|
9b38ed65c0 | ||
|
|
25c20e5093 | ||
|
|
ec8a441649 | ||
|
|
04a91dc71a | ||
|
|
2023926a3a | ||
|
|
75465ac4bf | ||
|
|
2dbd0b3832 | ||
|
|
3b7d97b194 | ||
|
|
a1fab0e744 | ||
|
|
87331f0a3a | ||
|
|
6cd4f1fcaa | ||
|
|
6b84dc09a7 | ||
|
|
d125064430 | ||
|
|
39490b6883 | ||
|
|
e45f9c5a13 | ||
|
|
9ceb5ea3c5 | ||
|
|
16bd52148e | ||
|
|
9a2705c84c | ||
|
|
6c069a4afe | ||
|
|
42cbc46609 | ||
|
|
096026b92a | ||
|
|
060eafac60 | ||
|
|
f6f36750ec | ||
|
|
2e9aa01771 | ||
|
|
40d70cd1d4 | ||
|
|
17ef0dc12b | ||
|
|
e530ad5412 | ||
|
|
882eb85a33 | ||
|
|
6b0726bcde | ||
|
|
712467a7f4 | ||
|
|
0a9e732ea4 | ||
|
|
b101157d67 | ||
|
|
f859c289aa | ||
|
|
1009d2b4bc | ||
|
|
1739114490 | ||
|
|
9724bc07a6 | ||
|
|
24ff3622fd | ||
|
|
f1d1674693 | ||
|
|
c87a88b244 | ||
|
|
8bdcf4ec3b | ||
|
|
5f0188b036 | ||
|
|
bf3037d57e | ||
|
|
5ebd33576a | ||
|
|
4fb3639f71 | ||
|
|
d44a41c587 | ||
|
|
4960c4b97c | ||
|
|
5c51b0632f | ||
|
|
73b0693632 | ||
|
|
0bcb81bedd | ||
|
|
bfa23ddb80 | ||
|
|
28f473da14 | ||
|
|
1fd1202373 | ||
|
|
8845e736e5 | ||
|
|
dd16c2b99d | ||
|
|
e7779bba0a | ||
|
|
701c834115 | ||
|
|
18423e5805 | ||
|
|
b332d9897d | ||
|
|
191db5104a | ||
|
|
bfacd8a780 | ||
|
|
d4bff9d6b1 | ||
|
|
6defa1cd7d | ||
|
|
5b2b5fd967 | ||
|
|
6932498d48 | ||
|
|
e07f800417 | ||
|
|
464e5f1496 | ||
|
|
724e3f2755 | ||
|
|
59c76141ce | ||
|
|
a494428334 | ||
|
|
7145a2d640 | ||
|
|
baaa04151d | ||
|
|
381125becd | ||
|
|
091327afee | ||
|
|
f1d7d7f02a | ||
|
|
84bd4d3d38 | ||
|
|
0367cf8e41 | ||
|
|
afea724e4d | ||
|
|
a4915184cd | ||
|
|
b7a7797293 | ||
|
|
d0e59f1824 | ||
|
|
67befea66e | ||
|
|
f18ebc4d67 | ||
|
|
5324832f13 | ||
|
|
2d9162a4dd | ||
|
|
d9443162ef | ||
|
|
e8dbab99eb | ||
|
|
cdcc04c8ff | ||
|
|
740a1c991e | ||
|
|
70cfe8d693 | ||
|
|
520e711ca6 | ||
|
|
6d1fe32a39 | ||
|
|
1cc548284d | ||
|
|
d49843de0b | ||
|
|
42efd95476 | ||
|
|
2ec68ef1aa | ||
|
|
6e09489685 | ||
|
|
af07c411ee | ||
|
|
a22ca4758c | ||
|
|
bb3ba88f18 | ||
|
|
ce646c590f | ||
|
|
ba8cca55e8 | ||
|
|
ae738fae35 | ||
|
|
2922c8fe77 |
@@ -0,0 +1,82 @@
|
||||
# Cal.com Development Guide for AI Agents
|
||||
|
||||
This directory contains comprehensive documentation for AI agents working on the Cal.com codebase.
|
||||
|
||||
## Quick Navigation
|
||||
|
||||
- **[Commands](commands.md)** - Build, test, and development commands
|
||||
- **[Knowledge Base](knowledge-base.md)** - Knowledge base & best practices
|
||||
- **[Architecture Overview](#architecture-overview)** - System structure and patterns
|
||||
|
||||
## Getting Started
|
||||
|
||||
Cal.com is a monorepo using Yarn workspaces and Turbo for build orchestration. The main application is in `apps/web/` with shared packages in `packages/`.
|
||||
|
||||
### Key Directories
|
||||
|
||||
- `apps/web/` - Main Next.js application
|
||||
- `packages/prisma/` - Database schema and migrations
|
||||
- `packages/trpc/` - API layer using tRPC
|
||||
- `packages/ui/` - Shared UI components
|
||||
- `packages/features/` - Feature-specific code
|
||||
- `packages/app-store/` - Third-party app integrations
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
### Database Layer
|
||||
|
||||
- **Prisma ORM** with PostgreSQL
|
||||
- Schema in `packages/prisma/schema.prisma`
|
||||
- Always use `select` instead of `include` for better performance
|
||||
- Never expose `credential.key` field in API responses
|
||||
|
||||
### API Layer
|
||||
|
||||
- **tRPC** for type-safe APIs
|
||||
- Routers in `packages/trpc/server/routers/`
|
||||
- Authentication handled via NextAuth.js
|
||||
|
||||
### Frontend
|
||||
|
||||
- **Next.js 13+** with App Router in some areas
|
||||
- **React 18** with TypeScript
|
||||
- **Tailwind CSS** for styling
|
||||
- Internationalization with `next-i18next`
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Error Handling
|
||||
|
||||
- Use early returns to reduce nesting
|
||||
- Throw descriptive errors with proper error codes
|
||||
- Prefer composition over prop drilling
|
||||
|
||||
### Performance
|
||||
|
||||
- Avoid O(n²) logic in backend code
|
||||
- Minimize Day.js usage in performance-critical paths
|
||||
- Use `select` queries to only fetch needed data
|
||||
- Consider using `.utc()` for Day.js operations
|
||||
|
||||
### Security
|
||||
|
||||
- Never commit secrets or API keys
|
||||
- Always validate input data
|
||||
- Use proper authentication checks
|
||||
- Never expose sensitive credential fields
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests** with Vitest
|
||||
- **Integration tests** for complex workflows
|
||||
- **E2E tests** with Playwright
|
||||
- Test files use `.test.ts` or `.spec.ts` extensions
|
||||
|
||||
## Pull Request Guidelines
|
||||
|
||||
For large PRs (>500 lines or >10 files):
|
||||
|
||||
- Split by feature boundaries
|
||||
- Separate database migrations, backend logic, frontend components
|
||||
- Create dependency chains that can be merged sequentially
|
||||
- Pattern: Database → Backend → Frontend → Tests
|
||||
@@ -0,0 +1,56 @@
|
||||
# Coding Standards & Best Practices
|
||||
|
||||
|
||||
|
||||
## Import Guidelines
|
||||
|
||||
### Type Imports
|
||||
|
||||
```typescript
|
||||
// ✅ Good - Use type imports for TypeScript types
|
||||
import type { User } from "@prisma/client";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
// ❌ Bad - Regular import for types
|
||||
import { User } from "@prisma/client";
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Code Structure
|
||||
|
||||
### Early Returns
|
||||
|
||||
- Prefer early returns to reduce nesting: `if (!booking) return null;`
|
||||
|
||||
### Composition Over Prop Drilling
|
||||
|
||||
- Use React children and context instead of passing props through multiple components
|
||||
|
||||
### Security Rules
|
||||
|
||||
```typescript
|
||||
// ❌ NEVER expose credential keys
|
||||
const user = await prisma.user.findFirst({
|
||||
select: {
|
||||
credentials: {
|
||||
select: {
|
||||
key: true, // ❌ NEVER do this
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ✅ Good - Never select credential.key field
|
||||
const user = await prisma.user.findFirst({
|
||||
select: {
|
||||
credentials: {
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
// key field is excluded for security
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,83 @@
|
||||
# Build, Test & Development Commands
|
||||
|
||||
## Development Commands
|
||||
|
||||
- `yarn dev` - Start development server for web app
|
||||
- `yarn dev:all` - Start web, website, and console apps
|
||||
- `yarn dev:api` - Start web app with API proxy and API
|
||||
- `yarn dev:console` - Start web app with console
|
||||
- `yarn dx` - Start development with database setup
|
||||
|
||||
## Build Commands
|
||||
|
||||
- `yarn build` - Build all packages and apps
|
||||
- `yarn build:ai` - Build AI package specifically
|
||||
- `yarn clean` - Remove build artifacts (node_modules, .next, .turbo, dist)
|
||||
|
||||
## Lint & Type Check
|
||||
|
||||
- `yarn lint` - Run ESLint on codebase
|
||||
- `yarn lint:fix` - Run ESLint and fix issues
|
||||
- `yarn lint:report` - Generate lint report
|
||||
- `yarn type-check` - Run TypeScript type checking
|
||||
- `yarn format` - Format code with Prettier
|
||||
|
||||
## Testing Commands
|
||||
|
||||
### Unit Tests
|
||||
|
||||
- `yarn test` - Run unit tests (vitest)
|
||||
- `yarn test <filename>` - Run tests for specific file
|
||||
- `yarn test <filename> -- --integrationTestsOnly` - Run integration tests for specific file
|
||||
- `yarn test <filename> -t "<testName>" -- --integrationTestsOnly` - Run specific test by name
|
||||
- `yarn tdd` - Run tests in watch mode
|
||||
- `yarn test:ui` - Run tests with UI interface
|
||||
|
||||
### End-to-End Tests
|
||||
|
||||
- `yarn e2e` - Run end-to-end tests (Playwright)
|
||||
- `yarn e2e <filename>` - Run E2E tests for specific file
|
||||
- `yarn e2e <filename> --grep "<testName>"` - Run specific E2E test by name
|
||||
- `yarn e2e:app-store` - Run app store E2E tests
|
||||
- `yarn e2e:embed` - Run embed E2E tests
|
||||
- `yarn test-e2e` - Run database seed + E2E tests
|
||||
|
||||
## Database Commands
|
||||
|
||||
- `yarn prisma` - Run Prisma CLI commands
|
||||
- `yarn db-seed` - Seed database with test data
|
||||
- `yarn db-deploy` - Deploy database migrations
|
||||
- `yarn db-studio` - Open Prisma Studio
|
||||
- `psql "postgresql://postgres:@localhost:5432/calendso"` - Connect to local PostgreSQL database
|
||||
|
||||
## App Store Commands
|
||||
|
||||
- `yarn create-app` - Create new app store integration
|
||||
- `yarn edit-app` - Edit existing app
|
||||
- `yarn delete-app` - Delete app
|
||||
- `yarn app-store:build` - Build app store
|
||||
- `yarn app-store:watch` - Watch app store for changes
|
||||
|
||||
## Useful Development Patterns
|
||||
|
||||
### Running Single Tests
|
||||
|
||||
```bash
|
||||
# Unit test specific file
|
||||
yarn vitest run packages/lib/some-file.test.ts
|
||||
|
||||
# Integration test specific file
|
||||
yarn test routing-form-response-denormalized.integration-test.ts -- --integrationTestsOnly
|
||||
|
||||
# E2E test specific file
|
||||
yarn e2e tests/booking-flow.e2e.ts
|
||||
|
||||
# Run specific test by name
|
||||
yarn e2e tests/booking-flow.e2e.ts --grep "should create booking"
|
||||
```
|
||||
|
||||
### Environment Setup
|
||||
|
||||
- Copy `.env.example` to `.env` and configure
|
||||
- Copy `.env.appStore.example` to `.env.appStore` for app store development
|
||||
- Run `yarn dx` for initial development setup with database
|
||||
@@ -0,0 +1,320 @@
|
||||
# Knowledge Base - Product & Domain-Specific Information
|
||||
|
||||
## Repo note for calcom/cal.com
|
||||
|
||||
The whole thing is a monorepo. You need to be working in the apps/web folder.
|
||||
|
||||
Linting and Formatting
|
||||
- Run lint with report generation: `yarn lint:report`
|
||||
- Run type checking: `yarn type-check:ci --force`
|
||||
- Run auto-fix: `yarn lint -- --fix`
|
||||
|
||||
Development
|
||||
- Install dependencies: `yarn`
|
||||
- Set up environment:
|
||||
- Copy `.env.example` to `.env`
|
||||
- Generate keys with `openssl rand -base64 32` for both `NEXTAUTH_SECRET` and `CALENDSO_ENCRYPTION_KEY`
|
||||
- Configure Postgres database URL in `.env`
|
||||
- Set DATABASE_DIRECT_URL to the same value as DATABASE_URL
|
||||
|
||||
Database Setup
|
||||
- Development: `yarn workspace @calcom/prisma db-migrate`
|
||||
- Production: `yarn workspace @calcom/prisma db-deploy`
|
||||
|
||||
When setting up local development database, it'll create a bunch of users for you. The passwords are the same as the username. e.g. 'free:free' and 'pro:pro'
|
||||
|
||||
PR Requirements
|
||||
- PR title must follow Conventional Commits specification
|
||||
- For most PRs, you only need to run linting and type checking
|
||||
- E2E tests will only run if PR has "ready-for-e2e" label
|
||||
|
||||
Logging
|
||||
- Control logging verbosity by setting `NEXT_PUBLIC_LOGGER_LEVEL` in .env:
|
||||
- 0: silly
|
||||
- 1: trace
|
||||
- 2: debug
|
||||
- 3: info
|
||||
- 4: warn
|
||||
- 5: error
|
||||
- 6: fatal
|
||||
|
||||
## When addressing issues in the Cal.com repository
|
||||
|
||||
When working on the Cal.com repository, prioritize fixing type issues before addressing failing tests. Running `yarn type-check:ci --force` to identify and fix TypeScript errors should be done first, as these errors are often the root cause of test failures. Only after resolving type issues should you move on to fixing failing tests with `TZ=UTC yarn test`.
|
||||
|
||||
## When creating pull requests
|
||||
|
||||
Create pull requests in draft mode by default, so that actual human can mark it as ready for review only when it is.
|
||||
|
||||
## When developing Playwright tests in the Cal.com repository
|
||||
|
||||
Always ensure Playwright tests pass locally before pushing code. The user requires fast local e2e feedback loops instead of relying on CI, which is too slow for development iteration. Never push test code until those tests are passing locally first.
|
||||
|
||||
## When fixing failing tests in the Cal.com repository
|
||||
|
||||
When fixing failing tests in the Cal.com repository, take an incremental approach by addressing one file at a time rather than attempting to fix all issues simultaneously. This methodical approach makes it easier to identify and resolve specific issues without getting overwhelmed by the complexity of multiple failing tests across different files. Focus on getting each file's tests passing completely before moving on to the next file.
|
||||
|
||||
To identify and fix issues in the Cal.com codebase:
|
||||
|
||||
1. Run `yarn type-check:ci --force` to identify TypeScript type errors and get fresh results always, bypassing any caching issues
|
||||
2. Run `yarn test` to identify failing unit tests
|
||||
3. Address both type errors and failing tests before considering the task complete
|
||||
4. Type errors often need to be fixed first as they may be causing the test failures
|
||||
|
||||
## When implementing mock services in the Cal.com test files
|
||||
|
||||
When mocking calendar services in Cal.com test files, implement the Calendar interface rather than adding individual properties from each specific calendar service type (like FeishuCalendarService). Since all calendar services implement the Calendar interface and are stored in a map, the mock service should also implement this interface to ensure type compatibility. This approach is more maintainable than trying to add all properties from each specific calendar service implementation. For complex mocks that cause type compatibility issues with deep mocks, consider using simpler fake implementations that directly implement the required interfaces instead of trying to match all properties of the original service classes. When needed, you can modify other mock files to support your implementation rather than trying to force compatibility with existing mocks.
|
||||
|
||||
## When implementing mocks for Cal.com app-store integrations
|
||||
|
||||
When mocking app-store resources in Cal.com tests, prefer implementing simpler mock designs that directly implement the required interfaces rather than trying to match complex deep mock structures created with mockDeep. This approach is more maintainable and helps resolve type compatibility issues. The user encourages creative solutions and refactoring to better designs when the standard mocking approach causes persistent type errors.
|
||||
|
||||
## When implementing workflow triggers in the Cal.com repository
|
||||
|
||||
To trigger workflows in Cal.com, use the `scheduleWorkflowReminders` function. This is the standard approach used throughout the codebase for triggering any workflow. Before implementing new workflow triggers, examine existing implementations in the codebase to understand the pattern. The function filters workflows by trigger type and processes each workflow step. Key locations where this is used include booking handlers, confirmation processes, and other booking-related events.
|
||||
|
||||
## When making changes to Prisma schema in Cal.com
|
||||
|
||||
After making changes to the Prisma schema in Cal.com and creating migrations, you need to run `yarn prisma generate` to update the TypeScript types. This is especially important when switching Node.js versions, after adding new fields to models, or after pulling changes that include Prisma schema updates, as it ensures the TypeScript compiler recognizes the updated schema structure. If you encounter errors related to missing enum values (like CreationSource.WEBAPP), running `yarn prisma generate` will typically resolve these issues by regenerating the TypeScript types from the schema.
|
||||
|
||||
If you encounter enum generator errors during the Prisma generate step (like "Cannot find module './enum-generator.ts'"), run `yarn install` first before trying to generate. This ensures all dependencies are properly installed before the generation process.
|
||||
|
||||
Whenever you change the schema.prisma file, remember to always consolidate migrations by squashing them as declared in the Prisma docs: https://www.prisma.io/docs/orm/prisma-migrate/workflows/squashing-migrations. This helps maintain a clean migration history and prevents accumulation of multiple migration files.
|
||||
|
||||
## When reviewing PRs in the Cal.com repository
|
||||
|
||||
When asked to review a PR, focus on providing a clear summary of what the PR is doing and its core functionality. Avoid getting sidetracked by CI failures, testing issues, or technical implementation details unless specifically requested. The user prefers concise, focused reviews that prioritize understanding the main purpose and changes of the PR.
|
||||
|
||||
## When running Playwright tests in the Cal.com repository
|
||||
|
||||
Use the command format `PLAYWRIGHT_HEADLESS=1 yarn e2e [test-file.e2e.ts]` to run Playwright tests instead of the standard `yarn playwright test` command. This format includes the proper timezone setting, virtual display server, and uses the repository's e2e runner.
|
||||
|
||||
## When running tests in the Cal.com repository
|
||||
|
||||
When running tests in the Cal.com repository, use the TZ=UTC environment variable (e.g., `TZ=UTC yarn test`) to ensure consistent timezone handling. This prevents timezone-related test failures that might occur when tests are run in different environments or by different developers with varying local timezone settings.
|
||||
|
||||
## When working on calendar cache features in the Cal.com codebase
|
||||
|
||||
The calendar cache system follows specific patterns in `packages/features/calendar-cache-sql`. When implementing provider-specific calendar cache services (like for Outlook/Office365), the provider-specific code should be placed in the corresponding provider directory (e.g., `packages/app-store/office365calendar`).
|
||||
|
||||
## When working on PRs in the Cal.com repository
|
||||
|
||||
When making changes to the Cal.com codebase, always run type checks locally using `yarn type-check:ci` before concluding that CI failures are unrelated to your changes. Even if errors appear in files you haven't directly modified, your changes might still be causing type issues through dependencies or type inference. Compare type check results between the main branch and your feature branch to confirm whether you've introduced new type errors.
|
||||
|
||||
## When working on type issues in the Cal.com repository
|
||||
|
||||
Type casting with "as any" is strictly forbidden in the Cal.com codebase. When encountering Prisma type incompatibilities or other TypeScript type issues, proper type-safe solutions must be used instead, such as Prisma extensions system, type parameter constraints, repository pattern isolation, explicit type definitions, and extension composition patterns that are already established in the codebase.
|
||||
|
||||
## When working on UI layout changes in the Cal.com web application
|
||||
|
||||
The event types page UI components are located in `apps/web/modules/event-types/views/event-types-listing-view.tsx`. This file contains the layout implementation for the search bar and team tabs components on the event types listing page.
|
||||
|
||||
Changes to shared UI patterns (like tab layouts and button alignments) need to be checked across multiple views to maintain consistency:
|
||||
- Event types page layout: `apps/web/modules/event-types/views/event-types-listing-view.tsx`
|
||||
- Bookings page layout: `apps/web/modules/bookings/views/bookings-listing-view.tsx`
|
||||
- Common elements like tabs, search bars, and filter buttons should maintain consistent alignment across views
|
||||
|
||||
## When working on workflow triggers or similar enum-based features in the Cal.com codebase
|
||||
|
||||
To add new workflow triggers:
|
||||
|
||||
1. Check packages/prisma/schema.prisma for existing webhooks and workflow trigger enums as reference
|
||||
2. Add the same enums to workflows (only when asked by user specifically, or else focus on users requirement)
|
||||
3. Add enums to packages/features/ee/workflows/lib/constants.ts for UI display
|
||||
4. Add translations to en/locale.json using the format {enum}_trigger (all lowercase). Webhook triggers serve as the reference implementation pattern for workflow triggers.
|
||||
|
||||
## When working with app-store integrations in Cal.com
|
||||
|
||||
The Cal.com repository uses generated files (*.generated.ts) for app-store integrations. These files are created by the app-store-cli tool. When making structural changes to how integrations are imported or used, you need to update CLI code that generates these files. Typically manual changes to the *.generated.ts files are not made. That was only for PR 19771 for a proof-of-concept. Recent changes have moved from dynamic imports to static map-based imports for better performance. When working with browser components in the app-store, static imports should be used rather than dynamic imports (using Next.js' dynamic function) to maintain consistency with the performance improvements.
|
||||
|
||||
When modifying the app-store-cli build.ts file, you must ensure it correctly handles all types of generated files:
|
||||
1. Regular service files (calendar.services.generated.ts, crm.services.generated.ts, etc.) need default imports
|
||||
2. Browser component files (apps.browser-addon.generated.tsx, etc.) may require dynamic imports with Next.js
|
||||
3. After making changes to build.ts, always verify all generated files have the correct imports by checking each file type
|
||||
|
||||
The lazyImport parameter in getExportedObject() determines whether to use dynamic imports (for browser components) or static imports (for server-side services).
|
||||
|
||||
## When working with branches in the Cal.com repository
|
||||
|
||||
When asked to move changes to a different branch in the Cal.com repository, use git commands to commit existing changes to the specified branch rather than redoing the work. This is more efficient and prevents duplication of effort. The user prefers direct branch operations over reimplementing the same changes multiple times.
|
||||
|
||||
## When working with calendar events in the Cal.com codebase
|
||||
|
||||
Cal.com events in Google Calendar can be identified by checking if the iCalUID ends with "@Cal.com" (e.g., "2GBXSdEixretciJfKVmYN8@Cal.com"). This identifier is used to distinguish Cal.com bookings from other calendar events for data storage and privacy purposes.
|
||||
|
||||
## When working with CI/CD in the Cal.com repository
|
||||
|
||||
When reviewing CI check failures in Cal.com:
|
||||
1. E2E tests can be flaky and may fail intermittently
|
||||
2. Focus only on CI failures that are directly related to your code changes
|
||||
3. Infrastructure-related failures (like dependency installation issues) can be disregarded if all code-specific checks (type checking, linting, unit tests) are passing
|
||||
|
||||
## When working with database models in Cal.com
|
||||
|
||||
Database models in Cal.com are defined in `packages/prisma/schema.prisma`. When adding new fields to models:
|
||||
|
||||
1. For timestamp fields like `createdAt` and `updatedAt`:
|
||||
- Do not set default values if you want existing records to have null values
|
||||
- Only new records should get timestamps automatically
|
||||
- For `updatedAt` fields, ensure they're updated when records are modified
|
||||
|
||||
2. Create a migration using `npx prisma migrate dev --name migration_name` to update the database schema
|
||||
|
||||
3. When implementing cache-related features that require timestamp tracking, always update the database schema first before modifying application code that references those fields. The schema changes must be completed and migrated before the application can successfully query or use the new fields.
|
||||
|
||||
## When working with generated files in the Cal.com repository
|
||||
|
||||
When fixing imports in Cal.com's generated files (like packages/app-store/apps.browser-*.generated.tsx), always check the actual exports in the source files first. For EventTypeAppCardInterface components, they likely use named exports rather than default exports, requiring imports like `import * as ComponentName from "./path"` instead of `import ComponentName from "./path"`. This verification step is crucial when working with browser-addon, browser-appsettings, browser-eventtypesettings, and browser-install generated files. For these files, if you're seeing import errors, check whether the components are exported as default exports in their source files and adjust your import statements accordingly.
|
||||
|
||||
## When working with git and CI systems
|
||||
|
||||
Always push committed changes to the remote repository before waiting for or checking CI status. Waiting for CI checks on unpushed local commits is backwards - the CI runs on the remote repository state, not local commits. The proper sequence is: commit locally, run local checks, push to remote, then monitor CI status.
|
||||
|
||||
## When working with imports/exports in the Cal.com codebase
|
||||
|
||||
When working with imports in the Cal.com codebase, particularly in app-store integrations, pay attention to whether modules use named exports or default exports. Many services like VideoApiAdapter, CalendarService, and PaymentService are exported as named exports, but the actual export name may differ from the generic service type (e.g., `export class AppleCalendarService` instead of `export class CalendarService`). When importing these services, verify the actual export name in the source file and use the appropriate named import syntax (e.g., `import { AppleCalendarService } from "./applecalendar/lib/CalendarService"` or with renaming `import { AppleCalendarService as ApplecalendarCalendarService } from "./applecalendar/lib/CalendarService"`). Always check the actual export pattern and name in the source file to determine the correct import syntax.
|
||||
|
||||
## When working with tRPC components in the Cal.com repository
|
||||
|
||||
When making changes that affect tRPC components or after pulling updates that modify tRPC-related files, you need to follow a specific build order:
|
||||
1. First run `yarn prisma generate` to ensure all database types are up-to-date
|
||||
2. Then run `cd packages/trpc && yarn build` to rebuild the tRPC package
|
||||
This sequence ensures that type definitions are properly generated before building the tRPC components that depend on them, preventing type errors during compilation.
|
||||
|
||||
## When working with workflows or webhooks in the Cal.com repository
|
||||
|
||||
Workflows and webhooks are two completely separate features in Cal.com with different implementations and file structures. The workflow constants file is located at `packages/features/ee/workflows/lib/constants.ts`, not in the webhooks directory. When working on workflow triggers, do not reference or use webhook trigger implementations - they are distinct systems that should not be confused or mixed.
|
||||
|
||||
## When adding new feature flags to the Cal.com repository
|
||||
|
||||
To seed new feature flags in Cal.com, create a Prisma migration using the command `yarn prisma migrate dev --create-only --name seed_[feature_name]_feature`. The migration file should be placed in `packages/prisma/migrations/` with a timestamp prefix format like `20250724210733_seed_calendar_cache_sql_features/migration.sql`. Follow the pattern from existing feature seeding migrations like `packages/prisma/migrations/20241216000000_add_calendar_cache_serve/migration.sql` for the SQL structure. The migration should INSERT the new features into the `Feature` table with appropriate type (like `OPERATIONAL`) and default `enabled` status for manual team enablement.
|
||||
|
||||
## When adding new UI elements or text strings to Cal.com
|
||||
|
||||
All UI strings in Cal.com must be properly translated using the i18n system. This includes:
|
||||
- Labels for new UI elements (like dropdown labels, settings headers)
|
||||
- Option values that are displayed to users
|
||||
- Any text that appears in the interface
|
||||
|
||||
Even if some related strings are already translated (like "Bookings" and "Insights"), new strings must be explicitly added to the translation system.
|
||||
|
||||
## When creating a pull request
|
||||
|
||||
### Title
|
||||
|
||||
- Use conventional commits: `feat:`, `fix:`, `refactor:`
|
||||
- Be specific: `fix: handle timezone edge case in booking creation`
|
||||
- Not generic: `fix: booking bug`
|
||||
|
||||
### Size Limits
|
||||
|
||||
- **Large PRs** (>500 lines or >10 files) are not recommended.
|
||||
- Guide the user how to split large PRs into smaller ones.
|
||||
|
||||
## When handling errors
|
||||
|
||||
### Descriptive Errors
|
||||
|
||||
```typescript
|
||||
// ✅ Good - Descriptive error with context
|
||||
throw new Error(`Unable to create booking: User ${userId} has no available time slots for ${date}`);
|
||||
|
||||
// ❌ Bad - Generic error
|
||||
throw new Error("Booking failed");
|
||||
```
|
||||
|
||||
### Error Types
|
||||
|
||||
```typescript
|
||||
// ✅ Good - Use proper error classes
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Invalid booking time slot",
|
||||
});
|
||||
```
|
||||
|
||||
## Basic Performance Guidelines
|
||||
|
||||
- Aim for O(n) or O(n log n) complexity, avoid O(n²)
|
||||
- Use database-level filtering instead of JavaScript filtering
|
||||
- Consider pagination for large datasets
|
||||
- Use database transactions for related operations
|
||||
|
||||
## When querying database
|
||||
|
||||
Prefer Select over Include:
|
||||
|
||||
```typescript
|
||||
// ✅ Good - Use select for performance and security
|
||||
const booking = await prisma.booking.findFirst({
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ❌ Bad - Include fetches all fields
|
||||
const booking = await prisma.booking.findFirst({
|
||||
include: {
|
||||
user: true, // This gets ALL user fields
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Avoid barrel imports
|
||||
|
||||
```typescript
|
||||
// ❌ Bad - Avoid importing from index.ts barrel files
|
||||
import { BookingService, UserService } from "./services";
|
||||
|
||||
// ✅ Good - Import directly from source files
|
||||
import { BookingService } from "./services/BookingService";
|
||||
import { UserService } from "./services/UserService";
|
||||
|
||||
|
||||
// ❌ Bad
|
||||
import { Button } from "@calcom/ui";
|
||||
|
||||
// ✅ Good - Import directly from source files
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
```
|
||||
|
||||
## File Naming Conventions
|
||||
|
||||
### Repository Files
|
||||
|
||||
- **Must** include `Repository` suffix, PascalCase matching class: `PrismaBookingRepository.ts`
|
||||
|
||||
### Service Files
|
||||
|
||||
- **Must** include `Service` suffix, PascalCase matching class, avoid generic names: `MembershipService.ts`
|
||||
|
||||
### General Files
|
||||
|
||||
- **Components**: PascalCase (e.g., `BookingForm.tsx`)
|
||||
- **Utilities**: kebab-case (e.g., `date-utils.ts`)
|
||||
- **Types**: PascalCase with `.types.ts` suffix (e.g., `Booking.types.ts`)
|
||||
- **Tests**: Same as source file + `.test.ts` or `.spec.ts`
|
||||
- **Avoid**: Dot-suffixes like `.service.ts`, `.repository.ts` (except for tests, types, specs)
|
||||
|
||||
## When using Day.js
|
||||
|
||||
```typescript
|
||||
// ⚠️ Slow in performance-critical code (loops)
|
||||
dates.map((date) => dayjs(date).add(1, "day").format());
|
||||
|
||||
// ✅ Better - Use .utc() for performance
|
||||
dates.map((date) => dayjs.utc(date).add(1, "day").format());
|
||||
|
||||
// ✅ Best - Use native Date when possible
|
||||
dates.map((date) => new Date(date.valueOf() + 24 * 60 * 60 * 1000));
|
||||
```
|
||||
+19
-1
@@ -383,9 +383,27 @@ TASKER_ENABLE_EMAILS=0
|
||||
# Ratelimiting via unkey
|
||||
UNKEY_ROOT_KEY=
|
||||
|
||||
# Used for Cal.ai Enterprise Voice AI Agents
|
||||
# Used for Cal.ai Voice AI Agents
|
||||
# https://retellai.com
|
||||
RETELL_AI_KEY=
|
||||
# Local testing overrides for Retell AI
|
||||
RETELL_AI_TEST_MODE=false
|
||||
# JSON mapping of local to production event type IDs (e.g. {"50": 747280} without any string)
|
||||
RETELL_AI_TEST_EVENT_TYPE_MAP=
|
||||
RETELL_AI_TEST_CAL_API_KEY=
|
||||
|
||||
# Used for buying phone number for cal ai voice agent
|
||||
STRIPE_PHONE_NUMBER_MONTHLY_PRICE_ID=
|
||||
|
||||
|
||||
CAL_AI_CALL_RATE_PER_MINUTE=0.29
|
||||
|
||||
|
||||
STRIPE_WEBHOOK_SECRET_BILLING=
|
||||
|
||||
|
||||
# Price for buying a phone number for cal.ai voice agent (Default is 5)
|
||||
NEXT_PUBLIC_CAL_AI_PHONE_NUMBER_MONTHLY_PRICE=
|
||||
|
||||
# Used for the huddle01 integration
|
||||
HUDDLE01_API_TOKEN=
|
||||
|
||||
@@ -2,4 +2,22 @@
|
||||
/** @type {import("eslint").Linter.Config} */
|
||||
module.exports = {
|
||||
extends: ["./packages/config/eslint-preset.js"],
|
||||
plugins: ["import"],
|
||||
rules: {
|
||||
"import/no-cycle": ["warn", { maxDepth: Infinity }],
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ["packages/lib/**/*.{ts,tsx,js,jsx}", "packages/prisma/**/*.{ts,tsx,js,jsx}"],
|
||||
rules: {
|
||||
"no-restricted-imports": [
|
||||
"warn",
|
||||
{
|
||||
paths: ["@calcom/app-store"],
|
||||
patterns: ["@calcom/app-store/*"],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
+7
-2
@@ -2,7 +2,12 @@
|
||||
/apps/api/**/* @calcom/Platform @calcom/Foundation
|
||||
/apps/ui-playground/**/* @calcom/Consumer @calcom/Foundation
|
||||
/apps/web/**/layout.tsx @calcom/Consumer @calcom/Foundation
|
||||
/apps/web/lib/**/* @calcom/Foundation
|
||||
/apps/web/lib/csp.ts @calcom/Foundation
|
||||
/apps/web/lib/buildNonce.ts @calcom/Foundation
|
||||
/apps/web/lib/daily-webhook/**/* @calcom/Foundation
|
||||
/apps/web/lib/core/**/* @calcom/Foundation
|
||||
/apps/web/lib/booking.ts @calcom/Foundation
|
||||
/apps/web/lib/handleOrgRedirect.ts @calcom/Foundation
|
||||
/apps/web/middleware.ts @calcom/Foundation
|
||||
/deploy/**/* @calcom/Foundation
|
||||
/infra/**/* @calcom/Foundation
|
||||
@@ -25,7 +30,7 @@
|
||||
/packages/lib/slots.ts @calcom/Foundation
|
||||
/packages/platform/atoms/**/*WebWrapper.tsx @calcom/Consumer
|
||||
/packages/platform/**/* @calcom/Platform @calcom/Foundation
|
||||
/packages/prisma/**/* @calcom/DBA
|
||||
/packages/prisma/**/* @calcom/Foundation
|
||||
/packages/trpc/server/routers/viewer/bookings/confirm.handler.ts @calcom/Foundation
|
||||
/packages/trpc/server/routers/viewer/bookings/get.handler.ts @calcom/Foundation
|
||||
/packages/trpc/server/routers/viewer/slots/**/* @calcom/Foundation
|
||||
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
working-directory: docs
|
||||
run: |
|
||||
export NODE_OPTIONS="--max_old_space_size=8192"
|
||||
npm install -g mintlify@4.0.436
|
||||
npm install -g mintlify@4.2.87
|
||||
mintlify dev &
|
||||
sleep 5 # Let it run for 5 seconds
|
||||
kill $!
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Atoms E2E Tests
|
||||
name: E2E Atoms
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
@@ -19,7 +19,7 @@ env:
|
||||
jobs:
|
||||
e2e-atoms:
|
||||
timeout-minutes: 15
|
||||
name: Atoms E2E Tests
|
||||
name: E2E Atoms
|
||||
runs-on: buildjet-4vcpu-ubuntu-2204
|
||||
steps:
|
||||
- uses: docker/login-action@v3
|
||||
@@ -30,7 +30,7 @@ jobs:
|
||||
- uses: ./.github/actions/dangerous-git-checkout
|
||||
- uses: ./.github/actions/yarn-install
|
||||
- uses: ./.github/actions/yarn-playwright-install
|
||||
- name: Run Atoms E2E Tests
|
||||
- name: Run E2E Atoms Tests
|
||||
working-directory: packages/platform/examples/base
|
||||
run: yarn test:e2e
|
||||
- name: Upload Test Results
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
with:
|
||||
repo-token: ${{ secrets.EQUITY_BEE_TEAM_LABELER_ACTION_TOKEN }}
|
||||
organization-name: calcom
|
||||
ignore-labels: "admin, app-store, ai, authentication, automated-testing, billing, bookings, caldav, calendar-apps, ci, console, crm-apps, dba, devops, docs, documentation, emails, embeds, event-types, i18n, impersonation, manual-testing, ui, performance, ops-stack, organizations, public-api, routing-forms, seats, teams, webhooks, workflows, zapier"
|
||||
ignore-labels: "admin, app-store, ai, authentication, automated-testing, billing, bookings, caldav, calendar-apps, ci, console, crm-apps, dba, devops, docs, documentation, emails, embeds, event-types, i18n, impersonation, manual-testing, ui, performance, ops-stack, organizations, public-api, routing-forms, seats, self-hosted, teams, webhooks, workflows, zapier"
|
||||
apply-labels-from-issue:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
name: Performance Tests
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [created]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
base_url:
|
||||
description: 'Base URL for performance tests'
|
||||
required: false
|
||||
default: 'https://cal.dev'
|
||||
|
||||
jobs:
|
||||
performance-tests:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
BASE_URL: ${{ github.event.inputs.base_url || 'https://cal.dev' }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup K6
|
||||
uses: grafana/setup-k6-action@v1
|
||||
with:
|
||||
k6-version: '1.0.0'
|
||||
|
||||
- name: Run Smoke Tests
|
||||
uses: grafana/run-k6-action@v1
|
||||
env:
|
||||
K6_CLOUD_TOKEN: ${{ secrets.K6_CLOUD_TOKEN }}
|
||||
K6_CLOUD_PROJECT_ID: ${{ secrets.K6_CLOUD_PROJECT_ID }}
|
||||
with:
|
||||
path: tests/performance/smoke/*.js
|
||||
cloud-run-locally: true
|
||||
fail-fast: true
|
||||
|
||||
- name: Run Load Tests
|
||||
uses: grafana/run-k6-action@v1
|
||||
env:
|
||||
K6_CLOUD_TOKEN: ${{ secrets.K6_CLOUD_TOKEN }}
|
||||
K6_CLOUD_PROJECT_ID: ${{ secrets.K6_CLOUD_PROJECT_ID }}
|
||||
with:
|
||||
path: tests/performance/load/*.js
|
||||
cloud-run-locally: true
|
||||
fail-fast: true
|
||||
|
||||
- name: Run Stress Tests
|
||||
uses: grafana/run-k6-action@v1
|
||||
env:
|
||||
K6_CLOUD_TOKEN: ${{ secrets.K6_CLOUD_TOKEN }}
|
||||
K6_CLOUD_PROJECT_ID: ${{ secrets.K6_CLOUD_PROJECT_ID }}
|
||||
with:
|
||||
path: tests/performance/stress/*.js
|
||||
cloud-run-locally: true
|
||||
fail-fast: true
|
||||
|
||||
- name: Run Spike Tests
|
||||
uses: grafana/run-k6-action@v1
|
||||
env:
|
||||
K6_CLOUD_TOKEN: ${{ secrets.K6_CLOUD_TOKEN }}
|
||||
K6_CLOUD_PROJECT_ID: ${{ secrets.K6_CLOUD_PROJECT_ID }}
|
||||
with:
|
||||
path: tests/performance/spike/*.js
|
||||
cloud-run-locally: true
|
||||
fail-fast: true
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
with:
|
||||
filters: |
|
||||
has-files-requiring-all-checks:
|
||||
- "!(**.md|.github/CODEOWNERS|docs/**|help/**|apps/web/public/static/locales/**/common.json)"
|
||||
- "!(**.md|**.mdx|.github/CODEOWNERS|docs/**|help/**|apps/web/public/static/locales/**/common.json|i18n.lock)"
|
||||
- name: Get Latest Commit SHA
|
||||
id: get_sha
|
||||
run: |
|
||||
|
||||
@@ -97,3 +97,7 @@ apps/auth
|
||||
!.yarn/sdks
|
||||
!.yarn/versions
|
||||
i18n.cache
|
||||
packages/**/.yarn/ci-cache/
|
||||
|
||||
# AI
|
||||
.claude
|
||||
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
undecided:
|
||||
- "@calcom/prisma"
|
||||
Vendored
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
undecided:
|
||||
- "@calcom/prisma"
|
||||
Vendored
Vendored
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
undecided:
|
||||
- "@calcom/prisma"
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
undecided:
|
||||
- calcom-monorepo
|
||||
Vendored
@@ -0,0 +1,20 @@
|
||||
# Cal.com Development Guide for AI Agents
|
||||
|
||||
**📖 Complete documentation is in the [.agents/](.agents/) directory.**
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Essential Commands
|
||||
|
||||
- `yarn dev` - Start development server
|
||||
- `yarn build` - Build all packages
|
||||
- `yarn lint:fix` - Lint and fix code
|
||||
- `yarn type-check` - TypeScript checking
|
||||
- `yarn test <filename> -- --integrationTestsOnly` - Run integration tests
|
||||
- `yarn e2e <filename> --grep "<testName>"` - Run specific E2E test
|
||||
|
||||
## 📚 Detailed Documentation
|
||||
|
||||
- **[.agents/README.md](.agents/README.md)** - Complete development guide
|
||||
- **[.agents/commands.md](.agents/commands.md)** - All build, test & dev commands
|
||||
- **[.agents/knowledge-base.md](.agents/knowledge-base.md)** - Knowledge base & best practices
|
||||
@@ -4,7 +4,7 @@ import type { NextApiRequest } from "next";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/client";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { schemaEventTypeCreateBodyParams, schemaEventTypeReadPublic } from "~/lib/validations/event-type";
|
||||
import { canUserAccessTeamWithRole } from "~/pages/api/teams/[teamId]/_auth-middleware";
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
"@axiomhq/winston": "^1.2.0",
|
||||
"@calcom/platform-constants": "*",
|
||||
"@calcom/platform-enums": "*",
|
||||
"@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.321",
|
||||
"@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.344",
|
||||
"@calcom/platform-types": "*",
|
||||
"@calcom/platform-utils": "*",
|
||||
"@calcom/prisma": "*",
|
||||
@@ -55,9 +55,9 @@
|
||||
"@nestjs/platform-express": "^10.0.0",
|
||||
"@nestjs/swagger": "^7.3.0",
|
||||
"@nestjs/throttler": "6.2.1",
|
||||
"@sentry/nestjs": "^8.37.1",
|
||||
"@sentry/node": "^8.8.0",
|
||||
"@sentry/profiling-node": "^8.37.1",
|
||||
"@sentry/nestjs": "^9.15.0",
|
||||
"@sentry/node": "^9.15.0",
|
||||
"@sentry/profiling-node": "^9.15.0",
|
||||
"@snyk/protect": "latest",
|
||||
"body-parser": "^1.20.2",
|
||||
"bull": "^4.12.4",
|
||||
|
||||
@@ -38,7 +38,6 @@ import {
|
||||
} from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { ApiQuery, ApiExcludeController as DocsExcludeController } from "@nestjs/swagger";
|
||||
import { CreationSource } from "@prisma/client";
|
||||
import { Request } from "express";
|
||||
import { NextApiRequest } from "next/types";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
@@ -58,6 +57,7 @@ import {
|
||||
getBookingForReschedule,
|
||||
ErrorCode,
|
||||
} from "@calcom/platform-libraries";
|
||||
import { CreationSource } from "@calcom/platform-libraries";
|
||||
import {
|
||||
GetBookingsInput_2024_04_15,
|
||||
CancelBookingInput_2024_04_15,
|
||||
|
||||
+362
-816
File diff suppressed because it is too large
Load Diff
@@ -22,7 +22,6 @@ import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { Logger } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { CreationSource } from "@prisma/client";
|
||||
import { isURL, isPhoneNumber } from "class-validator";
|
||||
import { Request } from "express";
|
||||
import { DateTime } from "luxon";
|
||||
@@ -30,6 +29,7 @@ import { NextApiRequest } from "next/types";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { z } from "zod";
|
||||
|
||||
import { CreationSource } from "@calcom/platform-libraries";
|
||||
import { EventTypeMetaDataSchema } from "@calcom/platform-libraries/event-types";
|
||||
import {
|
||||
CancelBookingInput,
|
||||
|
||||
+1
-1
@@ -30,6 +30,7 @@ import {
|
||||
NoticeThresholdUnitEnum,
|
||||
FrequencyInput,
|
||||
} from "@calcom/platform-enums";
|
||||
import { SchedulingType } from "@calcom/platform-libraries";
|
||||
import {
|
||||
ApiSuccessResponse,
|
||||
CreateEventTypeInput_2024_06_14,
|
||||
@@ -39,7 +40,6 @@ import {
|
||||
NotesDefaultFieldInput_2024_06_14,
|
||||
UpdateEventTypeInput_2024_06_14,
|
||||
} from "@calcom/platform-types";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
|
||||
const orderBySlug = (a: { slug: string }, b: { slug: string }) => {
|
||||
if (a.slug < b.slug) return -1;
|
||||
|
||||
+2
-2
@@ -90,7 +90,7 @@ function getBaseProperties(field: InputBookingField): CustomField | SystemField
|
||||
}
|
||||
|
||||
if (fieldIsCustomSystemName(field)) {
|
||||
const systemName = { ...systemBeforeFieldName };
|
||||
const systemName = structuredClone(systemBeforeFieldName);
|
||||
if (systemName.variantsConfig?.variants?.fullName?.fields?.[0]) {
|
||||
systemName.variantsConfig.variants.fullName.fields[0].label = field.label;
|
||||
}
|
||||
@@ -110,7 +110,7 @@ function getBaseProperties(field: InputBookingField): CustomField | SystemField
|
||||
}
|
||||
|
||||
if (fieldIsCustomSystemNameSplit(field)) {
|
||||
const systemNameSplit = { ...systemBeforeFieldNameSplit };
|
||||
const systemNameSplit = structuredClone(systemBeforeFieldNameSplit);
|
||||
|
||||
const firstNameField = systemNameSplit.variantsConfig?.variants?.firstAndLastName?.fields?.find(
|
||||
(field) => field.name === "firstName"
|
||||
|
||||
+1
@@ -520,6 +520,7 @@ export const systemBeforeFieldName: NameSystemField = {
|
||||
name: "fullName",
|
||||
type: "text",
|
||||
required: true,
|
||||
label: "your_name",
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
+1
-1
@@ -292,7 +292,7 @@ describe("transformBookingFieldsInternalToApi", () => {
|
||||
isDefault: true,
|
||||
required: true,
|
||||
disableOnPrefill: false,
|
||||
label: undefined,
|
||||
label: "your_name",
|
||||
placeholder: undefined,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -2,13 +2,7 @@ import { extractUserContext } from "@/lib/extract-user-context";
|
||||
import { filterReqHeaders } from "@/lib/filterReqHeaders";
|
||||
import type { ArgumentsHost, ExceptionFilter } from "@nestjs/common";
|
||||
import { Catch, HttpStatus, Logger } from "@nestjs/common";
|
||||
import {
|
||||
PrismaClientInitializationError,
|
||||
PrismaClientKnownRequestError,
|
||||
PrismaClientRustPanicError,
|
||||
PrismaClientUnknownRequestError,
|
||||
PrismaClientValidationError,
|
||||
} from "@prisma/client/runtime/library";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { Request } from "express";
|
||||
|
||||
import {
|
||||
@@ -21,18 +15,18 @@ import {
|
||||
import { Response } from "@calcom/platform-types";
|
||||
|
||||
type PrismaError =
|
||||
| PrismaClientInitializationError
|
||||
| PrismaClientKnownRequestError
|
||||
| PrismaClientRustPanicError
|
||||
| PrismaClientUnknownRequestError
|
||||
| PrismaClientValidationError;
|
||||
| Prisma.PrismaClientInitializationError
|
||||
| Prisma.PrismaClientKnownRequestError
|
||||
| Prisma.PrismaClientRustPanicError
|
||||
| Prisma.PrismaClientUnknownRequestError
|
||||
| Prisma.PrismaClientValidationError;
|
||||
|
||||
@Catch(
|
||||
PrismaClientInitializationError,
|
||||
PrismaClientKnownRequestError,
|
||||
PrismaClientRustPanicError,
|
||||
PrismaClientUnknownRequestError,
|
||||
PrismaClientValidationError
|
||||
Prisma.PrismaClientInitializationError,
|
||||
Prisma.PrismaClientKnownRequestError,
|
||||
Prisma.PrismaClientRustPanicError,
|
||||
Prisma.PrismaClientUnknownRequestError,
|
||||
Prisma.PrismaClientValidationError
|
||||
)
|
||||
export class PrismaExceptionFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger("PrismaExceptionFilter");
|
||||
@@ -58,7 +52,7 @@ export class PrismaExceptionFilter implements ExceptionFilter {
|
||||
let message = "There was an error, please try again later.";
|
||||
let statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
let errorCode = INTERNAL_SERVER_ERROR;
|
||||
if (error instanceof PrismaClientKnownRequestError) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
switch (error.code) {
|
||||
case "P2002": // Unique constraint failed
|
||||
errorCode = CONFLICT;
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PrismaAttributeRepository as PrismaAttributeRepositoryLib } from "@calcom/platform-libraries/repositories";
|
||||
import { PrismaClient } from "@calcom/prisma";
|
||||
|
||||
@Injectable()
|
||||
export class PrismaAttributeRepository extends PrismaAttributeRepositoryLib {
|
||||
constructor(private readonly dbWrite: PrismaWriteService) {
|
||||
super(dbWrite.prisma as unknown as PrismaClient);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PrismaHostRepository as PrismaHostRepositoryLib } from "@calcom/platform-libraries/repositories";
|
||||
import { PrismaClient } from "@calcom/prisma";
|
||||
|
||||
@Injectable()
|
||||
export class PrismaHostRepository extends PrismaHostRepositoryLib {
|
||||
constructor(private readonly dbWrite: PrismaWriteService) {
|
||||
super(dbWrite.prisma as unknown as PrismaClient);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
export const SYSTEM_ADMIN_ROLE = "SYSADMIN";
|
||||
export const ORG_ROLES = [
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { PrismaAttributeRepository } from "@/lib/repositories/prisma-attribute.repository";
|
||||
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
|
||||
import { PrismaHostRepository } from "@/lib/repositories/prisma-host.repository";
|
||||
import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";
|
||||
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { LuckyUserService as BaseLuckyUserService } from "@calcom/platform-libraries/bookings";
|
||||
|
||||
@Injectable()
|
||||
export class LuckyUserService extends BaseLuckyUserService {
|
||||
constructor(
|
||||
bookingRepository: PrismaBookingRepository,
|
||||
hostRepository: PrismaHostRepository,
|
||||
oooRepository: PrismaOOORepository,
|
||||
userRepository: PrismaUserRepository,
|
||||
attributeRepository: PrismaAttributeRepository
|
||||
) {
|
||||
super({
|
||||
bookingRepository: bookingRepository,
|
||||
hostRepository: hostRepository,
|
||||
oooRepository: oooRepository,
|
||||
userRepository: userRepository,
|
||||
attributeRepository: attributeRepository,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
export const MembershipRoles = Reflector.createDecorator<MembershipRole[]>();
|
||||
|
||||
@@ -6,7 +6,7 @@ import { UserWithProfile } from "@/modules/users/users.repository";
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
@Injectable()
|
||||
export class OrganizationRolesGuard implements CanActivate {
|
||||
|
||||
@@ -107,6 +107,10 @@ export class BillingService implements OnModuleDestroy {
|
||||
const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);
|
||||
const customerId = teamWithBilling?.platformBilling?.customerId;
|
||||
|
||||
if (!customerId) {
|
||||
throw new NotFoundException("No customer id associated with the team.");
|
||||
}
|
||||
|
||||
const { url } = await this.stripeService.getStripe().checkout.sessions.create({
|
||||
customer: customerId,
|
||||
success_url: `${this.webAppUrl}/settings/platform/`,
|
||||
@@ -116,6 +120,7 @@ export class BillingService implements OnModuleDestroy {
|
||||
teamId: teamId.toString(),
|
||||
plan: plan.toString(),
|
||||
},
|
||||
currency: "usd",
|
||||
});
|
||||
|
||||
if (!url) throw new InternalServerErrorException("Failed to create Stripe session.");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
@Injectable()
|
||||
export class MembershipsRepository {
|
||||
|
||||
+2
-4
@@ -1,5 +1,4 @@
|
||||
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
|
||||
import { Locales } from "@/lib/enums/locales";
|
||||
import { MembershipRoles } from "@/modules/auth/decorators/roles/membership-roles.decorator";
|
||||
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
|
||||
import { OrganizationRolesGuard } from "@/modules/auth/guards/organization-roles/organization-roles.guard";
|
||||
@@ -7,7 +6,6 @@ import { GetManagedUsersInput } from "@/modules/oauth-clients/controllers/oauth-
|
||||
import { CreateManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/create-managed-user.output";
|
||||
import { GetManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/get-managed-user.output";
|
||||
import { GetManagedUsersOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/get-managed-users.output";
|
||||
import { ManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/managed-user.output";
|
||||
import { TOKENS_DOCS } from "@/modules/oauth-clients/controllers/oauth-flow/oauth-flow.controller";
|
||||
import { KeysResponseDto } from "@/modules/oauth-clients/controllers/oauth-flow/responses/KeysResponse.dto";
|
||||
import { OAuthClientGuard } from "@/modules/oauth-clients/guards/oauth-client-guard";
|
||||
@@ -34,10 +32,10 @@ import {
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiTags as DocsTags, ApiHeader } from "@nestjs/swagger";
|
||||
import { User, MembershipRole } from "@prisma/client";
|
||||
import { plainToInstance } from "class-transformer";
|
||||
import { User } from "@prisma/client";
|
||||
|
||||
import { SUCCESS_STATUS, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
@Controller({
|
||||
path: "/v2/oauth-clients/:clientId/users",
|
||||
|
||||
+2
-1
@@ -17,10 +17,11 @@ import { OAuthClientWebhooksService } from "@/modules/webhooks/services/oauth-cl
|
||||
import { WebhooksService } from "@/modules/webhooks/services/webhooks.service";
|
||||
import { Controller, Post, Body, UseGuards, Get, Param, Query, Delete, Patch } from "@nestjs/common";
|
||||
import { ApiHeader, ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
|
||||
import { Webhook, MembershipRole } from "@prisma/client";
|
||||
import { Webhook } from "@prisma/client";
|
||||
import { plainToClass } from "class-transformer";
|
||||
|
||||
import { SUCCESS_STATUS, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
import { SkipTakePagination } from "@calcom/platform-types";
|
||||
|
||||
import { OAuthClientGuard } from "../../guards/oauth-client-guard";
|
||||
|
||||
+1
-3
@@ -5,12 +5,10 @@ import { MembershipRoles } from "@/modules/auth/decorators/roles/membership-role
|
||||
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
|
||||
import { OrganizationRolesGuard } from "@/modules/auth/guards/organization-roles/organization-roles.guard";
|
||||
import { GetManagedUsersOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/get-managed-users.output";
|
||||
import { ManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/managed-user.output";
|
||||
import { CreateOAuthClientResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/CreateOAuthClientResponse.dto";
|
||||
import { GetOAuthClientResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/GetOAuthClientResponse.dto";
|
||||
import { GetOAuthClientsResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/GetOAuthClientsResponse.dto";
|
||||
import { OAuthClientGuard } from "@/modules/oauth-clients/guards/oauth-client-guard";
|
||||
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
||||
import { OAuthClientUsersOutputService } from "@/modules/oauth-clients/services/oauth-clients-users-output.service";
|
||||
import { OAuthClientsService } from "@/modules/oauth-clients/services/oauth-clients/oauth-clients.service";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
@@ -37,9 +35,9 @@ import {
|
||||
ApiExcludeEndpoint,
|
||||
ApiHeader,
|
||||
} from "@nestjs/swagger";
|
||||
import { User, MembershipRole } from "@prisma/client";
|
||||
|
||||
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
import { CreateOAuthClientInput, UpdateOAuthClientInput, Pagination } from "@calcom/platform-types";
|
||||
|
||||
@Controller({
|
||||
|
||||
@@ -8,9 +8,10 @@ import { CreateManagedUserInput } from "@/modules/users/inputs/create-managed-us
|
||||
import { UpdateManagedUserInput } from "@/modules/users/inputs/update-managed-user.input";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { BadRequestException, ConflictException, Injectable, Logger } from "@nestjs/common";
|
||||
import { User, CreationSource, PlatformOAuthClient } from "@prisma/client";
|
||||
import { User, PlatformOAuthClient } from "@prisma/client";
|
||||
|
||||
import { createNewUsersConnectToOrgIfExists, slugify } from "@calcom/platform-libraries";
|
||||
import { CreationSource } from "@calcom/platform-libraries";
|
||||
|
||||
@Injectable()
|
||||
export class OAuthClientUsersService {
|
||||
|
||||
+2
-1
@@ -1,6 +1,5 @@
|
||||
import { CreateOrganizationAttributeOptionInput } from "@/modules/organizations/attributes/options/inputs/create-organization-attribute-option.input";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { AttributeType } from "@prisma/client";
|
||||
import { Type } from "class-transformer";
|
||||
import {
|
||||
IsArray,
|
||||
@@ -12,6 +11,8 @@ import {
|
||||
ValidateNested,
|
||||
} from "class-validator";
|
||||
|
||||
import { AttributeType } from "@calcom/platform-libraries";
|
||||
|
||||
export class CreateOrganizationAttributeInput {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { AttributeType } from "@prisma/client";
|
||||
import { IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
|
||||
|
||||
import { AttributeType } from "@calcom/platform-libraries";
|
||||
|
||||
export class UpdateOrganizationAttributeInput {
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
|
||||
+4
-1
@@ -6,7 +6,7 @@ import { UsersModule } from "@/modules/users/users.module";
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import { SchedulingType, User } from "@prisma/client";
|
||||
import { User } from "@prisma/client";
|
||||
import * as request from "supertest";
|
||||
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
|
||||
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
ConfirmationPolicyEnum,
|
||||
NoticeThresholdUnitEnum,
|
||||
} from "@calcom/platform-enums";
|
||||
import { SchedulingType } from "@calcom/platform-libraries";
|
||||
import {
|
||||
ApiSuccessResponse,
|
||||
CreateTeamEventTypeInput_2024_06_14,
|
||||
@@ -725,6 +726,7 @@ describe("Organizations Event Types Endpoints", () => {
|
||||
isDefault: true,
|
||||
type: "name",
|
||||
slug: "name",
|
||||
label: "your_name",
|
||||
required: true,
|
||||
disableOnPrefill: false,
|
||||
},
|
||||
@@ -822,6 +824,7 @@ describe("Organizations Event Types Endpoints", () => {
|
||||
type: "name",
|
||||
slug: "name",
|
||||
required: true,
|
||||
label: "your_name",
|
||||
disableOnPrefill: false,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -7,12 +7,12 @@ import { TeamsRepository } from "@/modules/teams/teams/teams.repository";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
|
||||
|
||||
import { SchedulingType } from "@calcom/platform-libraries";
|
||||
import {
|
||||
CreateTeamEventTypeInput_2024_06_14,
|
||||
UpdateTeamEventTypeInput_2024_06_14,
|
||||
HostPriority,
|
||||
} from "@calcom/platform-types";
|
||||
import { SchedulingType } from "@calcom/prisma/client";
|
||||
|
||||
export type TransformedCreateTeamEventTypeInput = Awaited<
|
||||
ReturnType<InstanceType<typeof InputOrganizationsEventTypesService>["transformInputCreateTeamEventType"]>
|
||||
|
||||
@@ -2,9 +2,17 @@ import { OutputEventTypesService_2024_06_14 } from "@/ee/event-types/event-types
|
||||
import { TeamsEventTypesRepository } from "@/modules/teams/event-types/teams-event-types.repository";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import type { EventType, User, Schedule, Host, DestinationCalendar, CalVideoSettings } from "@prisma/client";
|
||||
import { SchedulingType, Team } from "@prisma/client";
|
||||
import type {
|
||||
Team,
|
||||
EventType,
|
||||
User,
|
||||
Schedule,
|
||||
Host,
|
||||
DestinationCalendar,
|
||||
CalVideoSettings,
|
||||
} from "@prisma/client";
|
||||
|
||||
import { SchedulingType } from "@calcom/platform-libraries";
|
||||
import { HostPriority, TeamEventTypeResponseHost } from "@calcom/platform-types";
|
||||
|
||||
type EventTypeRelations = {
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { IsBoolean, IsOptional, IsEnum, IsInt } from "class-validator";
|
||||
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
export class CreateOrgMembershipDto {
|
||||
@IsInt()
|
||||
@ApiProperty()
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { IsBoolean, IsOptional, IsEnum } from "class-validator";
|
||||
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
export class UpdateOrgMembershipDto {
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
|
||||
+1
-1
@@ -1,9 +1,9 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { Expose, Type } from "class-transformer";
|
||||
import { IsEnum, IsString, ValidateNested } from "class-validator";
|
||||
|
||||
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
import { OrgTeamOutputDto } from "@calcom/platform-types";
|
||||
|
||||
export class OrgMeTeamOutputDto extends OrgTeamOutputDto {
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { IsBoolean, IsOptional, IsEnum, IsInt } from "class-validator";
|
||||
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
export class CreateOrgTeamMembershipDto {
|
||||
@IsInt()
|
||||
@ApiProperty()
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { IsBoolean, IsOptional, IsEnum } from "class-validator";
|
||||
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
export class UpdateOrgTeamMembershipDto {
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
|
||||
+2
-1
@@ -1,8 +1,9 @@
|
||||
import { CreateUserInput } from "@/modules/users/inputs/create-user.input";
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { IsString, IsOptional, IsBoolean, IsEnum } from "class-validator";
|
||||
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
export class CreateOrganizationUserInput extends CreateUserInput {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
|
||||
+2
-1
@@ -4,10 +4,11 @@ import { UpdateOrganizationUserInput } from "@/modules/organizations/users/index
|
||||
import { OrganizationsUsersRepository } from "@/modules/organizations/users/index/organizations-users.repository";
|
||||
import { CreateUserInput } from "@/modules/users/inputs/create-user.input";
|
||||
import { Injectable, ConflictException, ForbiddenException } from "@nestjs/common";
|
||||
import { Team, CreationSource } from "@prisma/client";
|
||||
import { Team } from "@prisma/client";
|
||||
import { plainToInstance } from "class-transformer";
|
||||
|
||||
import { createNewUsersConnectToOrgIfExists } from "@calcom/platform-libraries";
|
||||
import { CreationSource } from "@calcom/platform-libraries";
|
||||
|
||||
@Injectable()
|
||||
export class OrganizationsUsersService {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { IsBoolean, IsOptional, IsEnum, IsInt } from "class-validator";
|
||||
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
export class CreateTeamMembershipInput {
|
||||
@IsInt()
|
||||
@ApiProperty({ type: Number })
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsBoolean, IsOptional, IsEnum } from "class-validator";
|
||||
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
export class UpdateTeamMembershipInput {
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { Expose, Transform, Type } from "class-transformer";
|
||||
import { IsBoolean, IsInt, IsObject, IsOptional, IsString, ValidateNested } from "class-validator";
|
||||
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
class MembershipUserOutputDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { Expose, Type } from "class-transformer";
|
||||
import { IsEnum, IsString, ValidateNested } from "class-validator";
|
||||
import { IsEnum, ValidateNested } from "class-validator";
|
||||
|
||||
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
import { TeamOutputDto } from "@calcom/platform-types";
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { Expose, Type } from "class-transformer";
|
||||
import { IsEnum, IsString, ValidateNested } from "class-validator";
|
||||
import { IsEnum, ValidateNested } from "class-validator";
|
||||
|
||||
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
import { TeamOutputDto } from "@calcom/platform-types";
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { Expose, Type } from "class-transformer";
|
||||
import { IsEnum, IsString, ValidateNested } from "class-validator";
|
||||
import { IsEnum, ValidateNested } from "class-validator";
|
||||
|
||||
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
import { TeamOutputDto } from "@calcom/platform-types";
|
||||
|
||||
@@ -4,7 +4,8 @@ import { CreateManagedUserInput } from "@/modules/users/inputs/create-managed-us
|
||||
import { UpdateManagedUserInput } from "@/modules/users/inputs/update-managed-user.input";
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import type { Profile, User, Team, Prisma } from "@prisma/client";
|
||||
import { CreationSource } from "@prisma/client";
|
||||
|
||||
import { CreationSource } from "@calcom/platform-libraries";
|
||||
|
||||
export type UserWithProfile = User & {
|
||||
movedToProfile?: (Profile & { organization: Pick<Team, "isPlatform" | "id" | "slug" | "name"> }) | null;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { ApiProperty, ApiPropertyOptional, PartialType } from "@nestjs/swagger";
|
||||
import { WebhookTriggerEvents } from "@prisma/client";
|
||||
import { IsArray, IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
|
||||
|
||||
import { WebhookTriggerEvents } from "@calcom/platform-libraries";
|
||||
|
||||
export class CreateWebhookInputDto {
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { WebhookTriggerEvents } from "@prisma/client";
|
||||
import { Expose, Type } from "class-transformer";
|
||||
import { IsBoolean, IsEnum, IsInt, IsString, ValidateNested, IsArray } from "class-validator";
|
||||
|
||||
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
|
||||
import { WebhookTriggerEvents } from "@calcom/platform-libraries";
|
||||
|
||||
export class WebhookOutputDto {
|
||||
@IsInt()
|
||||
|
||||
@@ -33,6 +33,11 @@ import {
|
||||
AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
|
||||
BaseWorkflowTriggerDto,
|
||||
BEFORE_EVENT,
|
||||
BOOKING_NO_SHOW_UPDATED,
|
||||
BOOKING_PAID,
|
||||
BOOKING_PAYMENT_INITIATED,
|
||||
BOOKING_REJECTED,
|
||||
BOOKING_REQUESTED,
|
||||
EVENT_CANCELLED,
|
||||
NEW_EVENT,
|
||||
OnAfterCalVideoGuestsNoShowTriggerDto,
|
||||
@@ -41,6 +46,11 @@ import {
|
||||
OnBeforeEventTriggerDto,
|
||||
OnCancelTriggerDto,
|
||||
OnCreationTriggerDto,
|
||||
OnNoShowUpdateTriggerDto,
|
||||
OnPaidTriggerDto,
|
||||
OnPaymentInitiatedTriggerDto,
|
||||
OnRejectedTriggerDto,
|
||||
OnRequestedTriggerDto,
|
||||
OnRescheduleTriggerDto,
|
||||
RESCHEDULE_EVENT,
|
||||
} from "./workflow-trigger.input";
|
||||
@@ -73,6 +83,11 @@ export type TriggerDtoType =
|
||||
| OnRescheduleTriggerDto
|
||||
| OnCancelTriggerDto
|
||||
| OnAfterCalVideoGuestsNoShowTriggerDto
|
||||
| OnRejectedTriggerDto
|
||||
| OnRequestedTriggerDto
|
||||
| OnPaymentInitiatedTriggerDto
|
||||
| OnPaidTriggerDto
|
||||
| OnNoShowUpdateTriggerDto
|
||||
| OnAfterCalVideoHostsNoShowTriggerDto;
|
||||
|
||||
@ApiExtraModels(
|
||||
@@ -81,6 +96,11 @@ export type TriggerDtoType =
|
||||
OnCancelTriggerDto,
|
||||
OnCreationTriggerDto,
|
||||
OnRescheduleTriggerDto,
|
||||
OnNoShowUpdateTriggerDto,
|
||||
OnRejectedTriggerDto,
|
||||
OnRequestedTriggerDto,
|
||||
OnPaymentInitiatedTriggerDto,
|
||||
OnPaidTriggerDto,
|
||||
OnAfterCalVideoGuestsNoShowTriggerDto,
|
||||
OnAfterCalVideoHostsNoShowTriggerDto,
|
||||
WorkflowEmailAddressStepDto,
|
||||
@@ -112,6 +132,11 @@ export class CreateWorkflowDto {
|
||||
{ $ref: getSchemaPath(OnRescheduleTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnAfterCalVideoGuestsNoShowTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnAfterCalVideoHostsNoShowTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnRejectedTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnRequestedTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnPaidTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnPaymentInitiatedTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnNoShowUpdateTriggerDto) },
|
||||
],
|
||||
})
|
||||
@ValidateNested()
|
||||
@@ -126,6 +151,11 @@ export class CreateWorkflowDto {
|
||||
{ value: OnRescheduleTriggerDto, name: RESCHEDULE_EVENT },
|
||||
{ value: OnAfterCalVideoGuestsNoShowTriggerDto, name: AFTER_GUESTS_CAL_VIDEO_NO_SHOW },
|
||||
{ value: OnAfterCalVideoHostsNoShowTriggerDto, name: AFTER_HOSTS_CAL_VIDEO_NO_SHOW },
|
||||
{ value: OnRequestedTriggerDto, name: BOOKING_REQUESTED },
|
||||
{ value: OnRejectedTriggerDto, name: BOOKING_REJECTED },
|
||||
{ value: OnPaymentInitiatedTriggerDto, name: BOOKING_PAYMENT_INITIATED },
|
||||
{ value: OnPaidTriggerDto, name: BOOKING_PAID },
|
||||
{ value: OnNoShowUpdateTriggerDto, name: BOOKING_NO_SHOW_UPDATED },
|
||||
],
|
||||
},
|
||||
})
|
||||
@@ -135,6 +165,11 @@ export class CreateWorkflowDto {
|
||||
| OnCreationTriggerDto
|
||||
| OnRescheduleTriggerDto
|
||||
| OnCancelTriggerDto
|
||||
| OnRejectedTriggerDto
|
||||
| OnRequestedTriggerDto
|
||||
| OnPaidTriggerDto
|
||||
| OnPaymentInitiatedTriggerDto
|
||||
| OnNoShowUpdateTriggerDto
|
||||
| OnAfterCalVideoGuestsNoShowTriggerDto
|
||||
| OnAfterCalVideoHostsNoShowTriggerDto;
|
||||
|
||||
|
||||
@@ -36,6 +36,16 @@ import {
|
||||
AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
|
||||
OnAfterCalVideoHostsNoShowTriggerDto,
|
||||
AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
|
||||
OnNoShowUpdateTriggerDto,
|
||||
OnRejectedTriggerDto,
|
||||
OnRequestedTriggerDto,
|
||||
OnPaymentInitiatedTriggerDto,
|
||||
OnPaidTriggerDto,
|
||||
BOOKING_REQUESTED,
|
||||
BOOKING_REJECTED,
|
||||
BOOKING_PAYMENT_INITIATED,
|
||||
BOOKING_PAID,
|
||||
BOOKING_NO_SHOW_UPDATED,
|
||||
} from "./workflow-trigger.input";
|
||||
|
||||
export type UpdateWorkflowStepDto =
|
||||
@@ -119,6 +129,11 @@ export class UpdateWhatsAppAttendeePhoneWorkflowStepDto extends WorkflowPhoneWha
|
||||
OnCancelTriggerDto,
|
||||
OnCreationTriggerDto,
|
||||
OnRescheduleTriggerDto,
|
||||
OnNoShowUpdateTriggerDto,
|
||||
OnRejectedTriggerDto,
|
||||
OnRequestedTriggerDto,
|
||||
OnPaymentInitiatedTriggerDto,
|
||||
OnPaidTriggerDto,
|
||||
OnAfterCalVideoGuestsNoShowTriggerDto,
|
||||
OnAfterCalVideoHostsNoShowTriggerDto,
|
||||
UpdateEmailAddressWorkflowStepDto,
|
||||
@@ -155,6 +170,11 @@ export class UpdateWorkflowDto {
|
||||
{ $ref: getSchemaPath(OnRescheduleTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnAfterCalVideoGuestsNoShowTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnAfterCalVideoHostsNoShowTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnRejectedTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnRequestedTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnPaidTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnPaymentInitiatedTriggerDto) },
|
||||
{ $ref: getSchemaPath(OnNoShowUpdateTriggerDto) },
|
||||
],
|
||||
})
|
||||
@IsOptional()
|
||||
@@ -170,6 +190,11 @@ export class UpdateWorkflowDto {
|
||||
{ value: OnRescheduleTriggerDto, name: RESCHEDULE_EVENT },
|
||||
{ value: OnAfterCalVideoGuestsNoShowTriggerDto, name: AFTER_GUESTS_CAL_VIDEO_NO_SHOW },
|
||||
{ value: OnAfterCalVideoHostsNoShowTriggerDto, name: AFTER_HOSTS_CAL_VIDEO_NO_SHOW },
|
||||
{ value: OnRequestedTriggerDto, name: BOOKING_REQUESTED },
|
||||
{ value: OnRejectedTriggerDto, name: BOOKING_REJECTED },
|
||||
{ value: OnPaymentInitiatedTriggerDto, name: BOOKING_PAYMENT_INITIATED },
|
||||
{ value: OnPaidTriggerDto, name: BOOKING_PAID },
|
||||
{ value: OnNoShowUpdateTriggerDto, name: BOOKING_NO_SHOW_UPDATED },
|
||||
],
|
||||
},
|
||||
})
|
||||
@@ -179,6 +204,11 @@ export class UpdateWorkflowDto {
|
||||
| OnCreationTriggerDto
|
||||
| OnRescheduleTriggerDto
|
||||
| OnCancelTriggerDto
|
||||
| OnRejectedTriggerDto
|
||||
| OnRequestedTriggerDto
|
||||
| OnPaidTriggerDto
|
||||
| OnPaymentInitiatedTriggerDto
|
||||
| OnNoShowUpdateTriggerDto
|
||||
| OnAfterCalVideoGuestsNoShowTriggerDto
|
||||
| OnAfterCalVideoHostsNoShowTriggerDto;
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { WorkflowActions, WorkflowTemplates } from "@prisma/client";
|
||||
import { Type } from "class-transformer";
|
||||
import { IsNumber, IsBoolean, IsString, ValidateNested, IsIn } from "class-validator";
|
||||
|
||||
import { WorkflowActions, WorkflowTemplates } from "@calcom/platform-libraries";
|
||||
|
||||
export const EMAIL_HOST = "email_host";
|
||||
export const EMAIL_ATTENDEE = "email_attendee";
|
||||
export const EMAIL_ADDRESS = "email_address";
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { TimeUnit, WorkflowTriggerEvents } from "@prisma/client";
|
||||
import { Type } from "class-transformer";
|
||||
import { IsIn, IsNumber, IsString, ValidateNested } from "class-validator";
|
||||
|
||||
import { TimeUnit, WorkflowTriggerEvents } from "@calcom/platform-libraries";
|
||||
|
||||
export const BEFORE_EVENT = "beforeEvent";
|
||||
export const EVENT_CANCELLED = "eventCancelled";
|
||||
export const NEW_EVENT = "newEvent";
|
||||
@@ -10,6 +11,11 @@ export const AFTER_EVENT = "afterEvent";
|
||||
export const RESCHEDULE_EVENT = "rescheduleEvent";
|
||||
export const AFTER_HOSTS_CAL_VIDEO_NO_SHOW = "afterHostsCalVideoNoShow";
|
||||
export const AFTER_GUESTS_CAL_VIDEO_NO_SHOW = "afterGuestsCalVideoNoShow";
|
||||
export const BOOKING_REJECTED = "bookingRejected";
|
||||
export const BOOKING_REQUESTED = "bookingRequested";
|
||||
export const BOOKING_PAYMENT_INITIATED = "bookingPaymentInitiated";
|
||||
export const BOOKING_PAID = "bookingPaid";
|
||||
export const BOOKING_NO_SHOW_UPDATED = "bookingNoShowUpdated";
|
||||
export const WORKFLOW_TRIGGER_TYPES = [
|
||||
BEFORE_EVENT,
|
||||
EVENT_CANCELLED,
|
||||
@@ -18,6 +24,11 @@ export const WORKFLOW_TRIGGER_TYPES = [
|
||||
RESCHEDULE_EVENT,
|
||||
AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
|
||||
AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
|
||||
BOOKING_REJECTED,
|
||||
BOOKING_REQUESTED,
|
||||
BOOKING_PAYMENT_INITIATED,
|
||||
BOOKING_PAID,
|
||||
BOOKING_NO_SHOW_UPDATED,
|
||||
] as const;
|
||||
|
||||
export const WORKFLOW_TRIGGER_TO_ENUM = {
|
||||
@@ -28,6 +39,11 @@ export const WORKFLOW_TRIGGER_TO_ENUM = {
|
||||
[RESCHEDULE_EVENT]: WorkflowTriggerEvents.RESCHEDULE_EVENT,
|
||||
[AFTER_HOSTS_CAL_VIDEO_NO_SHOW]: WorkflowTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
|
||||
[AFTER_GUESTS_CAL_VIDEO_NO_SHOW]: WorkflowTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
|
||||
[BOOKING_REJECTED]: WorkflowTriggerEvents.BOOKING_REJECTED,
|
||||
[BOOKING_REQUESTED]: WorkflowTriggerEvents.BOOKING_REQUESTED,
|
||||
[BOOKING_PAYMENT_INITIATED]: WorkflowTriggerEvents.BOOKING_PAYMENT_INITIATED,
|
||||
[BOOKING_NO_SHOW_UPDATED]: WorkflowTriggerEvents.BOOKING_NO_SHOW_UPDATED,
|
||||
[BOOKING_PAID]: WorkflowTriggerEvents.BOOKING_PAID,
|
||||
} as const;
|
||||
|
||||
export const ENUM_TO_WORKFLOW_TRIGGER = {
|
||||
@@ -38,6 +54,11 @@ export const ENUM_TO_WORKFLOW_TRIGGER = {
|
||||
[WorkflowTriggerEvents.RESCHEDULE_EVENT]: RESCHEDULE_EVENT,
|
||||
[WorkflowTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW]: AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
|
||||
[WorkflowTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW]: AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
|
||||
[WorkflowTriggerEvents.BOOKING_REJECTED]: BOOKING_REJECTED,
|
||||
[WorkflowTriggerEvents.BOOKING_REQUESTED]: BOOKING_REQUESTED,
|
||||
[WorkflowTriggerEvents.BOOKING_PAYMENT_INITIATED]: BOOKING_PAYMENT_INITIATED,
|
||||
[WorkflowTriggerEvents.BOOKING_PAID]: BOOKING_PAID,
|
||||
[WorkflowTriggerEvents.BOOKING_NO_SHOW_UPDATED]: BOOKING_NO_SHOW_UPDATED,
|
||||
} as const;
|
||||
|
||||
export const HOUR = "hour";
|
||||
@@ -108,6 +129,41 @@ export class OnCancelTriggerDto {
|
||||
type: typeof EVENT_CANCELLED = EVENT_CANCELLED;
|
||||
}
|
||||
|
||||
export class OnRejectedTriggerDto {
|
||||
@ApiProperty({
|
||||
description: "Trigger type for the workflow",
|
||||
})
|
||||
type: typeof BOOKING_REJECTED = BOOKING_REJECTED;
|
||||
}
|
||||
|
||||
export class OnRequestedTriggerDto {
|
||||
@ApiProperty({
|
||||
description: "Trigger type for the workflow",
|
||||
})
|
||||
type: typeof BOOKING_REQUESTED = BOOKING_REQUESTED;
|
||||
}
|
||||
|
||||
export class OnPaymentInitiatedTriggerDto {
|
||||
@ApiProperty({
|
||||
description: "Trigger type for the workflow",
|
||||
})
|
||||
type: typeof BOOKING_PAYMENT_INITIATED = BOOKING_PAYMENT_INITIATED;
|
||||
}
|
||||
|
||||
export class OnPaidTriggerDto {
|
||||
@ApiProperty({
|
||||
description: "Trigger type for the workflow",
|
||||
})
|
||||
type: typeof BOOKING_PAID = BOOKING_PAID;
|
||||
}
|
||||
|
||||
export class OnNoShowUpdateTriggerDto {
|
||||
@ApiProperty({
|
||||
description: "Trigger type for the workflow",
|
||||
})
|
||||
type: typeof BOOKING_NO_SHOW_UPDATED = BOOKING_NO_SHOW_UPDATED;
|
||||
}
|
||||
|
||||
export class TriggerOffsetDTO {
|
||||
@ApiProperty({
|
||||
description: "Offset before/after the trigger time; required for BEFORE_EVENT and AFTER_EVENT only",
|
||||
|
||||
@@ -2,11 +2,12 @@ import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { TimeUnit, Workflow, WorkflowStep, WorkflowTriggerEvents } from "@prisma/client";
|
||||
|
||||
import { TimeUnit, WorkflowTriggerEvents } from "@calcom/platform-libraries";
|
||||
import { TUpdateInputSchema } from "@calcom/platform-libraries/workflows";
|
||||
import { updateWorkflow } from "@calcom/platform-libraries/workflows";
|
||||
import { PrismaClient } from "@calcom/prisma";
|
||||
import type { Workflow, WorkflowStep } from "@calcom/prisma/client";
|
||||
|
||||
export type WorkflowType = Workflow & { activeOn: { eventTypeId: number }[]; steps: WorkflowStep[] };
|
||||
|
||||
|
||||
@@ -9132,6 +9132,8 @@
|
||||
{
|
||||
"name": "credentialId",
|
||||
"in": "query",
|
||||
"description": "The ID of the user's calendar credential used to access the calendar. Retrieve this from your connected calendar credentials via the `/v2/credentials` endpoint.",
|
||||
"example": 135,
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "number"
|
||||
@@ -9140,6 +9142,8 @@
|
||||
{
|
||||
"name": "externalId",
|
||||
"in": "query",
|
||||
"description": "The external calendar identifier from the calendar provider (e.g., email address for Google Calendar). This is returned when listing connected calendars.",
|
||||
"example": "user@gmail.com",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
@@ -22554,7 +22558,12 @@
|
||||
"afterEvent",
|
||||
"rescheduleEvent",
|
||||
"afterHostsCalVideoNoShow",
|
||||
"afterGuestsCalVideoNoShow"
|
||||
"afterGuestsCalVideoNoShow",
|
||||
"bookingRejected",
|
||||
"bookingRequested",
|
||||
"bookingPaymentInitiated",
|
||||
"bookingPaid",
|
||||
"bookingNoShowUpdated"
|
||||
]
|
||||
},
|
||||
"offset": {
|
||||
@@ -22923,6 +22932,71 @@
|
||||
"type"
|
||||
]
|
||||
},
|
||||
"OnNoShowUpdateTriggerDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"default": "bookingNoShowUpdated",
|
||||
"description": "Trigger type for the workflow"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"type"
|
||||
]
|
||||
},
|
||||
"OnRejectedTriggerDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"default": "bookingRejected",
|
||||
"description": "Trigger type for the workflow"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"type"
|
||||
]
|
||||
},
|
||||
"OnRequestedTriggerDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"default": "bookingRequested",
|
||||
"description": "Trigger type for the workflow"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"type"
|
||||
]
|
||||
},
|
||||
"OnPaymentInitiatedTriggerDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"default": "bookingPaymentInitiated",
|
||||
"description": "Trigger type for the workflow"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"type"
|
||||
]
|
||||
},
|
||||
"OnPaidTriggerDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"default": "bookingPaid",
|
||||
"description": "Trigger type for the workflow"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"type"
|
||||
]
|
||||
},
|
||||
"OnAfterCalVideoGuestsNoShowTriggerDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -23642,6 +23716,21 @@
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/OnAfterCalVideoHostsNoShowTriggerDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/OnRejectedTriggerDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/OnRequestedTriggerDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/OnPaidTriggerDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/OnPaymentInitiatedTriggerDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/OnNoShowUpdateTriggerDto"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -24298,6 +24387,21 @@
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/OnAfterCalVideoHostsNoShowTriggerDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/OnRejectedTriggerDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/OnRequestedTriggerDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/OnPaidTriggerDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/OnPaymentInitiatedTriggerDto"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/OnNoShowUpdateTriggerDto"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -15,7 +15,6 @@ export class ApiKeysRepositoryFixture {
|
||||
async createApiKey(userId: number, expiresAt: Date | null, teamId?: number) {
|
||||
const keyString = randomBytes(16).toString("hex");
|
||||
const hashedKey = createHash("sha256").update(keyString).digest("hex");
|
||||
console.log("createApiKey Fixutre", { hashedKey, keyString });
|
||||
const apiKey = await this.prismaWriteClient.apiKey.create({
|
||||
data: {
|
||||
userId,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { TestingModule } from "@nestjs/testing";
|
||||
import { Membership, MembershipRole, Prisma, Team, User } from "@prisma/client";
|
||||
import { Membership, Prisma, Team, User } from "@prisma/client";
|
||||
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
export class MembershipRepositoryFixture {
|
||||
private prismaReadClient: PrismaReadService["prisma"];
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
const Page = () => {
|
||||
redirect("/apps/installed/calendar");
|
||||
};
|
||||
|
||||
export default Page;
|
||||
@@ -1,7 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
const ServerPage = async () => {
|
||||
redirect("/apps/routing-forms/forms");
|
||||
};
|
||||
|
||||
export default ServerPage;
|
||||
@@ -3,7 +3,7 @@ import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
import Link from "next/link";
|
||||
import { z } from "zod";
|
||||
|
||||
import { IdentityProvider } from "@calcom/prisma/client";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export const generateMetadata = async () =>
|
||||
await _generateMetadata(
|
||||
(t) => t("apps"),
|
||||
(t) => t("admin_apps_description"),
|
||||
undefined,
|
||||
undefined,
|
||||
"/settings/admin/apps"
|
||||
);
|
||||
|
||||
const Page = () => {
|
||||
redirect("/settings/admin/apps/calendar");
|
||||
};
|
||||
|
||||
export default Page;
|
||||
+17
-12
@@ -117,6 +117,7 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
|
||||
{
|
||||
name: "admin_api",
|
||||
href: "https://cal.com/docs/enterprise-features/api/api-reference/bookings#admin-access",
|
||||
isExternalLink: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -181,14 +182,18 @@ const organizationAdminKeys = [
|
||||
"delegation_credential",
|
||||
];
|
||||
|
||||
export interface SettingsPermissions {
|
||||
canViewRoles?: boolean;
|
||||
}
|
||||
|
||||
const useTabs = ({
|
||||
isDelegationCredentialEnabled,
|
||||
isPbacEnabled,
|
||||
canViewRoles,
|
||||
permissions,
|
||||
}: {
|
||||
isDelegationCredentialEnabled: boolean;
|
||||
isPbacEnabled: boolean;
|
||||
canViewRoles?: boolean;
|
||||
permissions?: SettingsPermissions;
|
||||
}) => {
|
||||
const session = useSession();
|
||||
const { data: user } = trpc.viewer.me.get.useQuery({ includePasswordAdded: true });
|
||||
@@ -227,7 +232,7 @@ const useTabs = ({
|
||||
|
||||
// Add pbac menu item only if feature flag is enabled AND user has permission to view roles
|
||||
// This prevents showing the menu item when user has no organization permissions
|
||||
if (isPbacEnabled && canViewRoles) {
|
||||
if (isPbacEnabled && permissions?.canViewRoles) {
|
||||
newArray.push({
|
||||
name: "roles_and_permissions",
|
||||
href: "/settings/organizations/roles",
|
||||
@@ -294,7 +299,7 @@ interface SettingsSidebarContainerProps {
|
||||
navigationIsOpenedOnMobile?: boolean;
|
||||
bannersHeight?: number;
|
||||
teamFeatures?: Record<number, TeamFeatures>;
|
||||
canViewRoles?: boolean;
|
||||
permissions?: SettingsPermissions;
|
||||
}
|
||||
|
||||
const TeamRolesNavItem = ({
|
||||
@@ -487,7 +492,7 @@ const SettingsSidebarContainer = ({
|
||||
navigationIsOpenedOnMobile,
|
||||
bannersHeight,
|
||||
teamFeatures,
|
||||
canViewRoles,
|
||||
permissions,
|
||||
}: SettingsSidebarContainerProps) => {
|
||||
const searchParams = useCompatSearchParams();
|
||||
const orgBranding = useOrgBranding();
|
||||
@@ -517,7 +522,7 @@ const SettingsSidebarContainer = ({
|
||||
const tabsWithPermissions = useTabs({
|
||||
isDelegationCredentialEnabled,
|
||||
isPbacEnabled,
|
||||
canViewRoles,
|
||||
permissions,
|
||||
});
|
||||
|
||||
const { data: otherTeams } = trpc.viewer.organizations.listOtherTeams.useQuery(undefined, {
|
||||
@@ -792,13 +797,13 @@ export type SettingsLayoutProps = {
|
||||
children: React.ReactNode;
|
||||
containerClassName?: string;
|
||||
teamFeatures?: Record<number, TeamFeatures>;
|
||||
canViewRoles?: boolean;
|
||||
permissions?: SettingsPermissions;
|
||||
} & ComponentProps<typeof Shell>;
|
||||
|
||||
export default function SettingsLayoutAppDirClient({
|
||||
children,
|
||||
teamFeatures,
|
||||
canViewRoles,
|
||||
permissions,
|
||||
...rest
|
||||
}: SettingsLayoutProps) {
|
||||
const pathname = usePathname();
|
||||
@@ -833,7 +838,7 @@ export default function SettingsLayoutAppDirClient({
|
||||
sideContainerOpen={sideContainerOpen}
|
||||
setSideContainerOpen={setSideContainerOpen}
|
||||
teamFeatures={teamFeatures}
|
||||
canViewRoles={canViewRoles}
|
||||
permissions={permissions}
|
||||
/>
|
||||
}
|
||||
drawerState={state}
|
||||
@@ -856,7 +861,7 @@ type SidebarContainerElementProps = {
|
||||
bannersHeight?: number;
|
||||
setSideContainerOpen: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
teamFeatures?: Record<number, TeamFeatures>;
|
||||
canViewRoles?: boolean;
|
||||
permissions?: SettingsPermissions;
|
||||
};
|
||||
|
||||
const SidebarContainerElement = ({
|
||||
@@ -864,7 +869,7 @@ const SidebarContainerElement = ({
|
||||
bannersHeight,
|
||||
setSideContainerOpen,
|
||||
teamFeatures,
|
||||
canViewRoles,
|
||||
permissions,
|
||||
}: SidebarContainerElementProps) => {
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
@@ -881,7 +886,7 @@ const SidebarContainerElement = ({
|
||||
navigationIsOpenedOnMobile={sideContainerOpen}
|
||||
bannersHeight={bannersHeight}
|
||||
teamFeatures={teamFeatures}
|
||||
canViewRoles={canViewRoles}
|
||||
permissions={permissions}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -67,7 +67,11 @@ export default async function SettingsLayoutAppDir(props: SettingsLayoutProps) {
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsLayoutAppDirClient {...props} teamFeatures={teamFeatures ?? {}} canViewRoles={canViewRoles} />
|
||||
<SettingsLayoutAppDirClient
|
||||
{...props}
|
||||
teamFeatures={teamFeatures ?? {}}
|
||||
permissions={{ canViewRoles }}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
+7
-5
@@ -21,11 +21,13 @@ const Page = async () => {
|
||||
createRouterCaller(appsRouter),
|
||||
]);
|
||||
|
||||
const connectedCalendars = await calendarsCaller.connectedCalendars();
|
||||
const installedCalendars = await appsCaller.integrations({
|
||||
variant: "calendar",
|
||||
onlyInstalled: true,
|
||||
});
|
||||
const [connectedCalendars, installedCalendars] = await Promise.all([
|
||||
calendarsCaller.connectedCalendars(),
|
||||
appsCaller.integrations({
|
||||
variant: "calendar",
|
||||
onlyInstalled: true,
|
||||
}),
|
||||
]);
|
||||
return (
|
||||
<CalendarListContainer connectedCalendars={connectedCalendars} installedCalendars={installedCalendars} />
|
||||
);
|
||||
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import { SkeletonLoader } from "@calcom/atoms/connect/conferencing-apps/ConferencingAppsViewWebWrapper";
|
||||
|
||||
export default function Loading() {
|
||||
return <SkeletonLoader />;
|
||||
}
|
||||
+21
-1
@@ -1,6 +1,9 @@
|
||||
import { createRouterCaller } from "app/_trpc/context";
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
|
||||
import { ConferencingAppsViewWebWrapper } from "@calcom/atoms/connect/conferencing-apps/ConferencingAppsViewWebWrapper";
|
||||
import { appsRouter } from "@calcom/trpc/server/routers/viewer/apps/_router";
|
||||
import { eventTypesRouter } from "@calcom/trpc/server/routers/viewer/eventTypes/_router";
|
||||
|
||||
export const generateMetadata = async () =>
|
||||
await _generateMetadata(
|
||||
@@ -12,7 +15,24 @@ export const generateMetadata = async () =>
|
||||
);
|
||||
|
||||
const Page = async () => {
|
||||
return <ConferencingAppsViewWebWrapper />;
|
||||
const [appsCaller, eventTypesCaller] = await Promise.all([
|
||||
createRouterCaller(appsRouter),
|
||||
createRouterCaller(eventTypesRouter),
|
||||
]);
|
||||
|
||||
const [integrations, defaultConferencingApp, eventTypesQueryData] = await Promise.all([
|
||||
appsCaller.integrations({ variant: "conferencing", onlyInstalled: true }),
|
||||
appsCaller.getUsersDefaultConferencingApp(),
|
||||
eventTypesCaller.bulkEventFetch(),
|
||||
]);
|
||||
|
||||
return (
|
||||
<ConferencingAppsViewWebWrapper
|
||||
integrations={integrations}
|
||||
defaultConferencingApp={defaultConferencingApp}
|
||||
eventTypes={eventTypesQueryData?.eventTypes ?? []}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default Page;
|
||||
|
||||
+2
-2
@@ -21,9 +21,9 @@ export const generateMetadata = async () =>
|
||||
);
|
||||
|
||||
const Page = async () => {
|
||||
const t = await getTranslate();
|
||||
const [t, _headers, _cookies] = await Promise.all([getTranslate(), headers(), cookies()]);
|
||||
|
||||
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
|
||||
const session = await getServerSession({ req: buildLegacyRequest(_headers, _cookies) });
|
||||
|
||||
if (!session?.user.id || !session?.user.profile?.organizationId || !session?.user.org) {
|
||||
return redirect("/settings/profile");
|
||||
|
||||
+67
-51
@@ -3,12 +3,16 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import type { Resource } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { PERMISSION_REGISTRY, CrudAction } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import {
|
||||
Scope,
|
||||
CrudAction,
|
||||
getPermissionsForScope,
|
||||
} from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Checkbox, Label } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
import { Checkbox, Label } from "@calcom/ui/form";
|
||||
|
||||
import { usePermissions } from "./usePermissions";
|
||||
|
||||
@@ -17,6 +21,7 @@ interface AdvancedPermissionGroupProps {
|
||||
selectedPermissions: string[];
|
||||
onChange: (permissions: string[]) => void;
|
||||
disabled?: boolean;
|
||||
scope?: Scope;
|
||||
}
|
||||
|
||||
const INTERNAL_DATAACCESS_KEY = "_resource";
|
||||
@@ -26,21 +31,31 @@ export function AdvancedPermissionGroup({
|
||||
selectedPermissions,
|
||||
onChange,
|
||||
disabled,
|
||||
scope = Scope.Organization,
|
||||
}: AdvancedPermissionGroupProps) {
|
||||
const { t } = useLocale();
|
||||
const { toggleSinglePermission, toggleResourcePermissionLevel } = usePermissions();
|
||||
const resourceConfig = PERMISSION_REGISTRY[resource];
|
||||
const { toggleSinglePermission, toggleResourcePermissionLevel } = usePermissions(scope);
|
||||
const scopedRegistry = getPermissionsForScope(scope);
|
||||
const resourceConfig = scopedRegistry[resource];
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
|
||||
const isAllResources = resource === "*";
|
||||
|
||||
// Early return if resource is not in the scoped registry (and not the special "*" resource)
|
||||
if (!isAllResources && !resourceConfig) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const allResourcesSelected = selectedPermissions.includes("*.*");
|
||||
|
||||
// Get all possible permissions for this resource
|
||||
const allPermissions = isAllResources
|
||||
? ["*.*"]
|
||||
: Object.entries(resourceConfig)
|
||||
: resourceConfig
|
||||
? Object.entries(resourceConfig)
|
||||
.filter(([action]) => action !== INTERNAL_DATAACCESS_KEY)
|
||||
.map(([action]) => `${resource}.${action}`);
|
||||
.map(([action]) => `${resource}.${action}`)
|
||||
: [];
|
||||
|
||||
// Check if all permissions for this resource are selected
|
||||
const isAllSelected = isAllResources
|
||||
@@ -99,7 +114,7 @@ export function AdvancedPermissionGroup({
|
||||
<span
|
||||
className="text-default cursor-pointer text-sm font-medium leading-none"
|
||||
onClick={() => setIsExpanded(!isExpanded)}>
|
||||
{t(resourceConfig._resource?.i18nKey || "")}
|
||||
{t(resourceConfig?._resource?.i18nKey || "")}
|
||||
</span>
|
||||
<span
|
||||
className="text-muted cursor-pointer text-sm font-medium leading-none"
|
||||
@@ -113,56 +128,57 @@ export function AdvancedPermissionGroup({
|
||||
className="bg-default border-muted m-1 flex flex-col gap-2.5 rounded-xl border p-3"
|
||||
onClick={(e) => e.stopPropagation()} // Stop clicks in the permission list from affecting parent
|
||||
>
|
||||
{Object.entries(resourceConfig).map(([action, actionConfig]) => {
|
||||
const permission = `${resource}.${action}`;
|
||||
{resourceConfig &&
|
||||
Object.entries(resourceConfig).map(([action, actionConfig]) => {
|
||||
const permission = `${resource}.${action}`;
|
||||
|
||||
if (action === INTERNAL_DATAACCESS_KEY) {
|
||||
return null;
|
||||
}
|
||||
if (action === INTERNAL_DATAACCESS_KEY) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isChecked = selectedPermissions.includes(permission);
|
||||
const isReadPermission = action === CrudAction.Read;
|
||||
const isAutoEnabled = isReadAutoEnabled(action);
|
||||
const isChecked = selectedPermissions.includes(permission);
|
||||
const isReadPermission = action === CrudAction.Read;
|
||||
const isAutoEnabled = isReadAutoEnabled(action);
|
||||
|
||||
return (
|
||||
<div key={action} className="flex items-center">
|
||||
<Checkbox
|
||||
id={permission}
|
||||
checked={isChecked}
|
||||
className="mr-2"
|
||||
onCheckedChange={(checked) => {
|
||||
if (!disabled) {
|
||||
onChange(toggleSinglePermission(permission, !!checked, selectedPermissions));
|
||||
}
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()} // Stop checkbox clicks from affecting parent
|
||||
disabled={disabled}
|
||||
/>
|
||||
<div
|
||||
className="flex items-center gap-2"
|
||||
onClick={(e) => e.stopPropagation()} // Stop label clicks from affecting parent
|
||||
>
|
||||
<Label htmlFor={permission} className="mb-0">
|
||||
<span className={classNames(isAutoEnabled && "text-muted-foreground")}>
|
||||
{t(actionConfig?.i18nKey || "")}
|
||||
return (
|
||||
<div key={action} className="flex items-center">
|
||||
<Checkbox
|
||||
id={permission}
|
||||
checked={isChecked}
|
||||
className="mr-2"
|
||||
onCheckedChange={(checked) => {
|
||||
if (!disabled) {
|
||||
onChange(toggleSinglePermission(permission, !!checked, selectedPermissions));
|
||||
}
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()} // Stop checkbox clicks from affecting parent
|
||||
disabled={disabled}
|
||||
/>
|
||||
<div
|
||||
className="flex items-center gap-2"
|
||||
onClick={(e) => e.stopPropagation()} // Stop label clicks from affecting parent
|
||||
>
|
||||
<Label htmlFor={permission} className="mb-0">
|
||||
<span className={classNames(isAutoEnabled && "text-muted-foreground")}>
|
||||
{t(actionConfig?.i18nKey || "")}
|
||||
</span>
|
||||
</Label>
|
||||
<span className="text-sm text-gray-500">
|
||||
{t(
|
||||
actionConfig && "descriptionI18nKey" in actionConfig
|
||||
? actionConfig.descriptionI18nKey
|
||||
: ""
|
||||
)}
|
||||
</span>
|
||||
</Label>
|
||||
<span className="text-sm text-gray-500">
|
||||
{t(
|
||||
actionConfig && "descriptionI18nKey" in actionConfig
|
||||
? actionConfig.descriptionI18nKey
|
||||
: ""
|
||||
{isAutoEnabled && (
|
||||
<Tooltip content={t("read_permission_auto_enabled_tooltip")}>
|
||||
<Icon name="info" className="text-muted-foreground h-3 w-3" />
|
||||
</Tooltip>
|
||||
)}
|
||||
</span>
|
||||
{isAutoEnabled && (
|
||||
<Tooltip content={t("read_permission_auto_enabled_tooltip")}>
|
||||
<Icon name="info" className="text-muted-foreground h-3 w-3" />
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}{" "}
|
||||
);
|
||||
})}{" "}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/button";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
|
||||
import { useRoleSheetState } from "../hooks/useRoleQueryStates";
|
||||
|
||||
|
||||
+4
-6
@@ -14,10 +14,10 @@ import {
|
||||
} from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/button";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Form, TextField, Checkbox, Label } from "@calcom/ui/components/form";
|
||||
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from "@calcom/ui/components/sheet";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Form, TextField, Checkbox, Label } from "@calcom/ui/form";
|
||||
|
||||
import { revalidateTeamRoles } from "../actions";
|
||||
import { AdvancedPermissionGroup } from "./AdvancedPermissionGroup";
|
||||
@@ -145,10 +145,6 @@ export function RoleSheet({ role, open, onOpenChange, teamId, scope = Scope.Orga
|
||||
});
|
||||
|
||||
const onSubmit = (values: FormValues) => {
|
||||
// Store the color in localStorage
|
||||
const roleKey = isEditing && role ? role.id : `new_role_${values.name}`;
|
||||
localStorage.setItem(`role_color_${roleKey}`, values.color);
|
||||
|
||||
if (isEditing && role) {
|
||||
updateMutation.mutate({
|
||||
teamId,
|
||||
@@ -224,6 +220,7 @@ export function RoleSheet({ role, open, onOpenChange, teamId, scope = Scope.Orga
|
||||
selectedPermissions={permissions}
|
||||
onChange={(newPermissions) => form.setValue("permissions", newPermissions)}
|
||||
disabled={isSystemRole}
|
||||
scope={scope}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -247,6 +244,7 @@ export function RoleSheet({ role, open, onOpenChange, teamId, scope = Scope.Orga
|
||||
permissions={permissions}
|
||||
onChange={(newPermissions) => form.setValue("permissions", newPermissions)}
|
||||
disabled={isSystemRole}
|
||||
scope={scope}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
+2
-2
@@ -2,9 +2,9 @@
|
||||
|
||||
import type { Scope } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Badge } from "@calcom/ui/badge";
|
||||
import { Button } from "@calcom/ui/button";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import {
|
||||
Dropdown,
|
||||
DropdownMenuContent,
|
||||
|
||||
+4
-2
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import type { Resource } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import type { Resource, Scope } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { PERMISSION_REGISTRY } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { ToggleGroup } from "@calcom/ui/components/form";
|
||||
@@ -13,6 +13,7 @@ interface SimplePermissionItemProps {
|
||||
permissions: string[];
|
||||
onChange: (permissions: string[]) => void;
|
||||
disabled?: boolean;
|
||||
scope?: Scope;
|
||||
}
|
||||
|
||||
export function SimplePermissionItem({
|
||||
@@ -20,9 +21,10 @@ export function SimplePermissionItem({
|
||||
permissions,
|
||||
onChange,
|
||||
disabled,
|
||||
scope,
|
||||
}: SimplePermissionItemProps) {
|
||||
const { t } = useLocale();
|
||||
const { getResourcePermissionLevel, toggleResourcePermissionLevel } = usePermissions();
|
||||
const { getResourcePermissionLevel, toggleResourcePermissionLevel } = usePermissions(scope);
|
||||
|
||||
const isAllResources = resource === "*";
|
||||
const options = isAllResources
|
||||
|
||||
-12
@@ -44,17 +44,5 @@ describe("usePermissions", () => {
|
||||
|
||||
expect(getResourcePermissionLevel("eventType", permissions)).toBe("all");
|
||||
});
|
||||
|
||||
it("should return 'all' for resource with manage permission", () => {
|
||||
const permissions = ["eventType.manage"];
|
||||
|
||||
expect(getResourcePermissionLevel("eventType", permissions)).toBe("all");
|
||||
});
|
||||
|
||||
it("should return 'all' for resource with manage permission even if other permissions are missing", () => {
|
||||
const permissions = ["eventType.manage", "eventType.read"]; // Has manage and read, but missing create, update, delete
|
||||
|
||||
expect(getResourcePermissionLevel("eventType", permissions)).toBe("all");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+35
-43
@@ -1,5 +1,12 @@
|
||||
import { CrudAction } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { PERMISSION_REGISTRY } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { CrudAction, Scope } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import {
|
||||
PERMISSION_REGISTRY,
|
||||
getPermissionsForScope,
|
||||
} from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import {
|
||||
getTransitiveDependencies,
|
||||
getTransitiveDependents,
|
||||
} from "@calcom/features/pbac/utils/permissionTraversal";
|
||||
|
||||
export type PermissionLevel = "none" | "read" | "all";
|
||||
|
||||
@@ -14,10 +21,11 @@ interface UsePermissionsReturn {
|
||||
toggleSinglePermission: (permission: string, enabled: boolean, currentPermissions: string[]) => string[];
|
||||
}
|
||||
|
||||
export function usePermissions(): UsePermissionsReturn {
|
||||
export function usePermissions(scope: Scope = Scope.Organization): UsePermissionsReturn {
|
||||
const getAllPossiblePermissions = () => {
|
||||
const permissions: string[] = [];
|
||||
Object.entries(PERMISSION_REGISTRY).forEach(([resource, config]) => {
|
||||
const scopedRegistry = getPermissionsForScope(scope);
|
||||
Object.entries(scopedRegistry).forEach(([resource, config]) => {
|
||||
if (resource !== "*") {
|
||||
Object.keys(config)
|
||||
.filter((action) => !action.startsWith("_"))
|
||||
@@ -30,7 +38,8 @@ export function usePermissions(): UsePermissionsReturn {
|
||||
};
|
||||
|
||||
const hasAllPermissions = (permissions: string[]) => {
|
||||
return Object.entries(PERMISSION_REGISTRY).every(([resource, config]) => {
|
||||
const scopedRegistry = getPermissionsForScope(scope);
|
||||
return Object.entries(scopedRegistry).every(([resource, config]) => {
|
||||
if (resource === "*") return true;
|
||||
return Object.keys(config)
|
||||
.filter((action) => !action.startsWith("_"))
|
||||
@@ -51,20 +60,14 @@ export function usePermissions(): UsePermissionsReturn {
|
||||
return "all";
|
||||
}
|
||||
|
||||
// Check if user has manage permission for this resource
|
||||
const hasManagePermission = permissions.includes(`${resource}.manage`);
|
||||
if (hasManagePermission) {
|
||||
return "all";
|
||||
}
|
||||
|
||||
// Filter out internal keys like _resource and manage when checking for individual permissions
|
||||
const crudPermissions = Object.keys(resourceConfig)
|
||||
.filter((action) => !action.startsWith("_") && action !== "manage")
|
||||
// Filter out internal keys like _resource when checking permissions
|
||||
const allResourcePerms = Object.keys(resourceConfig)
|
||||
.filter((action) => !action.startsWith("_"))
|
||||
.map((action) => `${resource}.${action}`);
|
||||
const hasAllCrudPerms = crudPermissions.every((p) => permissions.includes(p));
|
||||
const hasAllPerms = allResourcePerms.every((p) => permissions.includes(p));
|
||||
const hasReadPerm = permissions.includes(`${resource}.${CrudAction.Read}`);
|
||||
|
||||
if (hasAllCrudPerms) return "all";
|
||||
if (hasAllPerms) return "all";
|
||||
if (hasReadPerm) return "read";
|
||||
return "none";
|
||||
};
|
||||
@@ -87,7 +90,8 @@ export function usePermissions(): UsePermissionsReturn {
|
||||
} else {
|
||||
// Filter out current resource permissions
|
||||
newPermissions = newPermissions.filter((p) => !p.startsWith(`${resource}.`));
|
||||
const resourceConfig = PERMISSION_REGISTRY[resource as keyof typeof PERMISSION_REGISTRY];
|
||||
const scopedRegistry = getPermissionsForScope(scope);
|
||||
const resourceConfig = scopedRegistry[resource as keyof typeof scopedRegistry];
|
||||
|
||||
if (!resourceConfig) return currentPermissions;
|
||||
|
||||
@@ -135,34 +139,22 @@ export function usePermissions(): UsePermissionsReturn {
|
||||
// Add the requested permission
|
||||
newPermissions.push(permission);
|
||||
|
||||
// If enabling create, update, or delete, automatically enable read permission
|
||||
if (action === CrudAction.Create || action === CrudAction.Update || action === CrudAction.Delete) {
|
||||
const readPermission = `${resource}.${CrudAction.Read}`;
|
||||
if (!newPermissions.includes(readPermission)) {
|
||||
newPermissions.push(readPermission);
|
||||
// Add all transitive dependencies
|
||||
const dependencies = getTransitiveDependencies(permission);
|
||||
dependencies.forEach((dependency) => {
|
||||
if (!newPermissions.includes(dependency)) {
|
||||
newPermissions.push(dependency);
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// When disabling a permission, check if we need to disable related permissions
|
||||
if (action === CrudAction.Read) {
|
||||
// If disabling read, also disable create, update, and delete since they depend on read
|
||||
const dependentActions = [CrudAction.Create, CrudAction.Update, CrudAction.Delete];
|
||||
dependentActions.forEach((dependentAction) => {
|
||||
const dependentPermission = `${resource}.${dependentAction}`;
|
||||
newPermissions = newPermissions.filter((p) => p !== dependentPermission);
|
||||
});
|
||||
} else if (
|
||||
action === CrudAction.Create ||
|
||||
action === CrudAction.Update ||
|
||||
action === CrudAction.Delete
|
||||
) {
|
||||
// If disabling create, update, or delete, just remove that specific permission
|
||||
// Read permission remains enabled
|
||||
newPermissions = newPermissions.filter((p) => p !== permission);
|
||||
} else {
|
||||
// For other actions (custom actions), just remove the specific permission
|
||||
newPermissions = newPermissions.filter((p) => p !== permission);
|
||||
}
|
||||
// When disabling a permission, first remove the permission itself
|
||||
newPermissions = newPermissions.filter((p) => p !== permission);
|
||||
|
||||
// Remove all transitive dependents
|
||||
const dependents = getTransitiveDependents(permission);
|
||||
dependents.forEach((dependent) => {
|
||||
newPermissions = newPermissions.filter((p) => p !== dependent);
|
||||
});
|
||||
}
|
||||
|
||||
// Only add *.* back if all permissions are now selected
|
||||
|
||||
+69
-2
@@ -1,13 +1,21 @@
|
||||
import { createRouterCaller } from "app/_trpc/context";
|
||||
import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
import { unstable_cache } from "next/cache";
|
||||
import { headers, cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { Resource, CustomAction } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
|
||||
import { RoleManagementFactory } from "@calcom/features/pbac/services/role-management.factory";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
import { PrismaAttributeRepository } from "@calcom/lib/server/repository/PrismaAttributeRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { viewerTeamsRouter } from "@calcom/trpc/server/routers/viewer/teams/_router";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
import { TeamMembersView } from "~/teams/team-members-view";
|
||||
|
||||
export const generateMetadata = async ({ params }: { params: Promise<{ id: string }> }) =>
|
||||
@@ -54,6 +62,12 @@ const Page = async ({ params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params;
|
||||
const teamId = parseInt(id);
|
||||
|
||||
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
|
||||
|
||||
if (!session?.user.id) {
|
||||
return redirect("/auth/login");
|
||||
}
|
||||
|
||||
const teamCaller = await createRouterCaller(viewerTeamsRouter);
|
||||
const team = await teamCaller.get({ teamId });
|
||||
|
||||
@@ -70,6 +84,54 @@ const Page = async ({ params }: { params: Promise<{ id: string }> }) => {
|
||||
getCachedTeamAttributes(organizationId),
|
||||
]);
|
||||
|
||||
const fallbackRolesCanListMembers: MembershipRole[] = [MembershipRole.ADMIN, MembershipRole.OWNER];
|
||||
|
||||
// If the team is not private we allow members to list other members
|
||||
if (!team.isPrivate) {
|
||||
fallbackRolesCanListMembers.push(MembershipRole.MEMBER);
|
||||
}
|
||||
|
||||
// Get specific PBAC permissions for team member actions
|
||||
const permissions = await getSpecificPermissions({
|
||||
userId: session.user.id,
|
||||
teamId: teamId,
|
||||
resource: Resource.Team,
|
||||
userRole: team.membership.role,
|
||||
actions: [
|
||||
CustomAction.Invite,
|
||||
CustomAction.ChangeMemberRole,
|
||||
CustomAction.Remove,
|
||||
CustomAction.ListMembers,
|
||||
CustomAction.Impersonate,
|
||||
],
|
||||
fallbackRoles: {
|
||||
[CustomAction.Invite]: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
[CustomAction.ChangeMemberRole]: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
[CustomAction.Remove]: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
[CustomAction.ListMembers]: {
|
||||
roles: fallbackRolesCanListMembers,
|
||||
},
|
||||
[CustomAction.Impersonate]: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Map specific permissions to member actions
|
||||
const memberPermissions = {
|
||||
canListMembers: permissions[CustomAction.ListMembers],
|
||||
canInvite: permissions[CustomAction.Invite],
|
||||
canChangeMemberRole: permissions[CustomAction.ChangeMemberRole],
|
||||
canRemove: permissions[CustomAction.Remove],
|
||||
canImpersonate: permissions[CustomAction.Impersonate],
|
||||
};
|
||||
|
||||
const facetedTeamValues = {
|
||||
roles,
|
||||
teams: [team],
|
||||
@@ -84,7 +146,12 @@ const Page = async ({ params }: { params: Promise<{ id: string }> }) => {
|
||||
|
||||
return (
|
||||
<SettingsHeader title={t("team_members")} description={t("members_team_description")}>
|
||||
<TeamMembersView team={team} facetedTeamValues={facetedTeamValues} attributes={attributes} />
|
||||
<TeamMembersView
|
||||
team={team}
|
||||
facetedTeamValues={facetedTeamValues}
|
||||
attributes={attributes}
|
||||
permissions={memberPermissions}
|
||||
/>
|
||||
</SettingsHeader>
|
||||
);
|
||||
};
|
||||
|
||||
+69
-4
@@ -1,12 +1,20 @@
|
||||
import { createRouterCaller } from "app/_trpc/context";
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
import { unstable_cache } from "next/cache";
|
||||
import { headers, cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { Resource, CustomAction } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
|
||||
import { RoleManagementFactory } from "@calcom/features/pbac/services/role-management.factory";
|
||||
import { PrismaAttributeRepository } from "@calcom/lib/server/repository/PrismaAttributeRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { viewerOrganizationsRouter } from "@calcom/trpc/server/routers/viewer/organizations/_router";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
import { MembersView } from "~/members/members-view";
|
||||
|
||||
export const generateMetadata = async () =>
|
||||
@@ -38,11 +46,62 @@ const getCachedRoles = unstable_cache(
|
||||
);
|
||||
|
||||
const Page = async () => {
|
||||
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
|
||||
|
||||
if (!session?.user.id || !session?.user.profile?.organizationId || !session?.user.org) {
|
||||
return redirect("/settings/profile");
|
||||
}
|
||||
|
||||
const orgCaller = await createRouterCaller(viewerOrganizationsRouter);
|
||||
const [org, teams] = await Promise.all([orgCaller.listCurrent(), orgCaller.getTeams()]);
|
||||
const attributes = await getCachedAttributes(org.id);
|
||||
const [attributes, roles] = await Promise.all([getCachedAttributes(org.id), getCachedRoles(org.id)]);
|
||||
|
||||
const roles = await getCachedRoles(org.id);
|
||||
const fallbackRolesThatCanSeeMembers: MembershipRole[] = [MembershipRole.ADMIN, MembershipRole.OWNER];
|
||||
|
||||
if (!org?.isPrivate) {
|
||||
fallbackRolesThatCanSeeMembers.push(MembershipRole.MEMBER);
|
||||
}
|
||||
|
||||
// Get specific PBAC permissions for organization member actions
|
||||
const permissions = await getSpecificPermissions({
|
||||
userId: session.user.id,
|
||||
teamId: session.user.profile.organizationId,
|
||||
resource: Resource.Organization,
|
||||
userRole: session.user.org.role,
|
||||
actions: [
|
||||
CustomAction.ListMembers,
|
||||
CustomAction.Invite,
|
||||
CustomAction.ChangeMemberRole,
|
||||
CustomAction.Remove,
|
||||
CustomAction.Impersonate,
|
||||
],
|
||||
fallbackRoles: {
|
||||
[CustomAction.ListMembers]: {
|
||||
roles: fallbackRolesThatCanSeeMembers,
|
||||
},
|
||||
[CustomAction.Invite]: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
[CustomAction.ChangeMemberRole]: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
[CustomAction.Remove]: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
[CustomAction.Impersonate]: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Map specific permissions to member actions
|
||||
const memberPermissions = {
|
||||
canListMembers: permissions[CustomAction.ListMembers],
|
||||
canInvite: permissions[CustomAction.Invite],
|
||||
canChangeMemberRole: permissions[CustomAction.ChangeMemberRole],
|
||||
canRemove: permissions[CustomAction.Remove],
|
||||
canImpersonate: permissions[CustomAction.Impersonate],
|
||||
};
|
||||
|
||||
const facetedTeamValues = {
|
||||
roles,
|
||||
@@ -57,7 +116,13 @@ const Page = async () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<MembersView org={org} teams={teams} facetedTeamValues={facetedTeamValues} attributes={attributes} />
|
||||
<MembersView
|
||||
org={org}
|
||||
teams={teams}
|
||||
facetedTeamValues={facetedTeamValues}
|
||||
attributes={attributes}
|
||||
permissions={memberPermissions}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import { verifyPassword } from "@calcom/features/auth/lib/verifyPassword";
|
||||
import { symmetricDecrypt } from "@calcom/lib/crypto";
|
||||
import { totpAuthenticatorCheck } from "@calcom/lib/totp";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider } from "@calcom/prisma/client";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
|
||||
import handler from "@calcom/features/calAIPhone/phoneNumberSubscriptionWebhook";
|
||||
|
||||
export const GET = defaultResponderForAppDir(handler);
|
||||
@@ -5,7 +5,7 @@ import type { NextRequest } from "next/server";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import handleCancelBooking from "@calcom/features/bookings/lib/handleCancelBooking";
|
||||
import { bookingCancelInput } from "@calcom/prisma/zod-utils";
|
||||
import { bookingCancelWithCsrfSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
@@ -16,8 +16,16 @@ async function handler(req: NextRequest) {
|
||||
} catch (error) {
|
||||
return NextResponse.json({ success: false, message: "Invalid JSON" }, { status: 400 });
|
||||
}
|
||||
const bookingData = bookingCancelWithCsrfSchema.parse(appDirRequestBody);
|
||||
const cookieStore = await cookies();
|
||||
const cookieToken = cookieStore.get("calcom.csrf_token")?.value;
|
||||
|
||||
if (!cookieToken || cookieToken !== bookingData.csrfToken) {
|
||||
return NextResponse.json({ success: false, message: "Invalid CSRF token" }, { status: 403 });
|
||||
}
|
||||
cookieStore.delete("calcom.csrf_token");
|
||||
|
||||
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
|
||||
const bookingData = bookingCancelInput.parse(appDirRequestBody);
|
||||
const result = await handleCancelBooking({
|
||||
bookingData,
|
||||
userId: session?.user?.id || -1,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { randomBytes } from "crypto";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
|
||||
export async function GET() {
|
||||
const token = randomBytes(32).toString("hex");
|
||||
|
||||
const res = NextResponse.json({ csrfToken: token });
|
||||
|
||||
// We need this cookie to be accessible from embeds where the booking flow is displayed within an iframe on a different origin.
|
||||
// For third‑party iframe contexts (embeds on other sites), browsers require SameSite=None and Secure to make the cookie available.
|
||||
// For local development on http://localhost we fall back to SameSite=Lax to avoid requiring https during development.
|
||||
const useSecureCookies = WEBAPP_URL.startsWith("https://");
|
||||
res.cookies.set("calcom.csrf_token", token, {
|
||||
httpOnly: true,
|
||||
secure: useSecureCookies,
|
||||
sameSite: useSecureCookies ? "none" : "lax",
|
||||
path: "/",
|
||||
});
|
||||
|
||||
return res;
|
||||
}
|
||||
@@ -30,6 +30,10 @@ const querySchema = z.object({
|
||||
const decryptedSchema = z.object({
|
||||
bookingUid: z.string(),
|
||||
userId: z.number().int(),
|
||||
platformClientId: z.string().optional(),
|
||||
platformRescheduleUrl: z.string().optional(),
|
||||
platformCancelUrl: z.string().optional(),
|
||||
platformBookingUrl: z.string().optional(),
|
||||
});
|
||||
|
||||
// Move the sessionGetter function outside the GET function
|
||||
@@ -64,7 +68,14 @@ async function handler(request: NextRequest) {
|
||||
symmetricDecrypt(decodeURIComponent(token), process.env.CALENDSO_ENCRYPTION_KEY || "")
|
||||
);
|
||||
|
||||
const { bookingUid, userId } = decryptedSchema.parse(decryptedData);
|
||||
const {
|
||||
bookingUid,
|
||||
userId,
|
||||
platformClientId,
|
||||
platformRescheduleUrl,
|
||||
platformCancelUrl,
|
||||
platformBookingUrl,
|
||||
} = decryptedSchema.parse(decryptedData);
|
||||
|
||||
const booking = await prisma.booking.findUniqueOrThrow({
|
||||
where: { uid: bookingUid },
|
||||
@@ -97,6 +108,14 @@ async function handler(request: NextRequest) {
|
||||
recurringEventId: booking.recurringEventId || undefined,
|
||||
confirmed: action === DirectAction.ACCEPT,
|
||||
reason,
|
||||
platformClientParams: platformClientId
|
||||
? {
|
||||
platformClientId,
|
||||
platformRescheduleUrl,
|
||||
platformCancelUrl,
|
||||
platformBookingUrl,
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
} catch (e) {
|
||||
let message = "Error confirming booking";
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
async function getHandler() {
|
||||
return NextResponse.json({ message: "Please don't" }, { status: 400 });
|
||||
}
|
||||
|
||||
async function postHandler() {
|
||||
return NextResponse.json({ message: "Please don't" }, { status: 400 });
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(getHandler);
|
||||
export const POST = defaultResponderForAppDir(postHandler);
|
||||
@@ -12,7 +12,7 @@ import stripe from "@calcom/features/ee/payments/server/stripe";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
import { teamMetadataStrictSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
@@ -50,7 +50,7 @@ async function getHandler(req: NextRequest, { params }: { params: Promise<Params
|
||||
if (!team) {
|
||||
const prevTeam = await prisma.team.findFirstOrThrow({ where: { id } });
|
||||
|
||||
metadata = teamMetadataSchema.safeParse(prevTeam.metadata);
|
||||
metadata = teamMetadataStrictSchema.safeParse(prevTeam.metadata);
|
||||
if (!metadata.success) {
|
||||
throw new HttpError({ statusCode: 400, message: "Invalid team metadata" });
|
||||
}
|
||||
@@ -80,7 +80,7 @@ async function getHandler(req: NextRequest, { params }: { params: Promise<Params
|
||||
}
|
||||
|
||||
if (!metadata) {
|
||||
metadata = teamMetadataSchema.safeParse(team.metadata);
|
||||
metadata = teamMetadataStrictSchema.safeParse(team.metadata);
|
||||
if (!metadata.success) {
|
||||
throw new HttpError({ statusCode: 400, message: "Invalid team metadata" });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,686 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { Retell } from "retell-sdk";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
|
||||
import type { CalAiPhoneNumber, User, Team } from "@calcom/prisma/client";
|
||||
|
||||
import { POST } from "../route";
|
||||
|
||||
type MockPhoneNumberWithUser = Omit<CalAiPhoneNumber, "user" | "team"> & {
|
||||
user: Pick<User, "id" | "email" | "name">;
|
||||
team: null;
|
||||
};
|
||||
|
||||
type MockPhoneNumberWithTeam = Omit<CalAiPhoneNumber, "user" | "team"> & {
|
||||
user: null;
|
||||
team: Pick<Team, "id" | "name">;
|
||||
};
|
||||
|
||||
type RetellWebhookBody = {
|
||||
event: "call_started" | "call_ended" | "call_analyzed";
|
||||
call: {
|
||||
call_id: string;
|
||||
agent_id?: string;
|
||||
from_number?: string;
|
||||
to_number?: string;
|
||||
direction?: "inbound" | "outbound";
|
||||
call_status?: string;
|
||||
start_timestamp?: number;
|
||||
end_timestamp?: number;
|
||||
disconnection_reason?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
retell_llm_dynamic_variables?: Record<string, unknown>;
|
||||
transcript?: string;
|
||||
opt_out_sensitive_data_storage?: boolean;
|
||||
call_cost?: {
|
||||
product_costs?: Array<{
|
||||
product: string;
|
||||
unitPrice?: number;
|
||||
cost?: number;
|
||||
}>;
|
||||
total_duration_seconds?: number;
|
||||
total_duration_unit_price?: number;
|
||||
total_one_time_price?: number;
|
||||
combined_cost?: number;
|
||||
};
|
||||
call_analysis?: {
|
||||
call_summary?: string;
|
||||
in_voicemail?: boolean;
|
||||
user_sentiment?: string;
|
||||
call_successful?: boolean;
|
||||
custom_analysis_data?: Record<string, unknown>;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
vi.mock("app/api/defaultResponderForAppDir", () => ({
|
||||
defaultResponderForAppDir:
|
||||
(
|
||||
handler: (req: NextRequest, context: { params: Promise<Record<string, string>> }) => Promise<Response>
|
||||
) =>
|
||||
async (req: NextRequest, context?: { params: Promise<Record<string, string>> }) =>
|
||||
await handler(req, context || { params: Promise.resolve({}) }),
|
||||
}));
|
||||
|
||||
vi.mock("retell-sdk", () => ({
|
||||
Retell: {
|
||||
verify: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockHasAvailableCredits = vi.fn();
|
||||
const mockChargeCredits = vi.fn();
|
||||
|
||||
vi.mock("@calcom/features/ee/billing/credit-service", () => ({
|
||||
CreditService: vi.fn().mockImplementation(() => ({
|
||||
hasAvailableCredits: mockHasAvailableCredits,
|
||||
chargeCredits: mockChargeCredits,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/server/repository/PrismaPhoneNumberRepository", () => ({
|
||||
PrismaPhoneNumberRepository: {
|
||||
findByPhoneNumber: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("next/server", () => ({
|
||||
NextResponse: {
|
||||
json: vi.fn((data, options) => ({
|
||||
json: () => Promise.resolve(data),
|
||||
status: options?.status || 200,
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
const createMockRequest = (body: RetellWebhookBody, signature?: string): NextRequest => {
|
||||
const request = {
|
||||
text: vi.fn().mockResolvedValue(JSON.stringify(body)),
|
||||
headers: {
|
||||
get: vi.fn((name: string) => (name === "x-retell-signature" ? signature : null)),
|
||||
},
|
||||
} as unknown as NextRequest;
|
||||
return request;
|
||||
};
|
||||
|
||||
const callPOST = (request: NextRequest) => POST(request, { params: Promise.resolve({}) });
|
||||
|
||||
describe("Retell AI Webhook Handler", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubEnv("RETELL_AI_KEY", "test-api-key");
|
||||
vi.stubEnv("CAL_AI_CALL_RATE_PER_MINUTE", "0.29");
|
||||
});
|
||||
|
||||
it("should return 401 when signature is missing", async () => {
|
||||
const request = createMockRequest(
|
||||
{ event: "call_analyzed", call: { call_id: "test-call-id" } },
|
||||
"some-signature"
|
||||
);
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
});
|
||||
|
||||
it("should return 401 when API key is not configured", async () => {
|
||||
vi.unstubAllEnvs();
|
||||
|
||||
const request = createMockRequest(
|
||||
{ event: "call_analyzed", call: { call_id: "test-call-id" } },
|
||||
"some-signature"
|
||||
);
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
|
||||
// Restore the stubbed env for subsequent tests
|
||||
vi.stubEnv("RETELL_AI_KEY", "test-api-key");
|
||||
});
|
||||
|
||||
it("should return 401 when signature is invalid", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(false);
|
||||
|
||||
const request = createMockRequest(
|
||||
{ event: "call_analyzed", call: { call_id: "test-call-id" } },
|
||||
"invalid-signature"
|
||||
);
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
});
|
||||
|
||||
it("should handle non-call_analyzed events", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_started",
|
||||
call: { call_id: "test-call-id" },
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const data = await response.json();
|
||||
expect(data.success).toBe(true);
|
||||
expect(data.message).toContain("No handling for call_started");
|
||||
});
|
||||
|
||||
it("should process call_analyzed event with valid phone number and sufficient credits", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 1,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 1, email: "test@example.com", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
|
||||
mockHasAvailableCredits.mockResolvedValue(true);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "test-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
total_duration_seconds: 120,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const data = await response.json();
|
||||
expect(data.success).toBe(true);
|
||||
expect(mockChargeCredits).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 1,
|
||||
teamId: undefined,
|
||||
credits: 58, // 120 seconds = 2 minutes * $0.29 = $0.58 = 58 credits
|
||||
callDuration: 120,
|
||||
externalRef: "retell:test-call-id",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle team phone numbers", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const mockTeamPhoneNumber: MockPhoneNumberWithTeam = {
|
||||
id: 2,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: null,
|
||||
teamId: 5,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id-2",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
team: { id: 5, name: "Test Team" },
|
||||
user: null,
|
||||
};
|
||||
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockTeamPhoneNumber);
|
||||
|
||||
mockHasAvailableCredits.mockResolvedValue(true);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "test-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 50,
|
||||
total_duration_seconds: 180,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockChargeCredits).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: undefined,
|
||||
teamId: 5,
|
||||
credits: 87, // 180 seconds = 3 minutes * $0.29 = $0.87 = 87 credits
|
||||
callDuration: 180,
|
||||
externalRef: "retell:test-call-id",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle missing total_duration_seconds", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "test-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
// missing total_duration_seconds
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(PrismaPhoneNumberRepository.findByPhoneNumber).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle phone number not found", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(null);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "test-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
total_duration_seconds: 90,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockChargeCredits).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle insufficient credits", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 3,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id-3",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 1, email: "test@example.com", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
|
||||
mockHasAvailableCredits.mockResolvedValue(false);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "test-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
total_duration_seconds: 150,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it("should handle schema validation errors", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
// Missing required fields like from_number, to_number, etc.
|
||||
call_id: "test-call-id",
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const data = await response.json();
|
||||
expect(data.error).toBe("Internal server error");
|
||||
});
|
||||
|
||||
it("should calculate credits correctly based on duration", async () => {
|
||||
const testCases = [
|
||||
{ durationSeconds: 60, expectedCredits: 29 }, // 1 minute * $0.29 = $0.29 = 29 credits
|
||||
{ durationSeconds: 120, expectedCredits: 58 }, // 2 minutes * $0.29 = $0.58 = 58 credits
|
||||
{ durationSeconds: 150, expectedCredits: 73 }, // 2.5 minutes * $0.29 = $0.725 = 73 credits (rounded up)
|
||||
{ durationSeconds: 30, expectedCredits: 15 }, // 0.5 minutes * $0.29 = $0.145 = 15 credits (rounded up)
|
||||
];
|
||||
|
||||
for (const { durationSeconds, expectedCredits } of testCases) {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 4,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id-4",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 1, email: "test@example.com", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockHasAvailableCredits.mockResolvedValue(true);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: `test-call-${durationSeconds}s`,
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100, // This is ignored now
|
||||
total_duration_seconds: durationSeconds,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
await callPOST(request);
|
||||
|
||||
expect(mockChargeCredits).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 1,
|
||||
teamId: undefined,
|
||||
credits: expectedCredits,
|
||||
callDuration: durationSeconds,
|
||||
externalRef: expect.stringMatching(/^retell:test-call-/),
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("should pass callDuration to chargeCredits when provided", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 10,
|
||||
phoneNumber: "+15550001111",
|
||||
userId: 42,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "prov-10",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 42, email: "u@example.com", name: "U" },
|
||||
team: null,
|
||||
};
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockHasAvailableCredits.mockResolvedValue(true);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "call-dur",
|
||||
from_number: "+15550002222",
|
||||
to_number: "+15550001111",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 123,
|
||||
call_cost: {
|
||||
combined_cost: 12, // This is ignored now
|
||||
total_duration_seconds: 125,
|
||||
},
|
||||
},
|
||||
};
|
||||
const response = await callPOST(createMockRequest(body, "valid-signature"));
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockChargeCredits).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ userId: 42, credits: 61, callDuration: 125 }) // 125s = 2.083 minutes * $0.29 = $0.604 = 61 credits (rounded up)
|
||||
);
|
||||
});
|
||||
|
||||
describe("Idempotency", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should pass externalRef with correct format to chargeCredits", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 1,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 1, email: "test@example.com", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockChargeCredits.mockResolvedValue({ userId: 1 });
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "test-idempotency-call",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
total_duration_seconds: 60,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const response = await callPOST(createMockRequest(body, "valid-signature"));
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockChargeCredits).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 1,
|
||||
teamId: undefined,
|
||||
credits: 29, // 60 seconds = 1 minute * $0.29 = $0.29 = 29 credits
|
||||
callDuration: 60,
|
||||
externalRef: "retell:test-idempotency-call",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle duplicate webhook calls idempotently", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 1,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 1, email: "test@example.com", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "duplicate-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
total_duration_seconds: 60,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// First call - should charge normally
|
||||
mockChargeCredits.mockResolvedValue({ userId: 1 });
|
||||
const response1 = await callPOST(createMockRequest(body, "valid-signature"));
|
||||
expect(response1.status).toBe(200);
|
||||
const data1 = await response1.json();
|
||||
expect(data1.success).toBe(true);
|
||||
expect(data1.message).toContain("Successfully charged 29 credits");
|
||||
|
||||
// Second call - should return duplicate
|
||||
mockChargeCredits.mockResolvedValue({ bookingUid: null, duplicate: true });
|
||||
const response2 = await callPOST(createMockRequest(body, "valid-signature"));
|
||||
expect(response2.status).toBe(200);
|
||||
const data2 = await response2.json();
|
||||
expect(data2.success).toBe(true);
|
||||
expect(data2.message).toContain("Successfully charged 29 credits");
|
||||
|
||||
// Verify chargeCredits was called twice with same externalRef
|
||||
expect(mockChargeCredits).toHaveBeenCalledTimes(2);
|
||||
expect(mockChargeCredits).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ externalRef: "retell:duplicate-call-id" })
|
||||
);
|
||||
expect(mockChargeCredits).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({ externalRef: "retell:duplicate-call-id" })
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle errors from chargeCredits gracefully", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 1,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 1, email: "test@example.com", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
|
||||
// Mock chargeCredits to throw an error
|
||||
mockChargeCredits.mockRejectedValue(new Error("Credit service error"));
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "error-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
total_duration_seconds: 60,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const response = await callPOST(createMockRequest(body, "valid-signature"));
|
||||
|
||||
// Should still return 200 to prevent retries
|
||||
expect(response.status).toBe(200);
|
||||
const data = await response.json();
|
||||
expect(data.success).toBe(false);
|
||||
expect(data.message).toContain("Error charging credits for Retell AI call");
|
||||
});
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user