feat: add wrong assignment report dialog and webhook for routing form bookings (#25839)

Co-authored-by: [email protected] <[email protected]>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-01-22 16:44:29 +00:00
1 parent 89ae748681
commit 6f7c8bdd73
16 files changed
+1027 -7

No files matched your search

@@ -2002,6 +2002,49 @@ async updateMany({ where, data }: { where: BookingWhereInput; data: BookingUpdat
});
}
async findByUidIncludeEventTypeAndTeamAndAssignmentReason({ bookingUid }: { bookingUid: string }) {
return await this.prismaClient.booking.findUnique({
where: {
uid: bookingUid,
},
select: {
id: true,
uid: true,
title: true,
startTime: true,
endTime: true,
status: true,
user: {
select: {
id: true,
name: true,
email: true,
},
},
attendees: {
select: {
email: true,
name: true,
},
},
eventType: {
select: {
id: true,
title: true,
slug: true,
teamId: true,
},
},
assignmentReason: {
select: {
reasonString: true,
reasonEnum: true,
},
},
},
});
}
async updateRecordedStatus({
bookingUid,
isRecorded,
@@ -62,6 +62,7 @@ export const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP = {
WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR,
WebhookTriggerEvents.WRONG_ASSIGNMENT_REPORT,
] as const,
"routing-forms": [
WebhookTriggerEvents.FORM_SUBMITTED,
@@ -110,6 +110,9 @@ const TRIGGER_TO_BUILDER_CATEGORY: Record<WebhookTriggerEvents, BuilderCategory>
// Delegation events
[WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR]: "delegation",
// Wrong assignment report events
[WebhookTriggerEvents.WRONG_ASSIGNMENT_REPORT]: "booking",
};
export type BookingTriggerEvents =
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "public"."WebhookTriggerEvents" ADD VALUE 'WRONG_ASSIGNMENT_REPORT';
+1
View File
@@ -1119,6 +1119,7 @@ enum WebhookTriggerEvents {
AFTER_GUESTS_CAL_VIDEO_NO_SHOW
FORM_SUBMITTED_NO_EVENT
DELEGATION_CREDENTIAL_ERROR
WRONG_ASSIGNMENT_REPORT
}
model Webhook {
@@ -13,6 +13,7 @@ import { ZGetBookingDetailsInputSchema } from "./getBookingDetails.schema";
import { ZGetBookingHistoryInputSchema } from "./getBookingHistory.schema";
import { ZInstantBookingInputSchema } from "./getInstantBookingLocation.schema";
import { ZReportBookingInputSchema } from "./reportBooking.schema";
import { ZReportWrongAssignmentInputSchema } from "./reportWrongAssignment.schema";
import { ZRequestRescheduleInputSchema } from "./requestReschedule.schema";
import { bookingsProcedure } from "./util";
import { makeUserActor } from "@calcom/features/booking-audit/lib/makeActor";
@@ -117,6 +118,16 @@ export const bookingsRouter = router({
input,
});
}),
reportWrongAssignment: authedProcedure
.input(ZReportWrongAssignmentInputSchema)
.mutation(async ({ input, ctx }) => {
const { reportWrongAssignmentHandler } = await import("./reportWrongAssignment.handler");
return reportWrongAssignmentHandler({
ctx,
input,
});
}),
getBookingHistory: authedProcedure.input(ZGetBookingHistoryInputSchema).query(async ({ input, ctx }) => {
const { getBookingHistoryHandler } = await import("./getBookingHistory.handler");
@@ -0,0 +1,360 @@
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { BookingAccessService } from "@calcom/features/bookings/services/BookingAccessService";
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
import { sendGenericWebhookPayload } from "@calcom/features/webhooks/lib/sendPayload";
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
import { TRPCError } from "@trpc/server";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { reportWrongAssignmentHandler } from "./reportWrongAssignment.handler";
vi.mock("@calcom/features/bookings/repositories/BookingRepository");
vi.mock("@calcom/features/bookings/services/BookingAccessService");
vi.mock("@calcom/features/webhooks/lib/getWebhooks");
vi.mock("@calcom/features/webhooks/lib/sendPayload");
vi.mock("@calcom/prisma", () => ({ default: {} }));
vi.mock("@calcom/lib/logger", () => ({
default: {
getSubLogger: () => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
}),
},
}));
describe("reportWrongAssignmentHandler", () => {
const mockUser = {
id: 1,
email: "[email protected]",
name: "Reporter User",
};
const mockBooking = {
id: 100,
uid: "test-booking-uid",
title: "Test Booking",
startTime: new Date("2025-12-01T10:00:00Z"),
endTime: new Date("2025-12-01T11:00:00Z"),
status: BookingStatus.ACCEPTED,
user: {
id: 2,
email: "[email protected]",
name: "Host User",
},
attendees: [{ email: "[email protected]" }],
eventType: {
id: 10,
title: "Test Event",
slug: "test-event",
teamId: 5,
},
assignmentReason: [{ reasonString: "Matched by round-robin" }],
};
const mockBookingRepo = {
findByUidIncludeEventTypeAndTeamAndAssignmentReason: vi.fn(),
};
const mockBookingAccessService = {
doesUserIdHaveAccessToBooking: vi.fn(),
};
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(BookingRepository).mockImplementation(function () {
return mockBookingRepo;
});
vi.mocked(BookingAccessService).mockImplementation(function () {
return mockBookingAccessService;
});
vi.mocked(getWebhooks).mockResolvedValue([]);
vi.mocked(sendGenericWebhookPayload).mockResolvedValue({ ok: true, status: 200 });
});
describe("access control", () => {
it("should throw FORBIDDEN when user doesn't have access to booking", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(false);
await expect(
reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "This booking was assigned to me incorrectly",
},
})
).rejects.toThrow(TRPCError);
await expect(
reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "This booking was assigned to me incorrectly",
},
})
).rejects.toMatchObject({
code: "FORBIDDEN",
message: "You don't have access to this booking",
});
});
it("should throw NOT_FOUND when booking doesn't exist", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(null);
await expect(
reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "This booking was assigned to me incorrectly",
},
})
).rejects.toMatchObject({
code: "NOT_FOUND",
message: "Booking not found",
});
});
});
describe("successful report", () => {
it("should successfully report with all fields", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);
const result = await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
correctAssignee: "[email protected]",
additionalNotes: "This booking should have gone to the sales team",
},
});
expect(result.success).toBe(true);
expect(result.message).toBe("Wrong assignment reported successfully");
});
it("should successfully report with only required fields (no correctAssignee)", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);
const result = await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "Wrong person received this booking",
},
});
expect(result.success).toBe(true);
expect(result.message).toBe("Wrong assignment reported successfully");
});
});
describe("webhook integration", () => {
it("should send webhook with correct payload structure", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);
vi.mocked(getWebhooks).mockResolvedValue([
{ id: "webhook-1", subscriberUrl: "https://example.com/webhook", secret: "secret123" },
] as never);
await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
correctAssignee: "[email protected]",
additionalNotes: "Wrong assignment notes",
},
});
expect(getWebhooks).toHaveBeenCalledWith({
userId: mockBooking.user.id,
teamId: mockBooking.eventType.teamId,
triggerEvent: WebhookTriggerEvents.WRONG_ASSIGNMENT_REPORT,
});
expect(sendGenericWebhookPayload).toHaveBeenCalledWith(
expect.objectContaining({
triggerEvent: WebhookTriggerEvents.WRONG_ASSIGNMENT_REPORT,
data: expect.objectContaining({
booking: expect.objectContaining({
uid: mockBooking.uid,
id: mockBooking.id,
title: mockBooking.title,
}),
report: expect.objectContaining({
reportedBy: expect.objectContaining({
id: mockUser.id,
email: mockUser.email,
}),
routingReason: "Matched by round-robin",
guest: "[email protected]",
host: expect.objectContaining({
email: "[email protected]",
}),
correctAssignee: "[email protected]",
additionalNotes: "Wrong assignment notes",
}),
}),
})
);
});
it("should handle webhook failures gracefully", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);
vi.mocked(getWebhooks).mockResolvedValue([
{ id: "webhook-1", subscriberUrl: "https://example.com/webhook", secret: "secret123" },
] as never);
vi.mocked(sendGenericWebhookPayload).mockRejectedValue(new Error("Webhook delivery failed"));
const result = await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "Notes",
},
});
expect(result.success).toBe(true);
expect(result.message).toBe("Wrong assignment reported successfully");
});
it("should not fail when getWebhooks throws", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);
vi.mocked(getWebhooks).mockRejectedValue(new Error("Database error"));
const result = await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "Notes",
},
});
expect(result.success).toBe(true);
});
});
describe("edge cases", () => {
it("should handle booking without assignmentReason", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue({
...mockBooking,
assignmentReason: [],
});
vi.mocked(getWebhooks).mockResolvedValue([
{ id: "webhook-1", subscriberUrl: "https://example.com/webhook", secret: "secret123" },
] as never);
await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "Notes",
},
});
expect(sendGenericWebhookPayload).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
report: expect.objectContaining({
routingReason: null,
}),
}),
})
);
});
it("should handle booking without user", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue({
...mockBooking,
user: null,
});
const result = await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "Notes",
},
});
expect(result.success).toBe(true);
expect(getWebhooks).toHaveBeenCalledWith(
expect.objectContaining({
userId: null,
})
);
});
it("should handle booking without eventType", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue({
...mockBooking,
eventType: null,
});
vi.mocked(getWebhooks).mockResolvedValue([
{ id: "webhook-1", subscriberUrl: "https://example.com/webhook", secret: "secret123" },
] as never);
await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "Notes",
},
});
expect(getWebhooks).toHaveBeenCalledWith(
expect.objectContaining({
teamId: null,
})
);
expect(sendGenericWebhookPayload).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
booking: expect.objectContaining({
eventType: null,
}),
}),
})
);
});
it("should handle booking without attendees", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue({
...mockBooking,
attendees: [],
});
vi.mocked(getWebhooks).mockResolvedValue([
{ id: "webhook-1", subscriberUrl: "https://example.com/webhook", secret: "secret123" },
] as never);
await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "Notes",
},
});
expect(sendGenericWebhookPayload).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
report: expect.objectContaining({
guest: "",
}),
}),
})
);
});
});
});
@@ -0,0 +1,122 @@
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { BookingAccessService } from "@calcom/features/bookings/services/BookingAccessService";
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
import { sendGenericWebhookPayload } from "@calcom/features/webhooks/lib/sendPayload";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { TRPCError } from "@trpc/server";
import type { TReportWrongAssignmentInputSchema } from "./reportWrongAssignment.schema";
type ReportWrongAssignmentOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TReportWrongAssignmentInputSchema;
};
const log = logger.getSubLogger({ prefix: ["reportWrongAssignmentHandler"] });
export const reportWrongAssignmentHandler = async ({ ctx, input }: ReportWrongAssignmentOptions) => {
const { user } = ctx;
const { bookingUid, correctAssignee, additionalNotes } = input;
const bookingRepo = new BookingRepository(prisma);
const bookingAccessService = new BookingAccessService(prisma);
const hasAccess = await bookingAccessService.doesUserIdHaveAccessToBooking({
userId: user.id,
bookingUid,
});
if (!hasAccess) {
throw new TRPCError({ code: "FORBIDDEN", message: "You don't have access to this booking" });
}
const booking = await bookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason({ bookingUid });
if (!booking) {
throw new TRPCError({ code: "NOT_FOUND", message: "Booking not found" });
}
const teamId = booking.eventType?.teamId || null;
const bookingUserId = booking.user?.id || null;
const assignmentReason = booking.assignmentReason?.[0];
const guestEmail = booking.attendees[0]?.email || "";
const hostEmail = booking.user?.email || "";
const hostName = booking.user?.name || null;
const webhookPayload = {
booking: {
uid: booking.uid,
id: booking.id,
title: booking.title,
startTime: booking.startTime,
endTime: booking.endTime,
status: booking.status,
eventType: booking.eventType
? {
id: booking.eventType.id,
title: booking.eventType.title,
slug: booking.eventType.slug,
teamId: booking.eventType.teamId,
}
: null,
},
report: {
reportedBy: {
id: user.id,
email: user.email,
name: user.name,
},
routingReason: assignmentReason?.reasonString || null,
guest: guestEmail,
host: {
email: hostEmail,
name: hostName,
},
correctAssignee: correctAssignee || null,
additionalNotes: additionalNotes || null,
},
};
try {
const webhooks = await getWebhooks({
userId: bookingUserId,
teamId,
triggerEvent: WebhookTriggerEvents.WRONG_ASSIGNMENT_REPORT,
});
const webhookPromises = webhooks.map((webhook) =>
sendGenericWebhookPayload({
secretKey: webhook.secret,
triggerEvent: WebhookTriggerEvents.WRONG_ASSIGNMENT_REPORT,
createdAt: new Date().toISOString(),
webhook,
data: webhookPayload,
}).catch((error) => {
log.error(`Failed to send webhook to ${webhook.subscriberUrl}:`, error);
return { ok: false, status: 0 };
})
);
await Promise.allSettled(webhookPromises);
log.info(`Wrong assignment report sent for booking ${bookingUid}`, {
teamId,
userId: bookingUserId,
webhookCount: webhooks.length,
});
} catch (error) {
log.error("Failed to send wrong assignment webhooks:", error);
}
return {
success: true,
message: "Wrong assignment reported successfully",
};
};
@@ -0,0 +1,9 @@
import { z } from "zod";
export const ZReportWrongAssignmentInputSchema = z.object({
bookingUid: z.string(),
correctAssignee: z.string().email().optional(),
additionalNotes: z.string().min(1),
});
export type TReportWrongAssignmentInputSchema = z.infer<typeof ZReportWrongAssignmentInputSchema>;