chore: migrate booking requested webhook trigger (#27546)
* init * wiring up * fix type * feat: implement DI pattern for webhook producer in API v2 - Export IWebhookProducerService and getWebhookProducer from platform-libraries - Add WEBHOOK_PRODUCER token and useFactory provider in RegularBookingModule - Inject webhookProducer in RegularBookingService and pass to base class This follows the composition root pattern where only the NestJS module knows about getWebhookProducer(), and all consumers depend only on the IWebhookProducerService interface via constructor injection. Co-Authored-By: [email protected] <[email protected]> * test: migrate BOOKING_REQUESTED tests to new webhook architecture - Remove failing BOOKING_REQUESTED tests from fresh-booking.test.ts (4 tests) - Remove failing BOOKING_REQUESTED tests from reschedule.test.ts (2 tests) - Remove failing BOOKING_REQUESTED test from collective-scheduling.test.ts (1 test) - Replace WebhookTaskConsumer.test.ts with placeholder (constructor changed) - Create new webhook architecture test suite: - producer/WebhookTaskerProducerService.test.ts (14 tests) - consumer/WebhookTaskConsumer.test.ts (8 tests) - consumer/triggers/booking-requested.test.ts (8 tests) The new test suite is organized by trigger type for extensibility as more triggers are migrated to the producer/consumer pattern. Co-Authored-By: [email protected] <[email protected]> * test: remove paid events BOOKING_REQUESTED test (moved to new architecture) Co-Authored-By: [email protected] <[email protected]> * wrap webhook in own try-catch * wire datafetcher * fix * fix v2 * fix circular dependency * -- * merge-conflict-resolve * mreg-conflict-resolve * remove early return * test: add integration tests for BOOKING_REQUESTED webhook producer invocation Cover all 8 scenarios verifying the booking flow correctly invokes the webhook producer for BOOKING_REQUESTED: 1. Basic confirmation → queueBookingRequestedWebhook called 2. Booker-is-organizer + confirmation → still called 3. Confirmation threshold NOT met → not called (BOOKING_CREATED instead) 4. Confirmation threshold IS met → called 5. Paid event + confirmation → called after payment succeeds 6. Reschedule + confirmation (non-organizer) → called (not BOOKING_RESCHEDULED) 7. Reschedule + confirmation (organizer) → not called (BOOKING_RESCHEDULED instead) 8. Collective scheduling + confirmation → called Adds reusable MockWebhookProducer helper in @calcom/testing for extendable use as more webhook triggers migrate to the new architecture. Co-Authored-By: [email protected] <[email protected]> * fix bug * fix conditional check * remove unnecessary comment * add missing expect * remove empty test * clean up * tasker config * -- * fix missing metadata * remove faulty if else * test: add payload content verification tests for BOOKING_REQUESTED webhook Co-Authored-By: [email protected] <[email protected]> * remove unnecessary tests --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Hariom Balhara <[email protected]>
This commit is contained in:
39 files changed
+2609
-1523
No files matched your search
+43
-98
@@ -1,26 +1,37 @@
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { IWebhookDataFetcher } from "../../interface/IWebhookDataFetcher";
|
||||
import type { IWebhookRepository } from "../../interface/IWebhookRepository";
|
||||
import { WebhookVersion } from "../../interface/IWebhookRepository";
|
||||
import type { ILogger } from "../../interface/infrastructure";
|
||||
import type { IWebhookService } from "../../interface/services";
|
||||
import type { PayloadBuilderFactory } from "../../factory/versioned/PayloadBuilderFactory";
|
||||
import type { WebhookTaskPayload } from "../../types/webhookTask";
|
||||
import { WebhookTaskConsumer } from "../WebhookTaskConsumer";
|
||||
import { WebhookTaskConsumer } from "../../service/WebhookTaskConsumer";
|
||||
|
||||
/**
|
||||
* Unit Tests for WebhookTaskConsumer
|
||||
*
|
||||
* Tests the heavy Consumer service for processing webhook delivery tasks.
|
||||
* Tests the Consumer service for processing webhook delivery tasks.
|
||||
* The consumer handles the heavy lifting: DB queries, payload building, HTTP delivery.
|
||||
*
|
||||
* Constructor signature:
|
||||
* - webhookRepository: IWebhookRepository
|
||||
* - dataFetchers: IWebhookDataFetcher[]
|
||||
* - payloadBuilderFactory: PayloadBuilderFactory
|
||||
* - webhookService: IWebhookService
|
||||
* - logger: ILogger
|
||||
*/
|
||||
describe("WebhookTaskConsumer", () => {
|
||||
let consumer: WebhookTaskConsumer;
|
||||
let mockWebhookRepository: IWebhookRepository;
|
||||
let mockDataFetchers: IWebhookDataFetcher[];
|
||||
let mockPayloadBuilderFactory: PayloadBuilderFactory;
|
||||
let mockWebhookService: IWebhookService;
|
||||
let mockLogger: ILogger;
|
||||
|
||||
beforeEach(() => {
|
||||
// Mock Repository
|
||||
mockWebhookRepository = {
|
||||
getSubscribers: vi.fn().mockResolvedValue([]),
|
||||
getWebhookById: vi.fn(),
|
||||
@@ -29,7 +40,6 @@ describe("WebhookTaskConsumer", () => {
|
||||
getFilteredWebhooksForUser: vi.fn(),
|
||||
} as unknown as IWebhookRepository;
|
||||
|
||||
// Mock Data Fetchers (Strategy Pattern implementations)
|
||||
const createMockFetcher = (triggerEvents: string[]): IWebhookDataFetcher => ({
|
||||
canHandle: vi.fn((event) => triggerEvents.includes(event)),
|
||||
fetchEventData: vi.fn().mockResolvedValue({ _scaffold: true }),
|
||||
@@ -61,7 +71,16 @@ describe("WebhookTaskConsumer", () => {
|
||||
createMockFetcher([WebhookTriggerEvents.OOO_CREATED]),
|
||||
];
|
||||
|
||||
// Mock Logger
|
||||
mockPayloadBuilderFactory = {
|
||||
getBuilder: vi.fn().mockReturnValue({
|
||||
build: vi.fn().mockReturnValue({ payload: "mock-payload" }),
|
||||
}),
|
||||
} as unknown as PayloadBuilderFactory;
|
||||
|
||||
mockWebhookService = {
|
||||
processWebhooks: vi.fn().mockResolvedValue(undefined),
|
||||
} as unknown as IWebhookService;
|
||||
|
||||
mockLogger = {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
@@ -70,11 +89,17 @@ describe("WebhookTaskConsumer", () => {
|
||||
getSubLogger: vi.fn().mockReturnThis(),
|
||||
} as unknown as ILogger;
|
||||
|
||||
consumer = new WebhookTaskConsumer(mockWebhookRepository, mockDataFetchers, mockLogger);
|
||||
consumer = new WebhookTaskConsumer(
|
||||
mockWebhookRepository,
|
||||
mockDataFetchers,
|
||||
mockPayloadBuilderFactory,
|
||||
mockWebhookService,
|
||||
mockLogger
|
||||
);
|
||||
});
|
||||
|
||||
describe("Constructor & Dependencies", () => {
|
||||
it("should be instantiable with Repository, Data Fetchers, and Logger", () => {
|
||||
it("should be instantiable with all required dependencies", () => {
|
||||
expect(consumer).toBeInstanceOf(WebhookTaskConsumer);
|
||||
});
|
||||
|
||||
@@ -154,7 +179,7 @@ describe("WebhookTaskConsumer", () => {
|
||||
|
||||
expect(mockWebhookRepository.getSubscribers).toHaveBeenCalledWith({
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_CANCELLED,
|
||||
userId: undefined, // Not in payload
|
||||
userId: undefined,
|
||||
eventTypeId: 789,
|
||||
teamId: 111,
|
||||
orgId: 222,
|
||||
@@ -171,110 +196,31 @@ describe("WebhookTaskConsumer", () => {
|
||||
});
|
||||
|
||||
describe("processWebhookTask - Event Type Routing", () => {
|
||||
it("should process BOOKING_CREATED event type (scaffold)", async () => {
|
||||
it("should find appropriate data fetcher for BOOKING_REQUESTED", async () => {
|
||||
const payload: WebhookTaskPayload = {
|
||||
operationId: "op-test",
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_CREATED,
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "test-booking-uid",
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
vi.mocked(mockWebhookRepository.getSubscribers).mockResolvedValueOnce([
|
||||
{
|
||||
id: "sub-1",
|
||||
subscriberUrl: "https://example.com/webhook",
|
||||
payloadTemplate: null,
|
||||
appId: null,
|
||||
secret: null,
|
||||
time: null,
|
||||
timeUnit: null,
|
||||
eventTriggers: [WebhookTriggerEvents.BOOKING_CREATED],
|
||||
version: WebhookVersion.V_2021_10_20,
|
||||
},
|
||||
]);
|
||||
|
||||
await expect(consumer.processWebhookTask(payload, "task-test")).resolves.not.toThrow();
|
||||
expect(mockWebhookRepository.getSubscribers).toHaveBeenCalled();
|
||||
|
||||
const bookingFetcher = mockDataFetchers[0];
|
||||
expect(bookingFetcher.canHandle).toHaveBeenCalledWith(WebhookTriggerEvents.BOOKING_REQUESTED);
|
||||
});
|
||||
|
||||
it("should process FORM_SUBMITTED event type (scaffold)", async () => {
|
||||
it("should throw error when no data fetcher found for trigger event", async () => {
|
||||
const payload: WebhookTaskPayload = {
|
||||
operationId: "op-test",
|
||||
triggerEvent: WebhookTriggerEvents.FORM_SUBMITTED,
|
||||
formId: "test-form-id",
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
vi.mocked(mockWebhookRepository.getSubscribers).mockResolvedValueOnce([
|
||||
{
|
||||
id: "sub-1",
|
||||
subscriberUrl: "https://example.com/webhook",
|
||||
payloadTemplate: null,
|
||||
appId: null,
|
||||
secret: null,
|
||||
time: null,
|
||||
timeUnit: null,
|
||||
eventTriggers: [WebhookTriggerEvents.FORM_SUBMITTED],
|
||||
version: WebhookVersion.V_2021_10_20,
|
||||
},
|
||||
]);
|
||||
|
||||
await expect(consumer.processWebhookTask(payload, "task-test")).resolves.not.toThrow();
|
||||
expect(mockWebhookRepository.getSubscribers).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should process RECORDING_READY event type (scaffold)", async () => {
|
||||
const payload: WebhookTaskPayload = {
|
||||
operationId: "op-test",
|
||||
triggerEvent: WebhookTriggerEvents.RECORDING_READY,
|
||||
recordingId: "test-recording-id",
|
||||
triggerEvent: "UNKNOWN_EVENT" as WebhookTriggerEvents,
|
||||
bookingUid: "test-booking-uid",
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
vi.mocked(mockWebhookRepository.getSubscribers).mockResolvedValueOnce([
|
||||
{
|
||||
id: "sub-1",
|
||||
subscriberUrl: "https://example.com/webhook",
|
||||
payloadTemplate: null,
|
||||
appId: null,
|
||||
secret: null,
|
||||
time: null,
|
||||
timeUnit: null,
|
||||
eventTriggers: [WebhookTriggerEvents.RECORDING_READY],
|
||||
version: WebhookVersion.V_2021_10_20,
|
||||
},
|
||||
]);
|
||||
|
||||
await expect(consumer.processWebhookTask(payload, "task-test")).resolves.not.toThrow();
|
||||
expect(mockWebhookRepository.getSubscribers).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should process OOO_CREATED event type (scaffold)", async () => {
|
||||
const payload: WebhookTaskPayload = {
|
||||
userId: 456,
|
||||
operationId: "op-test",
|
||||
triggerEvent: WebhookTriggerEvents.OOO_CREATED,
|
||||
oooEntryId: 123,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
vi.mocked(mockWebhookRepository.getSubscribers).mockResolvedValueOnce([
|
||||
{
|
||||
id: "sub-1",
|
||||
subscriberUrl: "https://example.com/webhook",
|
||||
payloadTemplate: null,
|
||||
appId: null,
|
||||
secret: null,
|
||||
time: null,
|
||||
timeUnit: null,
|
||||
eventTriggers: [WebhookTriggerEvents.OOO_CREATED],
|
||||
version: WebhookVersion.V_2021_10_20,
|
||||
},
|
||||
]);
|
||||
|
||||
await expect(consumer.processWebhookTask(payload, "task-test")).resolves.not.toThrow();
|
||||
expect(mockWebhookRepository.getSubscribers).toHaveBeenCalled();
|
||||
await expect(consumer.processWebhookTask(payload, "task-test")).rejects.toThrow(
|
||||
"No data fetcher registered for trigger event: UNKNOWN_EVENT"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -324,7 +270,6 @@ describe("WebhookTaskConsumer", () => {
|
||||
},
|
||||
]);
|
||||
|
||||
// Mock the data fetcher to return null (simulating event not found)
|
||||
const bookingFetcher = mockDataFetchers[0];
|
||||
(bookingFetcher.fetchEventData as ReturnType<typeof vi.fn>).mockResolvedValueOnce(null);
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { PayloadBuilderFactory } from "../../../factory/versioned/PayloadBuilderFactory";
|
||||
import { createPayloadBuilderFactory } from "../../../factory/versioned/registry";
|
||||
import type { IWebhookDataFetcher } from "../../../interface/IWebhookDataFetcher";
|
||||
import type { IWebhookRepository } from "../../../interface/IWebhookRepository";
|
||||
import { WebhookVersion } from "../../../interface/IWebhookRepository";
|
||||
import type { ILogger } from "../../../interface/infrastructure";
|
||||
import type { IWebhookService } from "../../../interface/services";
|
||||
import { WebhookTaskConsumer } from "../../../service/WebhookTaskConsumer";
|
||||
import type { BookingWebhookTaskPayload } from "../../../types/webhookTask";
|
||||
|
||||
/**
|
||||
* BOOKING_REQUESTED Trigger Tests
|
||||
*
|
||||
* Tests specific to the BOOKING_REQUESTED webhook trigger.
|
||||
* This trigger fires when a booking requires confirmation (opt-in booking).
|
||||
*
|
||||
* Scenarios covered:
|
||||
* - Event types that require confirmation
|
||||
* - Paid events that require confirmation
|
||||
* - Reschedule scenarios with confirmation required
|
||||
* - Team/collective scheduling with confirmation required
|
||||
*/
|
||||
describe("BOOKING_REQUESTED Trigger", () => {
|
||||
let consumer: WebhookTaskConsumer;
|
||||
let mockWebhookRepository: IWebhookRepository;
|
||||
let mockBookingDataFetcher: IWebhookDataFetcher;
|
||||
let mockPayloadBuilderFactory: PayloadBuilderFactory;
|
||||
let mockWebhookService: IWebhookService;
|
||||
let mockLogger: ILogger;
|
||||
|
||||
const createMockCalendarEvent = (overrides = {}) => ({
|
||||
type: "Test Event",
|
||||
title: "Test Booking",
|
||||
description: "Test description",
|
||||
startTime: new Date().toISOString(),
|
||||
endTime: new Date(Date.now() + 3600000).toISOString(),
|
||||
organizer: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
name: "Organizer",
|
||||
timeZone: "UTC",
|
||||
language: { locale: "en" },
|
||||
},
|
||||
attendees: [
|
||||
{
|
||||
email: "[email protected]",
|
||||
name: "Attendee",
|
||||
timeZone: "UTC",
|
||||
language: { locale: "en" },
|
||||
},
|
||||
],
|
||||
location: "https://cal.com/video/test",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const createMockBooking = (overrides = {}) => ({
|
||||
id: 123,
|
||||
uid: "booking-uid-123",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
startTime: new Date(),
|
||||
endTime: new Date(Date.now() + 3600000),
|
||||
status: "PENDING",
|
||||
smsReminderNumber: null,
|
||||
iCalSequence: 0,
|
||||
assignmentReason: null,
|
||||
user: {
|
||||
id: 789,
|
||||
email: "[email protected]",
|
||||
name: "Organizer",
|
||||
},
|
||||
eventType: {
|
||||
id: 456,
|
||||
title: "Test Event Type",
|
||||
description: "Test event type description",
|
||||
requiresConfirmation: true,
|
||||
price: 0,
|
||||
currency: "USD",
|
||||
length: 60,
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
mockWebhookRepository = {
|
||||
getSubscribers: vi.fn().mockResolvedValue([]),
|
||||
getWebhookById: vi.fn(),
|
||||
findByWebhookId: vi.fn(),
|
||||
findByOrgIdAndTrigger: vi.fn(),
|
||||
getFilteredWebhooksForUser: vi.fn(),
|
||||
} as unknown as IWebhookRepository;
|
||||
|
||||
mockBookingDataFetcher = {
|
||||
canHandle: vi.fn((event) =>
|
||||
[
|
||||
WebhookTriggerEvents.BOOKING_CREATED,
|
||||
WebhookTriggerEvents.BOOKING_CANCELLED,
|
||||
WebhookTriggerEvents.BOOKING_RESCHEDULED,
|
||||
WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
WebhookTriggerEvents.BOOKING_REJECTED,
|
||||
WebhookTriggerEvents.BOOKING_NO_SHOW_UPDATED,
|
||||
].includes(event)
|
||||
),
|
||||
fetchEventData: vi.fn().mockResolvedValue({
|
||||
calendarEvent: createMockCalendarEvent(),
|
||||
booking: createMockBooking(),
|
||||
}),
|
||||
getSubscriberContext: vi.fn((payload: BookingWebhookTaskPayload) => ({
|
||||
triggerEvent: payload.triggerEvent,
|
||||
userId: payload.userId,
|
||||
eventTypeId: payload.eventTypeId,
|
||||
teamId: payload.teamId,
|
||||
orgId: payload.orgId,
|
||||
oAuthClientId: payload.oAuthClientId,
|
||||
})),
|
||||
};
|
||||
|
||||
mockPayloadBuilderFactory = {
|
||||
getBuilder: vi.fn().mockReturnValue({
|
||||
build: vi.fn().mockReturnValue({
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
createdAt: new Date().toISOString(),
|
||||
payload: {
|
||||
type: "Test Event Type",
|
||||
title: "Test Booking",
|
||||
startTime: new Date().toISOString(),
|
||||
endTime: new Date(Date.now() + 3600000).toISOString(),
|
||||
organizer: { email: "[email protected]" },
|
||||
attendees: [{ email: "[email protected]" }],
|
||||
metadata: {},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
} as unknown as PayloadBuilderFactory;
|
||||
|
||||
mockWebhookService = {
|
||||
processWebhooks: vi.fn().mockResolvedValue(undefined),
|
||||
} as unknown as IWebhookService;
|
||||
|
||||
mockLogger = {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
getSubLogger: vi.fn().mockReturnThis(),
|
||||
} as unknown as ILogger;
|
||||
|
||||
consumer = new WebhookTaskConsumer(
|
||||
mockWebhookRepository,
|
||||
[mockBookingDataFetcher],
|
||||
mockPayloadBuilderFactory,
|
||||
mockWebhookService,
|
||||
mockLogger
|
||||
);
|
||||
});
|
||||
|
||||
describe("Event Type that requires confirmation", () => {
|
||||
it("should process BOOKING_REQUESTED when event type requires confirmation", async () => {
|
||||
const payload: BookingWebhookTaskPayload = {
|
||||
operationId: "op-booking-requested-1",
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "booking-uid-123",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
vi.mocked(mockWebhookRepository.getSubscribers).mockResolvedValueOnce([
|
||||
{
|
||||
id: "sub-1",
|
||||
subscriberUrl: "https://example.com/webhook",
|
||||
payloadTemplate: null,
|
||||
appId: null,
|
||||
secret: "webhook-secret",
|
||||
time: null,
|
||||
timeUnit: null,
|
||||
eventTriggers: [WebhookTriggerEvents.BOOKING_REQUESTED],
|
||||
version: WebhookVersion.V_2021_10_20,
|
||||
},
|
||||
]);
|
||||
|
||||
await consumer.processWebhookTask(payload, "task-booking-requested-1");
|
||||
|
||||
expect(mockBookingDataFetcher.canHandle).toHaveBeenCalledWith(WebhookTriggerEvents.BOOKING_REQUESTED);
|
||||
expect(mockBookingDataFetcher.fetchEventData).toHaveBeenCalledWith(payload);
|
||||
expect(mockWebhookService.processWebhooks).toHaveBeenCalledWith(
|
||||
WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
expect.any(Object),
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
subscriberUrl: "https://example.com/webhook",
|
||||
}),
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it("should include metadata in BOOKING_REQUESTED payload", async () => {
|
||||
const payload: BookingWebhookTaskPayload = {
|
||||
operationId: "op-booking-requested-2",
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "booking-uid-456",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
metadata: { customField: "customValue", source: "api" },
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
vi.mocked(mockWebhookRepository.getSubscribers).mockResolvedValueOnce([
|
||||
{
|
||||
id: "sub-1",
|
||||
subscriberUrl: "https://example.com/webhook",
|
||||
payloadTemplate: null,
|
||||
appId: null,
|
||||
secret: null,
|
||||
time: null,
|
||||
timeUnit: null,
|
||||
eventTriggers: [WebhookTriggerEvents.BOOKING_REQUESTED],
|
||||
version: WebhookVersion.V_2021_10_20,
|
||||
},
|
||||
]);
|
||||
|
||||
await consumer.processWebhookTask(payload, "task-booking-requested-2");
|
||||
|
||||
expect(mockBookingDataFetcher.fetchEventData).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
metadata: { customField: "customValue", source: "api" },
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Team/Collective scheduling", () => {
|
||||
it("should process BOOKING_REQUESTED for team event with confirmation required", async () => {
|
||||
const payload: BookingWebhookTaskPayload = {
|
||||
operationId: "op-team-booking",
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "booking-uid-team",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
teamId: 111,
|
||||
orgId: 222,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
vi.mocked(mockWebhookRepository.getSubscribers).mockResolvedValueOnce([
|
||||
{
|
||||
id: "sub-team",
|
||||
subscriberUrl: "https://example.com/team-webhook",
|
||||
payloadTemplate: null,
|
||||
appId: null,
|
||||
secret: null,
|
||||
time: null,
|
||||
timeUnit: null,
|
||||
eventTriggers: [WebhookTriggerEvents.BOOKING_REQUESTED],
|
||||
version: WebhookVersion.V_2021_10_20,
|
||||
},
|
||||
]);
|
||||
|
||||
await consumer.processWebhookTask(payload, "task-team-booking");
|
||||
|
||||
expect(mockBookingDataFetcher.getSubscriberContext).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
teamId: 111,
|
||||
orgId: 222,
|
||||
})
|
||||
);
|
||||
expect(mockWebhookService.processWebhooks).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Integration: real PayloadBuilder verifies webhook payload content", () => {
|
||||
const realPayloadBuilderFactory = createPayloadBuilderFactory();
|
||||
|
||||
const defaultSubscriber = {
|
||||
id: "sub-1",
|
||||
subscriberUrl: "https://example.com/webhook",
|
||||
payloadTemplate: null,
|
||||
appId: null,
|
||||
secret: "secret",
|
||||
time: null,
|
||||
timeUnit: null,
|
||||
eventTriggers: [WebhookTriggerEvents.BOOKING_REQUESTED],
|
||||
version: WebhookVersion.V_2021_10_20,
|
||||
};
|
||||
|
||||
function buildConsumerWithRealBuilder() {
|
||||
return new WebhookTaskConsumer(
|
||||
mockWebhookRepository,
|
||||
[mockBookingDataFetcher],
|
||||
realPayloadBuilderFactory,
|
||||
mockWebhookService,
|
||||
mockLogger
|
||||
);
|
||||
}
|
||||
|
||||
function getDeliveredPayload(): Record<string, unknown> {
|
||||
const [, webhookPayload] = vi.mocked(mockWebhookService.processWebhooks).mock.calls[0];
|
||||
return (webhookPayload as { triggerEvent: string; createdAt: string; payload: Record<string, unknown> })
|
||||
.payload;
|
||||
}
|
||||
|
||||
function getDeliveredWebhookEnvelope(): {
|
||||
triggerEvent: string;
|
||||
createdAt: string;
|
||||
payload: Record<string, unknown>;
|
||||
} {
|
||||
const [, webhookPayload] = vi.mocked(mockWebhookService.processWebhooks).mock.calls[0];
|
||||
return webhookPayload as { triggerEvent: string; createdAt: string; payload: Record<string, unknown> };
|
||||
}
|
||||
|
||||
it("delivers PENDING status and BOOKING_REQUESTED triggerEvent in payload", async () => {
|
||||
const timestamp = "2024-06-15T10:00:00.000Z";
|
||||
const payload: BookingWebhookTaskPayload = {
|
||||
operationId: "op-status-check",
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "booking-uid-123",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
timestamp,
|
||||
};
|
||||
|
||||
vi.mocked(mockWebhookRepository.getSubscribers).mockResolvedValueOnce([defaultSubscriber]);
|
||||
|
||||
const consumerWithRealBuilder = buildConsumerWithRealBuilder();
|
||||
await consumerWithRealBuilder.processWebhookTask(payload, "task-status");
|
||||
|
||||
const envelope = getDeliveredWebhookEnvelope();
|
||||
expect(envelope.triggerEvent).toBe("BOOKING_REQUESTED");
|
||||
expect(envelope.createdAt).toBe(timestamp);
|
||||
|
||||
const p = getDeliveredPayload();
|
||||
expect(p.status).toBe("PENDING");
|
||||
});
|
||||
|
||||
it("includes eventTitle, eventDescription, requiresConfirmation, price, currency, and length from event type", async () => {
|
||||
vi.mocked(mockBookingDataFetcher.fetchEventData).mockResolvedValueOnce({
|
||||
calendarEvent: createMockCalendarEvent(),
|
||||
booking: createMockBooking({
|
||||
eventType: {
|
||||
id: 456,
|
||||
title: "Consultation Call",
|
||||
description: "30-minute consultation",
|
||||
requiresConfirmation: true,
|
||||
price: 5000,
|
||||
currency: "INR",
|
||||
length: 30,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
vi.mocked(mockWebhookRepository.getSubscribers).mockResolvedValueOnce([defaultSubscriber]);
|
||||
|
||||
const consumerWithRealBuilder = buildConsumerWithRealBuilder();
|
||||
await consumerWithRealBuilder.processWebhookTask(
|
||||
{
|
||||
operationId: "op-evt-type",
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "booking-uid-123",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
"task-evt-type"
|
||||
);
|
||||
|
||||
const p = getDeliveredPayload();
|
||||
expect(p.eventTitle).toBe("Consultation Call");
|
||||
expect(p.eventDescription).toBe("30-minute consultation");
|
||||
expect(p.requiresConfirmation).toBe(true);
|
||||
expect(p.price).toBe(5000);
|
||||
expect(p.currency).toBe("INR");
|
||||
expect(p.length).toBe(30);
|
||||
});
|
||||
|
||||
it("includes bookingId, title, location, organizer, and attendees from calendar event", async () => {
|
||||
vi.mocked(mockBookingDataFetcher.fetchEventData).mockResolvedValueOnce({
|
||||
calendarEvent: createMockCalendarEvent({
|
||||
title: "My Booking",
|
||||
location: "https://cal.com/video/abc",
|
||||
organizer: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
name: "Host User",
|
||||
timeZone: "America/New_York",
|
||||
language: { locale: "en" },
|
||||
},
|
||||
attendees: [
|
||||
{
|
||||
email: "[email protected]",
|
||||
name: "Guest User",
|
||||
timeZone: "Europe/London",
|
||||
language: { locale: "en" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
booking: createMockBooking({ id: 999 }),
|
||||
});
|
||||
|
||||
vi.mocked(mockWebhookRepository.getSubscribers).mockResolvedValueOnce([defaultSubscriber]);
|
||||
|
||||
const consumerWithRealBuilder = buildConsumerWithRealBuilder();
|
||||
await consumerWithRealBuilder.processWebhookTask(
|
||||
{
|
||||
operationId: "op-cal-evt",
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "booking-uid-123",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
"task-cal-evt"
|
||||
);
|
||||
|
||||
const p = getDeliveredPayload();
|
||||
expect(p.bookingId).toBe(999);
|
||||
expect(p.title).toBe("My Booking");
|
||||
expect(p.location).toBe("https://cal.com/video/abc");
|
||||
expect(p.organizer).toEqual(
|
||||
expect.objectContaining({
|
||||
email: "[email protected]",
|
||||
name: "Host User",
|
||||
timeZone: "America/New_York",
|
||||
})
|
||||
);
|
||||
expect(p.attendees).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
email: "[email protected]",
|
||||
name: "Guest User",
|
||||
timeZone: "Europe/London",
|
||||
}),
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it("metadata is empty object when no metadata provided (no videoCallUrl for pending requests)", async () => {
|
||||
vi.mocked(mockWebhookRepository.getSubscribers).mockResolvedValueOnce([defaultSubscriber]);
|
||||
|
||||
const consumerWithRealBuilder = buildConsumerWithRealBuilder();
|
||||
await consumerWithRealBuilder.processWebhookTask(
|
||||
{
|
||||
operationId: "op-no-metadata",
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "booking-uid-123",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
"task-no-metadata"
|
||||
);
|
||||
|
||||
const p = getDeliveredPayload();
|
||||
expect(p.metadata).toBeDefined();
|
||||
expect((p.metadata as Record<string, unknown>).videoCallUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
it("paid event payload has PENDING status and correct event type price/currency", async () => {
|
||||
vi.mocked(mockBookingDataFetcher.fetchEventData).mockResolvedValueOnce({
|
||||
calendarEvent: createMockCalendarEvent(),
|
||||
booking: createMockBooking({
|
||||
eventType: {
|
||||
id: 456,
|
||||
title: "Paid Consultation",
|
||||
description: "Paid event requiring confirmation",
|
||||
requiresConfirmation: true,
|
||||
price: 10000,
|
||||
currency: "USD",
|
||||
length: 60,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
vi.mocked(mockWebhookRepository.getSubscribers).mockResolvedValueOnce([defaultSubscriber]);
|
||||
|
||||
const consumerWithRealBuilder = buildConsumerWithRealBuilder();
|
||||
await consumerWithRealBuilder.processWebhookTask(
|
||||
{
|
||||
operationId: "op-paid-payload",
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "booking-uid-paid",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
"task-paid-payload"
|
||||
);
|
||||
|
||||
const p = getDeliveredPayload();
|
||||
expect(p.status).toBe("PENDING");
|
||||
expect(p.eventTitle).toBe("Paid Consultation");
|
||||
expect(p.price).toBe(10000);
|
||||
expect(p.currency).toBe("USD");
|
||||
expect(p.requiresConfirmation).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { ILogger } from "../../interface/infrastructure";
|
||||
import type { WebhookTasker } from "../../tasker/WebhookTasker";
|
||||
import { WebhookTaskerProducerService } from "../../service/WebhookTaskerProducerService";
|
||||
|
||||
/**
|
||||
* Unit Tests for WebhookTaskerProducerService
|
||||
*
|
||||
* Tests the lightweight Producer service for queueing webhook delivery tasks.
|
||||
* The producer has minimal dependencies (only Tasker and Logger) and queues
|
||||
* tasks to be processed by WebhookTaskConsumer.
|
||||
*/
|
||||
describe("WebhookTaskerProducerService", () => {
|
||||
let producer: WebhookTaskerProducerService;
|
||||
let mockWebhookTasker: WebhookTasker;
|
||||
let mockLogger: ILogger;
|
||||
|
||||
beforeEach(() => {
|
||||
mockWebhookTasker = {
|
||||
deliverWebhook: vi.fn().mockResolvedValue({ taskId: "mock-task-id" }),
|
||||
} as unknown as WebhookTasker;
|
||||
|
||||
mockLogger = {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
getSubLogger: vi.fn().mockReturnThis(),
|
||||
} as unknown as ILogger;
|
||||
|
||||
producer = new WebhookTaskerProducerService({
|
||||
webhookTasker: mockWebhookTasker,
|
||||
logger: mockLogger,
|
||||
});
|
||||
});
|
||||
|
||||
describe("Constructor & Dependencies", () => {
|
||||
it("should be instantiable with Tasker and Logger", () => {
|
||||
expect(producer).toBeInstanceOf(WebhookTaskerProducerService);
|
||||
});
|
||||
|
||||
it("should create sub-logger with prefix", () => {
|
||||
expect(mockLogger.getSubLogger).toHaveBeenCalledWith({
|
||||
prefix: ["[WebhookTaskerProducerService]"],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("queueBookingRequestedWebhook", () => {
|
||||
it("should queue a BOOKING_REQUESTED webhook task with required params", async () => {
|
||||
const params = {
|
||||
bookingUid: "booking-123",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
};
|
||||
|
||||
await producer.queueBookingRequestedWebhook(params);
|
||||
|
||||
expect(mockWebhookTasker.deliverWebhook).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "booking-123",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should queue a BOOKING_REQUESTED webhook task with all optional params", async () => {
|
||||
const params = {
|
||||
bookingUid: "booking-123",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
teamId: 111,
|
||||
orgId: 222,
|
||||
oAuthClientId: "oauth-client-123",
|
||||
operationId: "custom-op-id",
|
||||
metadata: { customKey: "customValue" },
|
||||
};
|
||||
|
||||
await producer.queueBookingRequestedWebhook(params);
|
||||
|
||||
expect(mockWebhookTasker.deliverWebhook).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
operationId: "custom-op-id",
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "booking-123",
|
||||
eventTypeId: 456,
|
||||
userId: 789,
|
||||
teamId: 111,
|
||||
orgId: 222,
|
||||
oAuthClientId: "oauth-client-123",
|
||||
metadata: { customKey: "customValue" },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should generate operationId if not provided", async () => {
|
||||
const params = {
|
||||
bookingUid: "booking-123",
|
||||
};
|
||||
|
||||
await producer.queueBookingRequestedWebhook(params);
|
||||
|
||||
expect(mockWebhookTasker.deliverWebhook).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
operationId: expect.any(String),
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "booking-123",
|
||||
timestamp: expect.any(String),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should log debug message when queueing", async () => {
|
||||
const params = {
|
||||
bookingUid: "booking-123",
|
||||
eventTypeId: 456,
|
||||
};
|
||||
|
||||
await producer.queueBookingRequestedWebhook(params);
|
||||
|
||||
expect(mockLogger.debug).toHaveBeenCalledWith(
|
||||
"Queueing booking webhook task",
|
||||
expect.objectContaining({
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
bookingUid: "booking-123",
|
||||
eventTypeId: 456,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should log and rethrow error if tasker fails", async () => {
|
||||
const error = new Error("Tasker error");
|
||||
vi.mocked(mockWebhookTasker.deliverWebhook).mockRejectedValueOnce(error);
|
||||
|
||||
const params = {
|
||||
bookingUid: "booking-123",
|
||||
};
|
||||
|
||||
await expect(producer.queueBookingRequestedWebhook(params)).rejects.toThrow("Tasker error");
|
||||
|
||||
expect(mockLogger.error).toHaveBeenCalledWith(
|
||||
"Failed to queue webhook delivery task",
|
||||
expect.objectContaining({
|
||||
error: "Tasker error",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Other booking webhook methods", () => {
|
||||
it("should queue BOOKING_CREATED webhook", async () => {
|
||||
await producer.queueBookingCreatedWebhook({ bookingUid: "booking-123" });
|
||||
|
||||
expect(mockWebhookTasker.deliverWebhook).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_CREATED,
|
||||
bookingUid: "booking-123",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should queue BOOKING_CANCELLED webhook", async () => {
|
||||
await producer.queueBookingCancelledWebhook({ bookingUid: "booking-123" });
|
||||
|
||||
expect(mockWebhookTasker.deliverWebhook).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_CANCELLED,
|
||||
bookingUid: "booking-123",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should queue BOOKING_RESCHEDULED webhook", async () => {
|
||||
await producer.queueBookingRescheduledWebhook({ bookingUid: "booking-123" });
|
||||
|
||||
expect(mockWebhookTasker.deliverWebhook).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_RESCHEDULED,
|
||||
bookingUid: "booking-123",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should queue BOOKING_REJECTED webhook", async () => {
|
||||
await producer.queueBookingRejectedWebhook({ bookingUid: "booking-123" });
|
||||
|
||||
expect(mockWebhookTasker.deliverWebhook).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REJECTED,
|
||||
bookingUid: "booking-123",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should queue BOOKING_NO_SHOW_UPDATED webhook", async () => {
|
||||
await producer.queueBookingNoShowUpdatedWebhook({ bookingUid: "booking-123" });
|
||||
|
||||
expect(mockWebhookTasker.deliverWebhook).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_NO_SHOW_UPDATED,
|
||||
bookingUid: "booking-123",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Payment webhook methods", () => {
|
||||
it("should queue BOOKING_PAYMENT_INITIATED webhook", async () => {
|
||||
await producer.queueBookingPaymentInitiatedWebhook({ bookingUid: "booking-123" });
|
||||
|
||||
expect(mockWebhookTasker.deliverWebhook).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_PAYMENT_INITIATED,
|
||||
bookingUid: "booking-123",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should queue BOOKING_PAID webhook", async () => {
|
||||
await producer.queueBookingPaidWebhook({ bookingUid: "booking-123" });
|
||||
|
||||
expect(mockWebhookTasker.deliverWebhook).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_PAID,
|
||||
bookingUid: "booking-123",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { EventType, User, Webhook } from "@calcom/prisma/client";
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
import { v4 } from "uuid";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import type { WebhookTaskPayload } from "../types/webhookTask";
|
||||
|
||||
/**
|
||||
* Webhook Producer Integration Tests
|
||||
*
|
||||
* These tests verify that the WebhookTaskerProducerService correctly:
|
||||
* 1. Integrates with the DI container
|
||||
* 2. Calls WebhookTasker.deliverWebhook() with correct payloads
|
||||
*
|
||||
* Note: With the new WebhookTasker architecture:
|
||||
* - Async mode sends to trigger.dev (external service)
|
||||
* - Sync mode executes immediately via WebhookTaskConsumer
|
||||
*
|
||||
* Neither writes to the local Prisma Task table, so we mock
|
||||
* the WebhookTasker to verify the producer's behavior.
|
||||
*/
|
||||
|
||||
// Track deliverWebhook calls
|
||||
const deliveredWebhooks: WebhookTaskPayload[] = [];
|
||||
|
||||
// Mock the WebhookTasker module before importing the container
|
||||
vi.mock("@calcom/features/webhooks/lib/tasker/WebhookTasker", () => ({
|
||||
WebhookTasker: class MockWebhookTasker {
|
||||
async deliverWebhook(payload: WebhookTaskPayload) {
|
||||
deliveredWebhooks.push(payload);
|
||||
return { taskId: `mock-task-${deliveredWebhooks.length}` };
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
// Import after mocking
|
||||
const { getWebhookProducer } = await import("@calcom/features/di/webhooks/containers/webhook");
|
||||
|
||||
describe("Webhook Producer Integration", () => {
|
||||
let testUser: User;
|
||||
let testEventType: EventType;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
let testWebhook: Webhook;
|
||||
|
||||
// Use unique identifiers for each test run to avoid collisions
|
||||
const testId = v4();
|
||||
|
||||
beforeAll(async () => {
|
||||
// Create test user
|
||||
testUser = await prisma.user.create({
|
||||
data: {
|
||||
email: `webhook-producer-test-${testId}@example.com`,
|
||||
username: `webhook-producer-test-${testId}`,
|
||||
name: "Webhook Producer Test User",
|
||||
},
|
||||
});
|
||||
|
||||
// Create test event type
|
||||
testEventType = await prisma.eventType.create({
|
||||
data: {
|
||||
title: "Webhook Producer Test Event",
|
||||
slug: `webhook-producer-test-event-${testId}`,
|
||||
length: 30,
|
||||
userId: testUser.id,
|
||||
},
|
||||
});
|
||||
|
||||
// Create test webhook
|
||||
testWebhook = await prisma.webhook.create({
|
||||
data: {
|
||||
id: `webhook-producer-test-${testId}`,
|
||||
userId: testUser.id,
|
||||
subscriberUrl: "https://example.com/webhook",
|
||||
eventTriggers: [WebhookTriggerEvents.BOOKING_CREATED],
|
||||
active: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
// Clear delivered webhooks before each test
|
||||
deliveredWebhooks.length = 0;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
// Clean up all test data
|
||||
await prisma.webhook.deleteMany({
|
||||
where: { userId: testUser.id },
|
||||
});
|
||||
await prisma.eventType.deleteMany({
|
||||
where: { id: testEventType.id },
|
||||
});
|
||||
await prisma.user.deleteMany({
|
||||
where: { id: testUser.id },
|
||||
});
|
||||
});
|
||||
|
||||
describe("BOOKING_REQUESTED", () => {
|
||||
test("calls deliverWebhook with correct payload", async () => {
|
||||
const producer = getWebhookProducer();
|
||||
const bookingUid = "test-booking-uid-requested";
|
||||
|
||||
await producer.queueBookingRequestedWebhook({
|
||||
bookingUid,
|
||||
eventTypeId: testEventType.id,
|
||||
userId: testUser.id,
|
||||
});
|
||||
|
||||
expect(deliveredWebhooks.length).toBe(1);
|
||||
|
||||
const payload = deliveredWebhooks[0];
|
||||
expect(payload.triggerEvent).toBe(WebhookTriggerEvents.BOOKING_REQUESTED);
|
||||
if (payload.triggerEvent === WebhookTriggerEvents.BOOKING_REQUESTED) {
|
||||
expect(payload.bookingUid).toBe(bookingUid);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,8 @@
|
||||
import type { TGetTranscriptAccessLink } from "@calcom/app-store/dailyvideo/zod";
|
||||
import type { FORM_SUBMITTED_WEBHOOK_RESPONSES } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
|
||||
import type { TimeUnit, WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
|
||||
import type { CalendarEvent, ConferenceData, Person } from "@calcom/types/Calendar";
|
||||
import type { WebhookVersion } from "../interface/IWebhookRepository";
|
||||
import type { CalendarEvent, Person } from "@calcom/types/Calendar";
|
||||
|
||||
export interface BaseEventDTO {
|
||||
triggerEvent: WebhookTriggerEvents;
|
||||
@@ -83,6 +82,7 @@ export interface BookingRequestedDTO extends BaseEventDTO {
|
||||
eventTypeId: number | null;
|
||||
userId: number | null;
|
||||
};
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BookingRescheduledDTO extends BaseEventDTO {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import type { BookingStatus } from "@calcom/prisma/enums";
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import type { EventTypeInfo, BookingWebhookEventDTO } from "../../dto/types";
|
||||
import type { BookingWebhookEventDTO, EventTypeInfo } from "../../dto/types";
|
||||
import type { WebhookPayload } from "../types";
|
||||
import type { IBookingPayloadBuilder } from "../versioned/PayloadBuilderFactory";
|
||||
|
||||
@@ -16,7 +15,9 @@ export type BookingExtraDataMap = {
|
||||
cancellationReason?: string;
|
||||
requestReschedule?: boolean;
|
||||
};
|
||||
[WebhookTriggerEvents.BOOKING_REQUESTED]: null;
|
||||
[WebhookTriggerEvents.BOOKING_REQUESTED]: {
|
||||
metadata?: { [key: string]: string | number | boolean | null };
|
||||
};
|
||||
[WebhookTriggerEvents.BOOKING_REJECTED]: null;
|
||||
[WebhookTriggerEvents.BOOKING_RESCHEDULED]: {
|
||||
rescheduleId?: number;
|
||||
@@ -38,6 +39,8 @@ export interface BookingPayloadParams<T extends keyof BookingExtraDataMap> {
|
||||
eventTypeId: number | null;
|
||||
userId: number | null;
|
||||
smsReminderNumber?: string | null;
|
||||
// Raw assignmentReason from DB for legacy webhook format [{ reasonEnum, reasonString }]
|
||||
assignmentReason?: { reasonEnum: string; reasonString: string }[];
|
||||
};
|
||||
eventType: EventTypeInfo;
|
||||
evt: CalendarEvent;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type {
|
||||
EventPayloadType,
|
||||
OOOEntryPayloadType,
|
||||
BookingNoShowUpdatedPayload,
|
||||
DelegationCredentialErrorPayloadType,
|
||||
EventPayloadType,
|
||||
OOOEntryPayloadType,
|
||||
} from "../dto/types";
|
||||
|
||||
export interface FormSubmittedPayload {
|
||||
|
||||
+233
-1
@@ -2,7 +2,11 @@ import { describe, it, expect, vi } from "vitest";
|
||||
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import type { BookingWebhookEventDTO, EventTypeInfo } from "../../../dto/types";
|
||||
import type {
|
||||
BookingWebhookEventDTO,
|
||||
EventPayloadType,
|
||||
EventTypeInfo,
|
||||
} from "../../../dto/types";
|
||||
import { BookingPayloadBuilder } from "./BookingPayloadBuilder";
|
||||
|
||||
vi.mock("@calcom/lib/dayjs", () => ({
|
||||
@@ -149,4 +153,232 @@ describe("v2021-10-20/BookingPayloadBuilder", () => {
|
||||
|
||||
expect(() => builder.build(minimalDTO)).not.toThrow();
|
||||
});
|
||||
|
||||
describe("Legacy payload shape compatibility (v2021-10-20)", () => {
|
||||
/**
|
||||
* These tests assert the real BookingPayloadBuilder output matches the
|
||||
* legacy webhook format expected by E2E (webhook.e2e.ts) and external
|
||||
* consumers. They exercise normalization and field shapes without mocks.
|
||||
*/
|
||||
|
||||
it("normalizes response labels to your_name and email_address for BOOKING_REQUESTED", () => {
|
||||
const dto = createMockDTO(WebhookTriggerEvents.BOOKING_REQUESTED, {
|
||||
evt: {
|
||||
...mockCalendarEvent,
|
||||
responses: {
|
||||
name: { value: "Test Testson", label: "name" },
|
||||
email: { value: "[email protected]", label: "email" },
|
||||
},
|
||||
userFieldsResponses: {},
|
||||
},
|
||||
});
|
||||
const result = builder.build(dto);
|
||||
const p = result.payload as EventPayloadType;
|
||||
|
||||
expect(p.responses?.name?.label).toBe("your_name");
|
||||
expect(p.responses?.name?.value).toBe("Test Testson");
|
||||
expect(p.responses?.email?.label).toBe("email_address");
|
||||
expect(p.responses?.email?.value).toBe("[email protected]");
|
||||
});
|
||||
|
||||
it("passes through userFieldsResponses unchanged (only responses is normalized)", () => {
|
||||
const dto = createMockDTO(WebhookTriggerEvents.BOOKING_REQUESTED, {
|
||||
evt: {
|
||||
...mockCalendarEvent,
|
||||
responses: {},
|
||||
userFieldsResponses: {
|
||||
name: { value: "Jane", label: "name" },
|
||||
email: { value: "[email protected]", label: "email" },
|
||||
},
|
||||
},
|
||||
});
|
||||
const result = builder.build(dto);
|
||||
const p = result.payload as EventPayloadType;
|
||||
|
||||
expect(p.userFieldsResponses?.name?.label).toBe("name");
|
||||
expect(p.userFieldsResponses?.email?.label).toBe("email");
|
||||
});
|
||||
|
||||
it("includes destinationCalendar in payload (null when not set)", () => {
|
||||
const dto = createMockDTO(WebhookTriggerEvents.BOOKING_REQUESTED, {
|
||||
evt: { ...mockCalendarEvent, destinationCalendar: undefined },
|
||||
});
|
||||
const result = builder.build(dto);
|
||||
const p = result.payload as EventPayloadType;
|
||||
|
||||
expect("destinationCalendar" in p).toBe(true);
|
||||
expect(p.destinationCalendar).toBeNull();
|
||||
});
|
||||
|
||||
it("includes destinationCalendar when evt has it", () => {
|
||||
const dto = createMockDTO(WebhookTriggerEvents.BOOKING_REQUESTED, {
|
||||
evt: {
|
||||
...mockCalendarEvent,
|
||||
destinationCalendar: { id: "cal-1", integration: "google_calendar" },
|
||||
},
|
||||
});
|
||||
const result = builder.build(dto);
|
||||
const p = result.payload as EventPayloadType;
|
||||
|
||||
expect(p.destinationCalendar).toEqual({
|
||||
id: "cal-1",
|
||||
integration: "google_calendar",
|
||||
});
|
||||
});
|
||||
|
||||
it("outputs assignmentReason as legacy array from booking", () => {
|
||||
const legacyReason = [
|
||||
{ reasonEnum: "ROUND_ROBIN", reasonString: "Round robin" },
|
||||
{ reasonEnum: "LEAST_RECENTLY_BOOKED", reasonString: "Least recently booked" },
|
||||
];
|
||||
const dto = createMockDTO(WebhookTriggerEvents.BOOKING_REQUESTED, {
|
||||
booking: {
|
||||
id: 1,
|
||||
eventTypeId: 1,
|
||||
userId: 1,
|
||||
smsReminderNumber: null,
|
||||
assignmentReason: legacyReason,
|
||||
},
|
||||
});
|
||||
const result = builder.build(dto);
|
||||
const p = result.payload as EventPayloadType;
|
||||
|
||||
expect(p.assignmentReason).toEqual(legacyReason);
|
||||
});
|
||||
|
||||
it("outputs assignmentReason as null when booking has none", () => {
|
||||
const dto = createMockDTO(WebhookTriggerEvents.BOOKING_REQUESTED, {
|
||||
booking: {
|
||||
id: 1,
|
||||
eventTypeId: 1,
|
||||
userId: 1,
|
||||
smsReminderNumber: null,
|
||||
},
|
||||
});
|
||||
const result = builder.build(dto);
|
||||
const p = result.payload as EventPayloadType;
|
||||
|
||||
expect(p.assignmentReason).toBeNull();
|
||||
});
|
||||
|
||||
it("BOOKING_REQUESTED payload includes metadata from extra", () => {
|
||||
const dto = createMockDTO(WebhookTriggerEvents.BOOKING_REQUESTED, {
|
||||
metadata: { videoCallUrl: "https://cal.com/video/abc" },
|
||||
});
|
||||
const result = builder.build(dto);
|
||||
const p = result.payload as EventPayloadType;
|
||||
|
||||
expect(p.metadata).toEqual({ videoCallUrl: "https://cal.com/video/abc" });
|
||||
});
|
||||
|
||||
it("preserves empty string description (does not replace with additionalNotes)", () => {
|
||||
const dto = createMockDTO(WebhookTriggerEvents.BOOKING_REQUESTED, {
|
||||
evt: {
|
||||
...mockCalendarEvent,
|
||||
description: "",
|
||||
additionalNotes: "organizer notes here",
|
||||
},
|
||||
});
|
||||
const result = builder.build(dto);
|
||||
const p = result.payload as EventPayloadType;
|
||||
|
||||
expect(p.description).toBe("");
|
||||
expect(p.additionalNotes).toBe("organizer notes here");
|
||||
});
|
||||
|
||||
it("defaults to price 0, currency usd, length null when eventType fields are missing", () => {
|
||||
const dto = createMockDTO(WebhookTriggerEvents.BOOKING_REQUESTED, {
|
||||
eventType: {
|
||||
...mockEventType,
|
||||
price: undefined,
|
||||
currency: undefined,
|
||||
length: undefined,
|
||||
},
|
||||
});
|
||||
const result = builder.build(dto);
|
||||
const p = result.payload as EventPayloadType;
|
||||
|
||||
expect(p.price).toBe(0);
|
||||
expect(p.currency).toBe("usd");
|
||||
expect(p.length).toBeNull();
|
||||
});
|
||||
|
||||
it("derives attendee firstName and lastName from full name when absent", () => {
|
||||
const dto = createMockDTO(WebhookTriggerEvents.BOOKING_REQUESTED, {
|
||||
evt: {
|
||||
...mockCalendarEvent,
|
||||
attendees: [
|
||||
{
|
||||
email: "[email protected]",
|
||||
name: "John Doe",
|
||||
timeZone: "UTC",
|
||||
language: { locale: "en" },
|
||||
},
|
||||
{
|
||||
email: "[email protected]",
|
||||
name: "Alice",
|
||||
timeZone: "UTC",
|
||||
language: { locale: "en" },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const result = builder.build(dto);
|
||||
const p = result.payload as EventPayloadType;
|
||||
|
||||
expect(p.attendees?.[0]).toMatchObject({
|
||||
name: "John Doe",
|
||||
firstName: "John",
|
||||
lastName: "Doe",
|
||||
});
|
||||
expect(p.attendees?.[1]).toMatchObject({
|
||||
name: "Alice",
|
||||
firstName: "Alice",
|
||||
lastName: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not leak evt.assignmentReason; only booking legacy array or null appears", () => {
|
||||
const evtShape = { category: "round_robin", details: "transformed" } as const;
|
||||
const dto = createMockDTO(WebhookTriggerEvents.BOOKING_REQUESTED, {
|
||||
evt: {
|
||||
...mockCalendarEvent,
|
||||
assignmentReason: evtShape,
|
||||
},
|
||||
booking: {
|
||||
id: 1,
|
||||
eventTypeId: 1,
|
||||
userId: 1,
|
||||
smsReminderNumber: null,
|
||||
assignmentReason: null,
|
||||
},
|
||||
});
|
||||
const result = builder.build(dto);
|
||||
const p = result.payload as EventPayloadType;
|
||||
|
||||
expect(p.assignmentReason).toBeNull();
|
||||
expect(p.assignmentReason).not.toEqual(evtShape);
|
||||
});
|
||||
|
||||
it("uses only booking.assignmentReason when both evt and booking have it", () => {
|
||||
const legacyArray = [{ reasonEnum: "ROUND_ROBIN", reasonString: "Round robin" }];
|
||||
const dto = createMockDTO(WebhookTriggerEvents.BOOKING_REQUESTED, {
|
||||
evt: {
|
||||
...mockCalendarEvent,
|
||||
assignmentReason: { category: "other", details: "from evt" },
|
||||
},
|
||||
booking: {
|
||||
id: 1,
|
||||
eventTypeId: 1,
|
||||
userId: 1,
|
||||
smsReminderNumber: null,
|
||||
assignmentReason: legacyArray,
|
||||
},
|
||||
});
|
||||
const result = builder.build(dto);
|
||||
const p = result.payload as EventPayloadType;
|
||||
|
||||
expect(p.assignmentReason).toEqual(legacyArray);
|
||||
});
|
||||
});
|
||||
});
|
||||
+102
-32
@@ -1,13 +1,51 @@
|
||||
import { getUTCOffsetByTimezone } from "@calcom/lib/dayjs";
|
||||
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
|
||||
import type { CalEventResponses } from "@calcom/types/Calendar";
|
||||
import type { BookingWebhookEventDTO } from "../../../dto/types";
|
||||
import type { WebhookPayload } from "../../types";
|
||||
import {
|
||||
BaseBookingPayloadBuilder,
|
||||
type BookingExtraDataMap,
|
||||
type BookingPayloadParams,
|
||||
} from "../../base/BaseBookingPayloadBuilder";
|
||||
import type { WebhookPayload } from "../../types";
|
||||
import type { V20211020BookingEventPayload } from "./types";
|
||||
|
||||
/** Default labels for system booking fields (form-builder / E2E expectation) */
|
||||
const SYSTEM_FIELD_DEFAULT_LABELS: Record<string, string> = {
|
||||
name: "your_name",
|
||||
email: "email_address",
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalize responses so system fields use default labels when label equals field name.
|
||||
* getCalEventResponses uses field name as label when bookingFields is missing; E2E expects default labels.
|
||||
*/
|
||||
function normalizeResponses(responses: CalEventResponses | null | undefined): CalEventResponses | undefined {
|
||||
if (!responses || typeof responses !== "object") return undefined;
|
||||
const out: CalEventResponses = {};
|
||||
for (const [name, entry] of Object.entries(responses)) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const defaultLabel = SYSTEM_FIELD_DEFAULT_LABELS[name];
|
||||
const label =
|
||||
defaultLabel && (entry.label === name || entry.label === undefined)
|
||||
? defaultLabel
|
||||
: (entry.label ?? name);
|
||||
out[name] = { ...entry, label };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Derive firstName/lastName from name for legacy payload parity (attendees[].firstName, attendees[].lastName). */
|
||||
function nameToFirstAndLast(name: string): { firstName: string; lastName: string } {
|
||||
const trimmed = (name ?? "").trim();
|
||||
if (!trimmed) return { firstName: "", lastName: "" };
|
||||
const firstSpace = trimmed.indexOf(" ");
|
||||
if (firstSpace === -1) return { firstName: trimmed, lastName: "" };
|
||||
return {
|
||||
firstName: trimmed.slice(0, firstSpace),
|
||||
lastName: trimmed.slice(firstSpace + 1).trim(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Booking payload builder for webhook version 2021-10-20.
|
||||
@@ -57,6 +95,9 @@ export class BookingPayloadBuilder extends BaseBookingPayloadBuilder {
|
||||
status: BookingStatus.PENDING,
|
||||
triggerEvent: dto.triggerEvent,
|
||||
createdAt: dto.createdAt,
|
||||
extra: {
|
||||
metadata: (dto.metadata ?? {}) as { [key: string]: string | number | boolean | null },
|
||||
},
|
||||
});
|
||||
|
||||
case WebhookTriggerEvents.BOOKING_REJECTED:
|
||||
@@ -131,40 +172,69 @@ export class BookingPayloadBuilder extends BaseBookingPayloadBuilder {
|
||||
params: BookingPayloadParams<T>
|
||||
): WebhookPayload {
|
||||
const utcOffsetOrganizer = getUTCOffsetByTimezone(params.evt.organizer?.timeZone, params.evt.startTime);
|
||||
const organizer = { ...params.evt.organizer, utcOffset: utcOffsetOrganizer };
|
||||
const organizer = {
|
||||
...params.evt.organizer,
|
||||
utcOffset: utcOffsetOrganizer,
|
||||
usernameInOrg: params.evt.organizer?.usernameInOrg,
|
||||
};
|
||||
|
||||
const attendeesWithLegacyFields =
|
||||
params.evt.attendees?.map((a) => {
|
||||
const utcOffset = getUTCOffsetByTimezone(a.timeZone, params.evt.startTime);
|
||||
const nameParts =
|
||||
"firstName" in a && "lastName" in a
|
||||
? {
|
||||
firstName: (a as { firstName?: string }).firstName ?? "",
|
||||
lastName: (a as { lastName?: string }).lastName ?? "",
|
||||
}
|
||||
: nameToFirstAndLast(a.name ?? "");
|
||||
return {
|
||||
...a,
|
||||
utcOffset,
|
||||
firstName: nameParts.firstName,
|
||||
lastName: nameParts.lastName,
|
||||
};
|
||||
}) ?? [];
|
||||
|
||||
// Destructure assignmentReason out of evt so it doesn't leak via the
|
||||
// spread — this version uses its own legacy-shaped field instead.
|
||||
const { assignmentReason: _evtAssignmentReason, ...evtWithoutAssignmentReason } = params.evt;
|
||||
|
||||
const payload: V20211020BookingEventPayload = {
|
||||
...evtWithoutAssignmentReason,
|
||||
bookingId: params.booking.id,
|
||||
startTime: params.evt.startTime,
|
||||
endTime: params.evt.endTime,
|
||||
title: params.evt.title,
|
||||
type: params.evt.type,
|
||||
hashedLink: params.evt.hashedLink ?? null,
|
||||
conferenceData: params.evt.conferenceData,
|
||||
organizer,
|
||||
attendees: attendeesWithLegacyFields,
|
||||
location: params.evt.location,
|
||||
uid: params.evt.uid,
|
||||
customInputs: params.evt.customInputs,
|
||||
responses: normalizeResponses(params.evt.responses) ?? params.evt.responses,
|
||||
userFieldsResponses: params.evt.userFieldsResponses,
|
||||
status: params.status,
|
||||
eventTitle: params.eventType?.eventTitle,
|
||||
eventDescription: params.eventType?.eventDescription ?? null,
|
||||
requiresConfirmation: params.eventType?.requiresConfirmation ?? null,
|
||||
price: params.eventType?.price ?? 0,
|
||||
currency: params.eventType?.currency ?? "usd",
|
||||
length: params.eventType?.length ?? null,
|
||||
smsReminderNumber: params.booking.smsReminderNumber || undefined,
|
||||
additionalNotes: params.evt.additionalNotes ?? "",
|
||||
description: params.evt.description ?? params.evt.additionalNotes ?? "",
|
||||
assignmentReason: params.booking.assignmentReason ?? null,
|
||||
destinationCalendar: params.evt.destinationCalendar ?? null,
|
||||
...(params.extra || {}),
|
||||
};
|
||||
|
||||
return {
|
||||
triggerEvent: params.triggerEvent,
|
||||
createdAt: params.createdAt,
|
||||
payload: {
|
||||
...params.evt,
|
||||
bookingId: params.booking.id,
|
||||
startTime: params.evt.startTime,
|
||||
endTime: params.evt.endTime,
|
||||
title: params.evt.title,
|
||||
type: params.evt.type,
|
||||
organizer,
|
||||
attendees:
|
||||
params.evt.attendees?.map((a) => ({
|
||||
...a,
|
||||
utcOffset: getUTCOffsetByTimezone(a.timeZone, params.evt.startTime),
|
||||
})) ?? [],
|
||||
location: params.evt.location,
|
||||
uid: params.evt.uid,
|
||||
customInputs: params.evt.customInputs,
|
||||
responses: params.evt.responses,
|
||||
userFieldsResponses: params.evt.userFieldsResponses,
|
||||
status: params.status,
|
||||
eventTitle: params.eventType?.eventTitle,
|
||||
eventDescription: params.eventType?.eventDescription,
|
||||
requiresConfirmation: params.eventType?.requiresConfirmation,
|
||||
price: params.eventType?.price,
|
||||
currency: params.eventType?.currency,
|
||||
length: params.eventType?.length,
|
||||
smsReminderNumber: params.booking.smsReminderNumber || undefined,
|
||||
description: params.evt.description || params.evt.additionalNotes,
|
||||
...(params.extra || {}),
|
||||
},
|
||||
payload: payload as WebhookPayload["payload"],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { EventPayloadType } from "../../../dto/types";
|
||||
|
||||
/**
|
||||
* v2021-10-20 booking event payload.
|
||||
*
|
||||
* Overrides CalendarEvent's `assignmentReason` (which uses the transformed
|
||||
* `{ category, details }` shape) with the legacy webhook format: a raw array
|
||||
* of `[{ reasonEnum, reasonString }]` from the DB, or null.
|
||||
*
|
||||
* This keeps the webhook contract stable for v2021-10-20 subscribers.
|
||||
*/
|
||||
export type V20211020BookingEventPayload = Omit<EventPayloadType, "assignmentReason"> & {
|
||||
assignmentReason?: { reasonEnum: string; reasonString: string }[] | null;
|
||||
};
|
||||
@@ -4,7 +4,6 @@
|
||||
interface BaseQueueWebhookParams {
|
||||
/** Unique identifier for this webhook operation (generated if not provided) */
|
||||
operationId?: string;
|
||||
|
||||
/** Additional context data (kept minimal) */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
@@ -15,22 +14,11 @@ interface BaseQueueWebhookParams {
|
||||
* BOOKING_REQUESTED, BOOKING_REJECTED, BOOKING_NO_SHOW_UPDATED
|
||||
*/
|
||||
export interface QueueBookingWebhookParams extends BaseQueueWebhookParams {
|
||||
/** Booking UID (required) */
|
||||
bookingUid: string;
|
||||
|
||||
/** Event Type ID */
|
||||
eventTypeId?: number;
|
||||
|
||||
/** Team ID */
|
||||
teamId?: number | null;
|
||||
|
||||
/** User ID */
|
||||
userId?: number;
|
||||
|
||||
/** Organization ID */
|
||||
orgId?: number;
|
||||
|
||||
/** OAuth Client ID (for platform webhooks) */
|
||||
oAuthClientId?: string | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -123,7 +123,8 @@ export class WebhookRepository implements IWebhookRepository {
|
||||
}): Promise<WebhookSubscriber[]> {
|
||||
const { userId, eventTypeId, managedParentEventTypeId, teamIds, oAuthClientId, triggerEvent } = params;
|
||||
|
||||
// Use static SQL with IS NOT NULL guards and PostgreSQL ANY() for arrays
|
||||
// IMPORTANT: Explicit type casts (::int, ::text) are required for nullable params
|
||||
// PostgreSQL can't infer types for NULL values without explicit casts
|
||||
const results = await this.prisma.$queryRaw<WebhookQueryResult[]>`
|
||||
-- Platform webhooks (highest priority)
|
||||
SELECT
|
||||
@@ -142,8 +143,8 @@ export class WebhookRepository implements IWebhookRepository {
|
||||
2 as priority
|
||||
FROM "Webhook"
|
||||
WHERE active = true
|
||||
AND ${userId} IS NOT NULL
|
||||
AND "userId" = ${userId}
|
||||
AND ${userId}::int IS NOT NULL
|
||||
AND "userId" = ${userId}::int
|
||||
AND ${triggerEvent}::"WebhookTriggerEvents" = ANY("eventTriggers")
|
||||
AND platform = false
|
||||
|
||||
@@ -155,8 +156,8 @@ export class WebhookRepository implements IWebhookRepository {
|
||||
3 as priority
|
||||
FROM "Webhook"
|
||||
WHERE active = true
|
||||
AND ${eventTypeId} IS NOT NULL
|
||||
AND "eventTypeId" = ${eventTypeId}
|
||||
AND ${eventTypeId}::int IS NOT NULL
|
||||
AND "eventTypeId" = ${eventTypeId}::int
|
||||
AND ${triggerEvent}::"WebhookTriggerEvents" = ANY("eventTriggers")
|
||||
AND platform = false
|
||||
|
||||
@@ -168,8 +169,8 @@ export class WebhookRepository implements IWebhookRepository {
|
||||
4 as priority
|
||||
FROM "Webhook"
|
||||
WHERE active = true
|
||||
AND ${managedParentEventTypeId} IS NOT NULL
|
||||
AND "eventTypeId" = ${managedParentEventTypeId}
|
||||
AND ${managedParentEventTypeId}::int IS NOT NULL
|
||||
AND "eventTypeId" = ${managedParentEventTypeId}::int
|
||||
AND ${triggerEvent}::"WebhookTriggerEvents" = ANY("eventTriggers")
|
||||
AND platform = false
|
||||
|
||||
@@ -181,7 +182,7 @@ export class WebhookRepository implements IWebhookRepository {
|
||||
5 as priority
|
||||
FROM "Webhook"
|
||||
WHERE active = true
|
||||
AND ${teamIds} IS NOT NULL
|
||||
AND ${teamIds}::int[] IS NOT NULL
|
||||
AND cardinality(${teamIds}::int[]) > 0
|
||||
AND "teamId" = ANY(${teamIds}::int[])
|
||||
AND ${triggerEvent}::"WebhookTriggerEvents" = ANY("eventTriggers")
|
||||
@@ -195,8 +196,8 @@ export class WebhookRepository implements IWebhookRepository {
|
||||
6 as priority
|
||||
FROM "Webhook"
|
||||
WHERE active = true
|
||||
AND ${oAuthClientId} IS NOT NULL
|
||||
AND "platformOAuthClientId" = ${oAuthClientId}
|
||||
AND ${oAuthClientId}::text IS NOT NULL
|
||||
AND "platformOAuthClientId" = ${oAuthClientId}::text
|
||||
AND ${triggerEvent}::"WebhookTriggerEvents" = ANY("eventTriggers")
|
||||
AND platform = false
|
||||
|
||||
|
||||
@@ -1,31 +1,27 @@
|
||||
import type { BookingForCalEventBuilder } from "@calcom/features/CalendarEventBuilder";
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
import type { WebhookEventDTO, WebhookSubscriber } from "../dto/types";
|
||||
import type { PayloadBuilderFactory } from "../factory/versioned/PayloadBuilderFactory";
|
||||
import type { IWebhookDataFetcher } from "../interface/IWebhookDataFetcher";
|
||||
import type { IWebhookRepository } from "../interface/IWebhookRepository";
|
||||
import { DEFAULT_WEBHOOK_VERSION } from "../interface/IWebhookRepository";
|
||||
import type { ILogger } from "../interface/infrastructure";
|
||||
import type { WebhookTaskPayload } from "../types/webhookTask";
|
||||
import type { IWebhookService } from "../interface/services";
|
||||
import type {
|
||||
BookingWebhookTaskPayload,
|
||||
PaymentWebhookTaskPayload,
|
||||
WebhookTaskPayload,
|
||||
} from "../types/webhookTask";
|
||||
|
||||
/**
|
||||
* Webhook Task Consumer
|
||||
*
|
||||
* Processes webhook delivery tasks from the queue:
|
||||
* 1. Fetches webhook subscribers
|
||||
* 2. Fetches event-specific data from database (via injected data fetchers)
|
||||
* 3. Builds and sends webhook payloads
|
||||
*
|
||||
* Architecture:
|
||||
* - Uses Strategy Pattern: Data fetchers are injected, consumer orchestrates
|
||||
* - Open/Closed: Add new webhook types by registering fetchers, no code modification
|
||||
* - Single Responsibility: Consumer orchestrates, fetchers handle domain logic
|
||||
* - Dependency Inversion: Depends on IWebhookDataFetcher interface
|
||||
*
|
||||
* Phase 0: Scaffold with placeholders for HTTP delivery
|
||||
* Phase 1+: Full implementation with PayloadBuilders and HTTP client
|
||||
*/
|
||||
export class WebhookTaskConsumer {
|
||||
private readonly log: ILogger;
|
||||
|
||||
constructor(
|
||||
private readonly webhookRepository: IWebhookRepository,
|
||||
private readonly dataFetchers: IWebhookDataFetcher[],
|
||||
private readonly payloadBuilderFactory: PayloadBuilderFactory,
|
||||
private readonly webhookService: IWebhookService,
|
||||
logger: ILogger
|
||||
) {
|
||||
this.log = logger.getSubLogger({ prefix: ["[WebhookTaskConsumer]"] });
|
||||
@@ -42,7 +38,6 @@ export class WebhookTaskConsumer {
|
||||
});
|
||||
|
||||
try {
|
||||
// Step 1: Get the appropriate data fetcher for this trigger event
|
||||
const fetcher = this.getDataFetcher(payload.triggerEvent);
|
||||
|
||||
if (!fetcher) {
|
||||
@@ -53,7 +48,6 @@ export class WebhookTaskConsumer {
|
||||
throw new Error(`No data fetcher registered for trigger event: ${payload.triggerEvent}`);
|
||||
}
|
||||
|
||||
// Step 2: Fetch webhook subscribers
|
||||
const subscriberContext = fetcher.getSubscriberContext(payload);
|
||||
const subscribers = await this.webhookRepository.getSubscribers(subscriberContext);
|
||||
|
||||
@@ -66,7 +60,6 @@ export class WebhookTaskConsumer {
|
||||
operationId: payload.operationId,
|
||||
});
|
||||
|
||||
// Step 3: Fetch event-specific data via data fetcher
|
||||
const eventData = await fetcher.fetchEventData(payload);
|
||||
|
||||
if (!eventData) {
|
||||
@@ -77,7 +70,6 @@ export class WebhookTaskConsumer {
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 4: Build and send webhooks to each subscriber
|
||||
await this.sendWebhooksToSubscribers(subscribers, eventData, payload);
|
||||
|
||||
this.log.debug("Webhook delivery task completed", {
|
||||
@@ -104,18 +96,120 @@ export class WebhookTaskConsumer {
|
||||
}
|
||||
|
||||
/**
|
||||
* Build webhook payloads and send to each subscriber.
|
||||
*
|
||||
* TODO: Implement with PayloadBuilders and HTTP client (Phase 1+)
|
||||
* Build webhook payloads and send to each subscriber via WebhookService.
|
||||
* Uses WebhookService.processWebhooks() for HTTP delivery.
|
||||
*/
|
||||
private async sendWebhooksToSubscribers(
|
||||
subscribers: unknown[],
|
||||
subscribers: WebhookSubscriber[],
|
||||
eventData: Record<string, unknown>,
|
||||
payload: WebhookTaskPayload
|
||||
): Promise<void> {
|
||||
this.log.debug("Webhook sending not implemented yet (Phase 0 scaffold)", {
|
||||
subscriberCount: subscribers.length,
|
||||
triggerEvent: payload.triggerEvent,
|
||||
});
|
||||
if (subscribers.length === 0) {
|
||||
this.log.debug("No subscribers to send webhooks to");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const dto = this.buildDTO(eventData, payload);
|
||||
|
||||
if (!dto) {
|
||||
this.log.warn("Failed to build DTO for webhook", {
|
||||
triggerEvent: payload.triggerEvent,
|
||||
operationId: payload.operationId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const builder = this.payloadBuilderFactory.getBuilder(DEFAULT_WEBHOOK_VERSION, dto.triggerEvent);
|
||||
const webhookPayload = builder.build(dto);
|
||||
|
||||
await this.webhookService.processWebhooks(dto.triggerEvent, webhookPayload, subscribers);
|
||||
|
||||
this.log.debug("Webhook sending completed", {
|
||||
subscriberCount: subscribers.length,
|
||||
triggerEvent: payload.triggerEvent,
|
||||
operationId: payload.operationId,
|
||||
});
|
||||
} catch (error) {
|
||||
this.log.error("Error in sendWebhooksToSubscribers", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
triggerEvent: payload.triggerEvent,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Build WebhookEventDTO from fetched event data.
|
||||
*
|
||||
* This method maps the data fetched from DB into the DTO structure
|
||||
* expected by PayloadBuilders.
|
||||
*/
|
||||
private buildDTO(eventData: Record<string, unknown>, payload: WebhookTaskPayload): WebhookEventDTO | null {
|
||||
const { triggerEvent, timestamp } = payload;
|
||||
|
||||
const calendarEvent = eventData.calendarEvent as CalendarEvent | undefined;
|
||||
const booking = eventData.booking as BookingForCalEventBuilder | undefined;
|
||||
const eventType = booking?.eventType;
|
||||
|
||||
if (!calendarEvent || !booking || !eventType) {
|
||||
this.log.warn("Missing required data to build DTO", {
|
||||
hasCalendarEvent: !!calendarEvent,
|
||||
hasBooking: !!booking,
|
||||
hasEventType: !!eventType,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const eventTypeInfo = {
|
||||
id: eventType.id,
|
||||
eventTitle: eventType.title,
|
||||
eventDescription: eventType.description,
|
||||
requiresConfirmation: eventType.requiresConfirmation,
|
||||
price: eventType.price,
|
||||
currency: eventType.currency,
|
||||
length: eventType.length,
|
||||
};
|
||||
|
||||
const bookingPayload = payload as BookingWebhookTaskPayload;
|
||||
const baseDTO = {
|
||||
createdAt: timestamp,
|
||||
bookingId: booking.id,
|
||||
eventTypeId: eventType.id,
|
||||
userId: booking.user?.id ?? null,
|
||||
teamId: bookingPayload.teamId ?? null,
|
||||
orgId: bookingPayload.orgId,
|
||||
platformClientId: bookingPayload.platformClientId ?? bookingPayload.oAuthClientId,
|
||||
evt: calendarEvent,
|
||||
eventType: eventTypeInfo,
|
||||
booking: {
|
||||
id: booking.id,
|
||||
eventTypeId: booking.eventTypeId,
|
||||
userId: booking.userId,
|
||||
startTime: booking.startTime,
|
||||
smsReminderNumber: booking.smsReminderNumber,
|
||||
iCalSequence: booking.iCalSequence,
|
||||
// Raw assignmentReason from DB for legacy format [{ reasonEnum, reasonString }]
|
||||
assignmentReason: booking.assignmentReason,
|
||||
},
|
||||
};
|
||||
|
||||
switch (triggerEvent) {
|
||||
case WebhookTriggerEvents.BOOKING_REQUESTED:
|
||||
return {
|
||||
...baseDTO,
|
||||
triggerEvent,
|
||||
metadata: {
|
||||
...(typeof booking.metadata === "object" &&
|
||||
booking.metadata !== null &&
|
||||
!Array.isArray(booking.metadata)
|
||||
? booking.metadata
|
||||
: {}),
|
||||
...(bookingPayload.metadata ?? {}),
|
||||
},
|
||||
} as WebhookEventDTO;
|
||||
default:
|
||||
this.log.warn("Unsupported trigger event for DTO building", { triggerEvent });
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
|
||||
import { CalendarEventBuilder } from "@calcom/features/CalendarEventBuilder";
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
import type { IWebhookDataFetcher, SubscriberContext } from "../../interface/IWebhookDataFetcher";
|
||||
import type { ILogger } from "../../interface/infrastructure";
|
||||
@@ -13,7 +15,10 @@ export class BookingWebhookDataFetcher implements IWebhookDataFetcher {
|
||||
WebhookTriggerEvents.BOOKING_NO_SHOW_UPDATED,
|
||||
]);
|
||||
|
||||
constructor(private readonly logger: ILogger) {}
|
||||
constructor(
|
||||
private readonly logger: ILogger,
|
||||
private readonly bookingRepository: BookingRepository
|
||||
) {}
|
||||
|
||||
canHandle(triggerEvent: WebhookTriggerEvents): boolean {
|
||||
return this.BOOKING_TRIGGERS.has(triggerEvent as never);
|
||||
@@ -27,9 +32,44 @@ export class BookingWebhookDataFetcher implements IWebhookDataFetcher {
|
||||
return null;
|
||||
}
|
||||
|
||||
// TODO: Implement using BookingRepository/EventTypeRepository/UserRepository (Phase 1+)
|
||||
this.logger.debug("Booking data fetch not implemented yet (Phase 0 scaffold)", { bookingUid });
|
||||
return { bookingUid, _scaffold: true };
|
||||
try {
|
||||
// Fetch complete booking data with all related entities
|
||||
const booking = await this.bookingRepository.getBookingForCalEventBuilderFromUid(bookingUid);
|
||||
|
||||
if (!booking) {
|
||||
this.logger.warn("Booking not found", { bookingUid });
|
||||
return null;
|
||||
}
|
||||
|
||||
// Build CalendarEvent using the builder pattern (same pattern used by email/sms tasks)
|
||||
// Map oAuthClientId to platformClientId for platform metadata
|
||||
const calendarEvent = (
|
||||
await CalendarEventBuilder.fromBooking(booking, {
|
||||
platformClientId: payload.oAuthClientId ?? undefined,
|
||||
platformRescheduleUrl: payload.platformRescheduleUrl ?? undefined,
|
||||
platformCancelUrl: payload.platformCancelUrl ?? undefined,
|
||||
platformBookingUrl: payload.platformBookingUrl ?? undefined,
|
||||
})
|
||||
).build();
|
||||
|
||||
if (!calendarEvent) {
|
||||
this.logger.error("Failed to build CalendarEvent from booking", { bookingUid });
|
||||
return null;
|
||||
}
|
||||
|
||||
// Return complete data needed for webhook payload building
|
||||
return {
|
||||
calendarEvent,
|
||||
booking,
|
||||
eventType: booking.eventType,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error("Error fetching booking data for webhook", {
|
||||
bookingUid,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
getSubscriberContext(payload: BookingWebhookTaskPayload): SubscriberContext {
|
||||
|
||||
@@ -1,33 +1,20 @@
|
||||
import type { Queue, schemaTask } from "@trigger.dev/sdk";
|
||||
import { queue } from "@trigger.dev/sdk";
|
||||
import { type Queue, queue, type schemaTask } from "@trigger.dev/sdk";
|
||||
|
||||
type WebhookDeliveryTask = Pick<Parameters<typeof schemaTask>[0], "machine" | "retry" | "queue">;
|
||||
|
||||
/**
|
||||
* Queue configuration for webhook delivery tasks
|
||||
*
|
||||
* Webhooks are time-sensitive, so we use a moderate concurrency limit
|
||||
* to ensure timely delivery while not overwhelming external services.
|
||||
*/
|
||||
export const webhookDeliveryQueue: Queue = queue({
|
||||
name: "webhook-delivery",
|
||||
concurrencyLimit: 20,
|
||||
concurrencyLimit: 25,
|
||||
});
|
||||
|
||||
/**
|
||||
* Task configuration for webhook delivery
|
||||
*
|
||||
* - machine: small-2x for lightweight HTTP requests
|
||||
* - retry: 3 attempts with exponential backoff for transient failures
|
||||
*/
|
||||
export const webhookDeliveryTaskConfig: WebhookDeliveryTask = {
|
||||
machine: "small-1x",
|
||||
queue: webhookDeliveryQueue,
|
||||
machine: "small-2x",
|
||||
retry: {
|
||||
maxAttempts: 3,
|
||||
factor: 1.8,
|
||||
minTimeoutInMs: 500,
|
||||
maxTimeoutInMs: 30_000,
|
||||
factor: 2,
|
||||
minTimeoutInMs: 30000,
|
||||
maxTimeoutInMs: 600000,
|
||||
randomize: true,
|
||||
outOfMemory: {
|
||||
machine: "medium-1x",
|
||||
|
||||
@@ -30,6 +30,10 @@ export const bookingWebhookTaskPayloadSchema = baseWebhookTaskSchema.extend({
|
||||
userId: z.number().optional(),
|
||||
orgId: z.number().optional(),
|
||||
oAuthClientId: z.string().nullable().optional(),
|
||||
platformClientId: z.string().nullable().optional(),
|
||||
platformRescheduleUrl: z.string().nullable().optional(),
|
||||
platformCancelUrl: z.string().nullable().optional(),
|
||||
platformBookingUrl: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user