From 8291c676ea3ce201fdcd99f4ebbab7bf9b1bc12a Mon Sep 17 00:00:00 2001 From: Syed Ali Shahbaz Date: Tue, 13 Jan 2026 10:53:50 +0400 Subject: [PATCH 1/3] init --- .../developing/guides/automation/webhooks.mdx | 3 +- .../bookings/lib/handleCancelBooking.ts | 46 ++++++++++++------- .../handleSeats/cancel/cancelAttendeeSeat.ts | 1 + packages/features/webhooks/lib/dto/types.ts | 3 ++ .../factory/base/BaseBookingPayloadBuilder.ts | 6 ++- .../v2021-10-20/BookingPayloadBuilder.ts | 1 + packages/features/webhooks/lib/sendPayload.ts | 1 + .../lib/service/BookingWebhookService.ts | 1 + .../features/webhooks/lib/types/params.ts | 2 + .../server/service/BookingWebhookFactory.ts | 11 +++++ .../bookings/requestReschedule.handler.ts | 6 +++ 11 files changed, 63 insertions(+), 18 deletions(-) diff --git a/docs/developing/guides/automation/webhooks.mdx b/docs/developing/guides/automation/webhooks.mdx index d4d4a8952d2687..ff2f863d6a5483 100644 --- a/docs/developing/guides/automation/webhooks.mdx +++ b/docs/developing/guides/automation/webhooks.mdx @@ -311,7 +311,8 @@ Select a version and trigger event to view the example payload: "requiresConfirmation": true, "price": null, "currency": "usd", - "status": "CANCELLED" + "status": "CANCELLED", + "requestReschedule": false } } ``` diff --git a/packages/features/bookings/lib/handleCancelBooking.ts b/packages/features/bookings/lib/handleCancelBooking.ts index 19ffa6e88ea1ef..a1dee57b982de3 100644 --- a/packages/features/bookings/lib/handleCancelBooking.ts +++ b/packages/features/bookings/lib/handleCancelBooking.ts @@ -54,7 +54,12 @@ import { getBookingToDelete } from "./getBookingToDelete"; import { handleInternalNote } from "./handleInternalNote"; import cancelAttendeeSeat from "./handleSeats/cancel/cancelAttendeeSeat"; import type { IBookingCancelService } from "./interfaces/IBookingCancelService"; -import { buildActorEmail, getUniqueIdentifier, makeGuestActor, makeUserActor } from "@calcom/features/booking-audit/lib/makeActor"; +import { + buildActorEmail, + getUniqueIdentifier, + makeGuestActor, + makeUserActor, +} from "@calcom/features/booking-audit/lib/makeActor"; import type { Actor } from "@calcom/features/booking-audit/lib/dto/types"; const log = logger.getSubLogger({ prefix: ["handleCancelBooking"] }); @@ -102,12 +107,17 @@ function getAuditActor({ }) ); // Having fallback prefix makes it clear that we created guest actor from fallback logic - actorEmail = buildActorEmail({ identifier: getUniqueIdentifier({ prefix: "fallback" }), actorType: "guest" }); - } - else { + actorEmail = buildActorEmail({ + identifier: getUniqueIdentifier({ prefix: "fallback" }), + actorType: "guest", + }); + } else { // We can't trust cancelledByEmail and thus can't reuse it as is because it can be set anything by anyone. If we use that as guest actor, we could accidentally attribute the action to the wrong guest actor. // Having param prefix makes it clear that we created guest actor from query param and we still don't use the email as is. - actorEmail = buildActorEmail({ identifier: getUniqueIdentifier({ prefix: "param" }), actorType: "guest" }); + actorEmail = buildActorEmail({ + identifier: getUniqueIdentifier({ prefix: "param" }), + actorType: "guest", + }); } return makeGuestActor({ email: actorEmail, name: null }); @@ -141,10 +151,13 @@ async function handler(input: CancelBookingInput) { // Extract action source once for reuse const actionSource = input.actionSource ?? "UNKNOWN"; if (actionSource === "UNKNOWN") { - log.warn("Booking cancellation with unknown actionSource", safeStringify({ - bookingUid: bookingToDelete.uid, - userUuid, - })); + log.warn( + "Booking cancellation with unknown actionSource", + safeStringify({ + bookingUid: bookingToDelete.uid, + userUuid, + }) + ); } const actorToUse = getAuditActor({ @@ -358,12 +371,12 @@ async function handler(input: CancelBookingInput) { cancellationReason: cancellationReason, ...(teamMembers && teamId && { - team: { - name: bookingToDelete?.eventType?.team?.name || "Nameless", - members: teamMembers, - id: teamId, - }, - }), + team: { + name: bookingToDelete?.eventType?.team?.name || "Nameless", + members: teamMembers, + id: teamId, + }, + }), seatsPerTimeSlot: bookingToDelete.eventType?.seatsPerTimeSlot, seatsShowAttendees: bookingToDelete.eventType?.seatsShowAttendees, iCalUID: bookingToDelete.iCalUID, @@ -404,6 +417,7 @@ async function handler(input: CancelBookingInput) { status: "CANCELLED", smsReminderNumber: bookingToDelete.smsReminderNumber || undefined, cancelledBy: cancelledBy, + requestReschedule: false, }).catch((e) => { logger.error( `Error executing webhook for event: ${eventTrigger}, URL: ${webhook.subscriberUrl}, bookingId: ${evt.bookingId}, bookingUid: ${evt.uid}`, @@ -714,7 +728,7 @@ type BookingCancelServiceDependencies = { * Handles both individual booking cancellations and bulk cancellations for recurring events. */ export class BookingCancelService implements IBookingCancelService { - constructor(private readonly deps: BookingCancelServiceDependencies) { } + constructor(private readonly deps: BookingCancelServiceDependencies) {} async cancelBooking(input: { bookingData: CancelRegularBookingData; bookingMeta?: CancelBookingMeta }) { const cancelBookingInput: CancelBookingInput = { diff --git a/packages/features/bookings/lib/handleSeats/cancel/cancelAttendeeSeat.ts b/packages/features/bookings/lib/handleSeats/cancel/cancelAttendeeSeat.ts index 00cb2f50e1e7ca..7616b6b4485fd9 100644 --- a/packages/features/bookings/lib/handleSeats/cancel/cancelAttendeeSeat.ts +++ b/packages/features/bookings/lib/handleSeats/cancel/cancelAttendeeSeat.ts @@ -164,6 +164,7 @@ async function cancelAttendeeSeat( ...eventTypeInfo, status: "CANCELLED", smsReminderNumber: bookingToDelete.smsReminderNumber || undefined, + requestReschedule: false, }; const promises = webhooks.map((webhook) => diff --git a/packages/features/webhooks/lib/dto/types.ts b/packages/features/webhooks/lib/dto/types.ts index 89db2bcd1bd678..b3e0890e2b82f2 100644 --- a/packages/features/webhooks/lib/dto/types.ts +++ b/packages/features/webhooks/lib/dto/types.ts @@ -50,9 +50,11 @@ export interface BookingCancelledDTO extends BaseEventDTO { eventTypeId: number | null; userId: number | null; smsReminderNumber?: string | null; + iCalSequence?: number | null; }; cancelledBy?: string; cancellationReason?: string; + requestReschedule?: boolean; } export interface BookingRejectedDTO extends BaseEventDTO { @@ -582,6 +584,7 @@ export type EventPayloadType = CalendarEvent & rescheduledBy?: string; cancelledBy?: string; paymentData?: Record; + requestReschedule?: boolean; }; // dto/types.ts diff --git a/packages/features/webhooks/lib/factory/base/BaseBookingPayloadBuilder.ts b/packages/features/webhooks/lib/factory/base/BaseBookingPayloadBuilder.ts index c92727d42c05c0..f26f4f8d79d879 100644 --- a/packages/features/webhooks/lib/factory/base/BaseBookingPayloadBuilder.ts +++ b/packages/features/webhooks/lib/factory/base/BaseBookingPayloadBuilder.ts @@ -11,7 +11,11 @@ import type { IBookingPayloadBuilder } from "../versioned/PayloadBuilderFactory" */ export type BookingExtraDataMap = { [WebhookTriggerEvents.BOOKING_CREATED]: null; - [WebhookTriggerEvents.BOOKING_CANCELLED]: { cancelledBy?: string; cancellationReason?: string }; + [WebhookTriggerEvents.BOOKING_CANCELLED]: { + cancelledBy?: string; + cancellationReason?: string; + requestReschedule?: boolean; + }; [WebhookTriggerEvents.BOOKING_REQUESTED]: null; [WebhookTriggerEvents.BOOKING_REJECTED]: null; [WebhookTriggerEvents.BOOKING_RESCHEDULED]: { diff --git a/packages/features/webhooks/lib/factory/versioned/v2021-10-20/BookingPayloadBuilder.ts b/packages/features/webhooks/lib/factory/versioned/v2021-10-20/BookingPayloadBuilder.ts index 8f2d65e0502cde..e6e57c4500a2c6 100644 --- a/packages/features/webhooks/lib/factory/versioned/v2021-10-20/BookingPayloadBuilder.ts +++ b/packages/features/webhooks/lib/factory/versioned/v2021-10-20/BookingPayloadBuilder.ts @@ -45,6 +45,7 @@ export class BookingPayloadBuilder extends BaseBookingPayloadBuilder { extra: { cancelledBy: dto.cancelledBy, cancellationReason: dto.cancellationReason, + requestReschedule: dto.requestReschedule ?? false, }, }); diff --git a/packages/features/webhooks/lib/sendPayload.ts b/packages/features/webhooks/lib/sendPayload.ts index e8487d799bb227..106f0cc06ee559 100644 --- a/packages/features/webhooks/lib/sendPayload.ts +++ b/packages/features/webhooks/lib/sendPayload.ts @@ -96,6 +96,7 @@ export type EventPayloadType = CalendarEvent & rescheduledBy?: string; cancelledBy?: string; paymentData?: PaymentData; + requestReschedule?: boolean; }; export type WebhookPayloadType = diff --git a/packages/features/webhooks/lib/service/BookingWebhookService.ts b/packages/features/webhooks/lib/service/BookingWebhookService.ts index 06cc1454d08d83..8cfb3c7d1a68d0 100644 --- a/packages/features/webhooks/lib/service/BookingWebhookService.ts +++ b/packages/features/webhooks/lib/service/BookingWebhookService.ts @@ -116,6 +116,7 @@ export class BookingWebhookService implements IBookingWebhookService { booking: params.booking, cancelledBy: params.cancelledBy, cancellationReason: params.cancellationReason, + requestReschedule: params.requestReschedule, }; await this.webhookNotifier.emitWebhook(dto, params.isDryRun); diff --git a/packages/features/webhooks/lib/types/params.ts b/packages/features/webhooks/lib/types/params.ts index 300bb7720b853b..1493b66a558cd0 100644 --- a/packages/features/webhooks/lib/types/params.ts +++ b/packages/features/webhooks/lib/types/params.ts @@ -44,6 +44,7 @@ export interface BookingCancelledParams { eventTypeId: number | null; userId: number | null; smsReminderNumber?: string | null; + iCalSequence?: number | null; }; eventType: { id: number; @@ -57,6 +58,7 @@ export interface BookingCancelledParams { }; cancelledBy?: string; cancellationReason?: string; + requestReschedule?: boolean; teamId?: number | null; orgId?: number | null; platformClientId?: string; diff --git a/packages/lib/server/service/BookingWebhookFactory.ts b/packages/lib/server/service/BookingWebhookFactory.ts index 44141099a76db5..4f3f6c4199cdd7 100644 --- a/packages/lib/server/service/BookingWebhookFactory.ts +++ b/packages/lib/server/service/BookingWebhookFactory.ts @@ -49,6 +49,11 @@ interface BaseWebhookPayload { interface CancelledEventPayload extends BaseWebhookPayload { cancelledBy: string; cancellationReason: string; + eventTypeId?: number | null; + length?: number | null; + iCalSequence?: number | null; + eventTitle?: string | null; + requestReschedule?: boolean; } export class BookingWebhookFactory { @@ -122,6 +127,12 @@ export class BookingWebhookFactory { ...basePayload, cancelledBy: params.cancelledBy, cancellationReason: params.cancellationReason, + status: "CANCELLED" as const, + eventTypeId: params.eventTypeId ?? null, + length: params.length ?? null, + iCalSequence: params.iCalSequence ?? null, + eventTitle: params.eventTitle ?? null, + requestReschedule: params.requestReschedule ?? false, }; } } diff --git a/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts b/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts index 7ee5bd3fbd097b..af1edf694e80a6 100644 --- a/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts +++ b/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts @@ -133,6 +133,7 @@ export const requestRescheduleHandler = async ({ ctx, input, source }: RequestRe const usersToPeopleType = (users: PersonAttendeeCommonFields[], selectedLanguage: TFunction): Person[] => { return users?.map((user) => { return { + id: user.id, email: user.email || "", name: user.name || "", username: user?.username || "", @@ -274,6 +275,11 @@ export const requestRescheduleHandler = async ({ ctx, input, source }: RequestRe smsReminderNumber: bookingToReschedule.smsReminderNumber, }), cancelledBy: user.email, + eventTypeId: bookingToReschedule.eventTypeId, + length: bookingToReschedule.eventType?.length ?? null, + iCalSequence: bookingToReschedule.iCalSequence + 1, + eventTitle: bookingToReschedule.eventType?.title ?? null, + requestReschedule: true, }); // Send webhook From 495906c4ca3221895ca367ab63d1f255e099bf6c Mon Sep 17 00:00:00 2001 From: Syed Ali Shahbaz Date: Tue, 13 Jan 2026 11:22:19 +0400 Subject: [PATCH 2/3] type and test fix --- .../repositories/BookingRepository.ts | 71 +++++++++++-------- .../__tests__/BookingWebhookFactory.test.ts | 6 ++ .../bookings/requestReschedule.handler.ts | 7 +- 3 files changed, 48 insertions(+), 36 deletions(-) diff --git a/packages/features/bookings/repositories/BookingRepository.ts b/packages/features/bookings/repositories/BookingRepository.ts index 37d569adc9c287..64e2656ddf8832 100644 --- a/packages/features/bookings/repositories/BookingRepository.ts +++ b/packages/features/bookings/repositories/BookingRepository.ts @@ -139,8 +139,8 @@ const buildWhereClauseForActiveBookings = ({ }, ...(!includeNoShowInRRCalculation ? { - OR: [{ noShowHost: false }, { noShowHost: null }], - } + OR: [{ noShowHost: false }, { noShowHost: null }], + } : {}), }, { @@ -159,24 +159,24 @@ const buildWhereClauseForActiveBookings = ({ ...(startDate || endDate ? rrTimestampBasis === RRTimestampBasis.CREATED_AT ? { - createdAt: { - ...(startDate ? { gte: startDate } : {}), - ...(endDate ? { lte: endDate } : {}), - }, - } + createdAt: { + ...(startDate ? { gte: startDate } : {}), + ...(endDate ? { lte: endDate } : {}), + }, + } : { - startTime: { - ...(startDate ? { gte: startDate } : {}), - ...(endDate ? { lte: endDate } : {}), - }, - } + startTime: { + ...(startDate ? { gte: startDate } : {}), + ...(endDate ? { lte: endDate } : {}), + }, + } : {}), ...(virtualQueuesData ? { - routedFromRoutingFormReponse: { - chosenRouteId: virtualQueuesData.chosenRouteId, - }, - } + routedFromRoutingFormReponse: { + chosenRouteId: virtualQueuesData.chosenRouteId, + }, + } : {}), }); @@ -325,7 +325,7 @@ const selectStatementToGetBookingForCalEventBuilder = { }; export class BookingRepository { - constructor(private prismaClient: PrismaClient) { } + constructor(private prismaClient: PrismaClient) {} /** * Gets the fromReschedule field for a booking by UID @@ -656,20 +656,20 @@ export class BookingRepository { const currentBookingsAllUsersQueryThree = eventTypeId ? this.prismaClient.booking.findMany({ - where: { - startTime: { lte: endDate }, - endTime: { gte: startDate }, - eventType: { - id: eventTypeId, - requiresConfirmation: true, - requiresConfirmationWillBlockSlot: true, - }, - status: { - in: [BookingStatus.PENDING], + where: { + startTime: { lte: endDate }, + endTime: { gte: startDate }, + eventType: { + id: eventTypeId, + requiresConfirmation: true, + requiresConfirmationWillBlockSlot: true, + }, + status: { + in: [BookingStatus.PENDING], + }, }, - }, - select: bookingsSelect, - }) + select: bookingsSelect, + }) : []; const [resultOne, resultTwo, resultThree] = await Promise.all([ @@ -1659,6 +1659,8 @@ export class BookingRepository { teamId: true, parentId: true, slug: true, + title: true, + length: true, hideOrganizerEmail: true, customReplyToEmail: true, bookingFields: true, @@ -1683,6 +1685,7 @@ export class BookingRepository { workflowReminders: true, responses: true, iCalUID: true, + iCalSequence: true, }, }); } @@ -1913,7 +1916,13 @@ export class BookingRepository { }); } - async updateRecordedStatus({ bookingUid, isRecorded }: { bookingUid: string; isRecorded: boolean }): Promise { + async updateRecordedStatus({ + bookingUid, + isRecorded, + }: { + bookingUid: string; + isRecorded: boolean; + }): Promise { await this.prismaClient.booking.update({ where: { uid: bookingUid }, data: { isRecorded }, diff --git a/packages/lib/server/service/__tests__/BookingWebhookFactory.test.ts b/packages/lib/server/service/__tests__/BookingWebhookFactory.test.ts index 11da828849d75c..ddfc3e4fb28905 100644 --- a/packages/lib/server/service/__tests__/BookingWebhookFactory.test.ts +++ b/packages/lib/server/service/__tests__/BookingWebhookFactory.test.ts @@ -92,6 +92,11 @@ describe("BookingWebhookFactory", () => { "description", "customInputs", "responses", + "eventTitle", + "eventTypeId", + "length", + "requestReschedule", + "iCalSequence", "userFieldsResponses", "startTime", "endTime", @@ -104,6 +109,7 @@ describe("BookingWebhookFactory", () => { "smsReminderNumber", "cancellationReason", "cancelledBy", + "status", ]; const actualKeys = Object.keys(payload).sort(); expect(actualKeys).toEqual(expectedKeys.sort()); diff --git a/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts b/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts index af1edf694e80a6..5e60f3bde183bb 100644 --- a/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts +++ b/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts @@ -103,10 +103,7 @@ export const requestRescheduleHandler = async ({ ctx, input, source }: RequestRe throw new TRPCError({ code: "FORBIDDEN", message: "User isn't owner of the current booking" }); } - let event: Partial = {}; - if (bookingToReschedule.eventType) { - event = bookingToReschedule.eventType; - } + const event: Partial = bookingToReschedule.eventType ?? {}; await bookingRepository.updateBookingStatus({ bookingId: bookingToReschedule.id, status: BookingStatus.CANCELLED, @@ -277,7 +274,7 @@ export const requestRescheduleHandler = async ({ ctx, input, source }: RequestRe cancelledBy: user.email, eventTypeId: bookingToReschedule.eventTypeId, length: bookingToReschedule.eventType?.length ?? null, - iCalSequence: bookingToReschedule.iCalSequence + 1, + iCalSequence: (bookingToReschedule.iCalSequence ?? 0) + 1, eventTitle: bookingToReschedule.eventType?.title ?? null, requestReschedule: true, }); From c58fc59a42bb4d0d40e335696ddfd2c4f1d32083 Mon Sep 17 00:00:00 2001 From: ofir-frd Date: Tue, 20 Jan 2026 20:01:52 +0200 Subject: [PATCH 3/3] Apply changes for benchmark PR --- AGENTS.md | 333 ++++++------------ .../v2021-10-20/BookingPayloadBuilder.ts | 4 +- 2 files changed, 101 insertions(+), 236 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5d960e83b54fa5..879c978338fdb5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,238 +1,103 @@ -# Cal.com Development Guide for AI Agents +# Compliance Rules -You are a senior Cal.com engineer working in a Yarn/Turbo monorepo. You prioritize type safety, security, and small, reviewable diffs. +This file contains the compliance and code quality rules for this repository. -## Do +## 1. Repository and Service Classes Must Follow Naming Conventions -- Use `select` instead of `include` in Prisma queries for performance and security -- Use `import type { X }` for TypeScript type imports -- Use early returns to reduce nesting: `if (!booking) return null;` -- Use `ErrorWithCode` for errors in non-tRPC files (services, repositories, utilities); use `TRPCError` only in tRPC routers -- Use conventional commits: `feat:`, `fix:`, `refactor:` -- Create PRs in draft mode by default -- Run `yarn type-check:ci --force` before concluding CI failures are unrelated to your changes -- Import directly from source files, not barrel files (e.g., `@calcom/ui/components/button` not `@calcom/ui`) -- Add translations to `apps/web/public/static/locales/en/common.json` for all UI strings -- Use `date-fns` or native `Date` instead of Day.js when timezone awareness isn't needed -- Put permission checks in `page.tsx`, never in `layout.tsx` -- Use `ast-grep` for searching if available; otherwise use `rg` (ripgrep), then fall back to `grep` -- Use Biome for formatting and linting - - -## Don't - -- Never use `as any` - use proper type-safe solutions instead -- Never expose `credential.key` field in API responses or queries -- Never commit secrets or API keys -- Never modify `*.generated.ts` files directly - they're created by app-store-cli -- Never put business logic in repositories - that belongs in Services -- Never use barrel imports from index.ts files -- Never skip running type checks before pushing -- Never create large PRs (>500 lines or >10 files) - split them instead - -## Commands - -### File-scoped (preferred for speed) - -```bash -# Type check - always run on changed files -yarn type-check:ci --force - -# Lint and format single file -yarn biome check --write path/to/file.tsx - -# Unit test specific file -yarn vitest run path/to/file.test.ts - -# Unit test specific file + specific test -yarn vitest run path/to/file.test.ts --testNamePattern="specific test name" - -# Integration test specific file -yarn test path/to/file.integration-test.ts -- --integrationTestsOnly - -# Integration test specific file + specific test -yarn test path/to/file.integration-test.ts --testNamePattern="specific test name" -- --integrationTestsOnly - -# E2E test specific file -PLAYWRIGHT_HEADLESS=1 yarn e2e path/to/file.e2e.ts - -# E2E test specific file + specific test -PLAYWRIGHT_HEADLESS=1 yarn e2e path/to/file.e2e.ts --grep "specific test name" -``` - -### Project-wide (use sparingly) - -```bash -# Development -yarn dev # Start dev server -yarn dx # Dev with database setup - -# Build & check -yarn build # Build all packages -yarn biome check --write . # Lint and format all -yarn type-check # Type check all - -# Tests (use TZ=UTC for consistency) -TZ=UTC yarn test # All unit tests -yarn e2e # All E2E tests - -# Database -yarn prisma generate # Regenerate types after schema changes -yarn workspace @calcom/prisma db-migrate # Run migrations -``` - -### Biome focused workflow -+ -```bash -yarn biome check --write . -yarn type-check:ci --force -``` - - -## Boundaries - -### Always do -- Run type check on changed files before committing -- Run relevant tests before pushing -- Use `select` in Prisma queries -- Follow conventional commits for PR titles -- Run Biome before pushing - -### Ask first -- Adding new dependencies -- Schema changes to `packages/prisma/schema.prisma` -- Changes affecting multiple packages -- Deleting files -- Running full build or E2E suites - -### Never do -- Commit secrets, API keys, or `.env` files -- Expose `credential.key` in any query -- Use `as any` type casting -- Force push or rebase shared branches -- Modify generated files directly - -## Project Structure - -``` -apps/web/ # Main Next.js application -packages/prisma/ # Database schema (schema.prisma) and migrations -packages/trpc/ # tRPC API layer (routers in server/routers/) -packages/ui/ # Shared UI components -packages/features/ # Feature-specific code -packages/app-store/ # Third-party integrations -packages/lib/ # Shared utilities -``` - -### Key files -- Routes: `apps/web/app/` (App Router) -- Database schema: `packages/prisma/schema.prisma` -- tRPC routers: `packages/trpc/server/routers/` -- Translations: `apps/web/public/static/locales/en/common.json` -- Workflow constants: `packages/features/ee/workflows/lib/constants.ts` - -## Tech Stack - -- **Framework**: Next.js 13+ (App Router in some areas) -- **Language**: TypeScript (strict) -- **Database**: PostgreSQL with Prisma ORM -- **API**: tRPC for type-safe APIs -- **Auth**: NextAuth.js -- **Styling**: Tailwind CSS -- **Testing**: Vitest (unit), Playwright (E2E) -- **i18n**: next-i18next - -## Code Examples - -### Good error handling - -```typescript -// Good - Descriptive error with context -throw new Error(`Unable to create booking: User ${userId} has no available time slots for ${date}`); - -// Bad - Generic error -throw new Error("Booking failed"); -``` - -For which error class to use (`ErrorWithCode` vs `TRPCError`) and concrete examples, see [Error Types in knowledge-base.md](agents/knowledge-base.md#error-types). - -### Good Prisma query - -```typescript -// Good - Use select for performance and security -const booking = await prisma.booking.findFirst({ - select: { - id: true, - title: true, - user: { - select: { - id: true, - name: true, - email: true, - } - } - } -}); - -// Bad - Include fetches all fields including sensitive ones -const booking = await prisma.booking.findFirst({ - include: { user: true } -}); -``` - -### Good imports - -```typescript -// Good - Type imports and direct paths -import type { User } from "@prisma/client"; -import { Button } from "@calcom/ui/components/button"; - -// Bad - Regular import for types, barrel imports -import { User } from "@prisma/client"; -import { Button } from "@calcom/ui"; -``` - -### API v2 Imports (apps/api/v2) - -When importing from `@calcom/features` or `@calcom/trpc` into `apps/api/v2`, **do not import directly** because the API v2 app's `tsconfig.json` doesn't have path mappings for these modules, which causes "module not found" errors. - -Instead, re-export from `packages/platform/libraries/index.ts` and import from `@calcom/platform-libraries`: - -```typescript -// Step 1: In packages/platform/libraries/index.ts, add the export -export { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository"; - -// Step 2: In apps/api/v2, import from platform-libraries -import { ProfileRepository } from "@calcom/platform-libraries"; - -// Bad - Direct import causes module not found error in apps/api/v2 -import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository"; -``` - -## PR Checklist - -- [ ] Title follows conventional commits: `feat(scope): description` -- [ ] Type check passes: `yarn type-check:ci --force` -- [ ] Lint passes: `yarn lint:fix` -- [ ] Relevant tests pass -- [ ] Diff is small and focused (<500 lines, <10 files) -- [ ] No secrets or API keys committed -- [ ] UI strings added to translation files -- [ ] Created as draft PR - -## When Stuck - -- Ask a clarifying question before making large speculative changes -- Propose a short plan for complex tasks -- Open a draft PR with notes if unsure about approach -- Fix type errors before test failures - they're often the root cause -- Run `yarn prisma generate` if you see missing enum/type errors - -## Extended Documentation +**Objective:** Ensure consistency and discoverability by requiring repository classes to use 'PrismaRepository' pattern and service classes to use 'Service' pattern, with filenames matching class names exactly in PascalCase -For detailed information, see the `agents/` directory: - -- **[agents/README.md](agents/README.md)** - Architecture overview and patterns -- **[agents/commands.md](agents/commands.md)** - Complete command reference -- **[agents/knowledge-base.md](agents/knowledge-base.md)** - Domain knowledge and best practices -- **[agents/coding-standards.md](agents/coding-standards.md)** - Coding standards with examples +**Success Criteria:** Repository files are named 'PrismaRepository.ts' with matching exported class names (e.g., PrismaAppRepository), and service files are named 'Service.ts' with matching class names (e.g., MembershipService) + +**Failure Criteria:** Repository or service files use generic names like 'app.ts', use dot-suffixes like '.service.ts' or '.repository.ts', or have filename/class name mismatches + +--- + +## 2. Prevent Circular Dependencies Between Core Packages + +**Objective:** Maintain clear architectural boundaries and prevent circular dependencies by enforcing import restrictions between core packages (lib, app-store, features, trpc) + +**Success Criteria:** The lib package does not import from app-store, features, or trpc; app-store does not import from features or trpc; features does not import from trpc; and trpc does not import from apps/web + +**Failure Criteria:** Code contains imports that violate the dependency hierarchy, such as lib importing from features, app-store importing from trpc, or any other restricted cross-package imports + +--- + +## 3. Use Biome for Code Formatting with Standardized Configuration + +**Objective:** Ensure consistent code formatting across the entire codebase by using Biome with specific formatting rules for line width, indentation, quotes, and semicolons + +**Success Criteria:** All TypeScript/JavaScript files use 110 character line width, 2-space indentation, LF line endings, double quotes for JSX, always include semicolons, use ES5 trailing commas, and always use arrow function parentheses + +**Failure Criteria:** Code files deviate from the standard formatting rules, such as using single quotes in JSX, omitting semicolons, using different indentation widths, or exceeding line width limits + +--- + +## 4. Default Exports Allowed Only in Next.js Page and Layout Files + +**Objective:** Enforce named exports throughout the codebase for better refactoring and tree-shaking, while allowing default exports only where Next.js requires them (page.tsx and layout.tsx files) + +**Success Criteria:** Files use named exports (export const, export function, export class) except for files matching patterns 'apps/web/app/**/page.tsx', 'apps/web/app/**/layout.tsx', and 'apps/web/app/pages/**/*.tsx' which may use default exports + +**Failure Criteria:** Non-page/layout files use default exports, or page/layout files fail to export the required default component + +--- + +## 5. Schema and Handler Files Must Be Separated with Type-Safe Patterns + +**Objective:** Maintain separation of concerns and type safety by requiring schema definitions in separate '.schema.ts' files with both Zod schema and TypeScript type exports, while handlers in '.handler.ts' files use these typed schemas + +**Success Criteria:** Schema files export both a TypeScript type (TInputSchema) and a corresponding Zod schema (ZInputSchema: z.ZodTypeInputSchema>), and handler files import and use these typed schemas for validation + +**Failure Criteria:** Schema and handler logic are mixed in the same file, schema files lack either TypeScript types or Zod schemas, or handler files perform validation without using the defined schemas + +--- + +## 6. Lint Staged Files Before Commit with Error-on-Warnings Enforcement + +**Objective:** Ensure code quality by running Biome linting on staged files before commits and treating warnings as errors unless explicitly skipped via SKIP_WARNINGS environment variable + +**Success Criteria:** Pre-commit hook runs 'biome lint --error-on-warnings' on staged TypeScript/JavaScript files, 'biome format' on JSON files, and 'prisma format' on schema.prisma, and all checks pass before commit is allowed + +**Failure Criteria:** Commits are made with linting warnings or formatting issues, staged files are not checked before commit, or the pre-commit hook is bypassed without proper justification + +--- + +## 7. Environment Variables Must Not Be Accessed Directly in Non-Configuration Code + +**Objective:** Prevent runtime errors and improve testability by avoiding direct process.env access in business logic and instead using centralized configuration modules or environment-specific checks + +**Success Criteria:** Direct process.env access is limited to configuration files, environment detection utilities (isENVProd, isENVDev), and build-time configuration, while business logic receives environment values through dependency injection or configuration objects + +**Failure Criteria:** Business logic, handlers, or service classes directly access process.env properties instead of using configuration abstractions or injected values + +--- + +## 8. All Tests Must Use Vitest Framework and UTC Timezone + +**Objective:** Ensure consistent test execution and prevent timezone-related bugs by standardizing on Vitest as the test framework and enforcing UTC timezone for all test runs + +**Success Criteria:** Test files use Vitest syntax (vi.mock, vi.fn, describe, it, expect), test commands set TZ=UTC environment variable, and tests do not depend on local timezone settings + +**Failure Criteria:** Tests use Jest-specific APIs, test commands omit TZ=UTC setting, or tests fail when run in different timezones + +--- + +## 9. React Components Must Use react-hook-form with Zod Schema Validation + +**Objective:** Ensure consistent form handling and validation by requiring React Hook Form with Zod resolver for all form components, providing type-safe validation and error handling + +**Success Criteria:** Form components use useForm hook with zodResolver, define Zod schemas for form validation, use Controller or register for form fields, and properly handle validation errors with error messages + +**Failure Criteria:** Form components implement custom validation logic without react-hook-form, lack Zod schema validation, or fail to properly display validation errors to users + +--- + +## 10. Custom Error Classes Must Use Hierarchical Structure with Typed Codes + +**Objective:** Enable robust error handling and debugging by requiring custom error classes that extend base Error classes with typed error codes, HTTP status codes, and structured error information + +**Success Criteria:** Error classes extend from base error types (HttpError, CalendarAppError, ErrorWithCode), include typed error codes for categorization, provide statusCode for HTTP errors, and include relevant context (URL, method, cause) + +**Failure Criteria:** Code throws generic Error objects, lacks error categorization, omits HTTP status codes for API errors, or fails to include sufficient debugging context + +--- diff --git a/packages/features/webhooks/lib/factory/versioned/v2021-10-20/BookingPayloadBuilder.ts b/packages/features/webhooks/lib/factory/versioned/v2021-10-20/BookingPayloadBuilder.ts index e6e57c4500a2c6..bcc8ffe49d2071 100644 --- a/packages/features/webhooks/lib/factory/versioned/v2021-10-20/BookingPayloadBuilder.ts +++ b/packages/features/webhooks/lib/factory/versioned/v2021-10-20/BookingPayloadBuilder.ts @@ -45,9 +45,9 @@ export class BookingPayloadBuilder extends BaseBookingPayloadBuilder { extra: { cancelledBy: dto.cancelledBy, cancellationReason: dto.cancellationReason, - requestReschedule: dto.requestReschedule ?? false, + requestReschedule: dto.requestReschedule ?? false }, - }); + }) case WebhookTriggerEvents.BOOKING_REQUESTED: return this.buildBookingPayload({