feat: Write wrong assignment reports to the database (#27405)

* Add DB table for wrong assignment reports

* When report is submitted write to the db

* Prevent duplicate reportings

* test: add migration and tests for WrongAssignmentReport table

Co-Authored-By: [email protected] <[email protected]>

* fix: add unique constraint on bookingUid and booking access check for hasWrongAssignmentReport

- Add @unique constraint on bookingUid in WrongAssignmentReport model to prevent duplicate reports at DB level
- Add booking ownership check using BookingAccessService in hasWrongAssignmentReport endpoint
- Refactor hasWrongAssignmentReport into separate handler and schema files

Addresses Cubic AI review feedback on PR #27405

Co-Authored-By: unknown <>

* feat: add routingFormId to WrongAssignmentReport and fix Select clearing

- Add routingFormId field to WrongAssignmentReport model in schema.prisma
- Add relation to App_RoutingForms_Form with SetNull on delete
- Update WrongAssignmentReportRepository.createReport to accept routingFormId
- Update BookingRepository.findByUidIncludeEventTypeAndTeamAndAssignmentReason to include routedFromRoutingFormReponse
- Extract routingFormId from booking in reportWrongAssignment handler
- Fix Select clearing issue: handle null case when user clears team member selection
- Update tests to include routingFormId field

Co-Authored-By: [email protected] <[email protected]>

* chore: add migration for routingFormId in WrongAssignmentReport

Co-Authored-By: [email protected] <[email protected]>

* fix: address Udit's review comments

- hasWrongAssignmentReport: throw UNAUTHORIZED error instead of returning false
- reportWrongAssignment: add try-catch for Prisma P2002 unique constraint error
- WrongAssignmentReport: add Team relation to teamId field
- WrongAssignmentReportRepository: use findUnique instead of findFirst
- reportWrongAssignment: use i18n for error messages

Co-Authored-By: [email protected] <[email protected]>

* fix: revert hasWrongAssignmentReport to return false when user lacks access

Per PR checklist, hasWrongAssignmentReport should return { hasReport: false }
when user lacks access to booking, not throw an error. This allows the UI
to gracefully treat 'no access' as 'no report exists'.

Co-Authored-By: [email protected] <[email protected]>

* test: update mocks for findUnique and i18n in unit tests

Co-Authored-By: [email protected] <[email protected]>

* fix: throw UNAUTHORIZED in hasWrongAssignmentReport and squash migrations

Co-Authored-By: [email protected] <[email protected]>

* fix: change User relation onDelete from Cascade to SetNull in WrongAssignmentReport

Address Hariom's review feedback:
- Changed reportedById from Int to Int? (nullable)
- Changed reportedBy relation from onDelete: Cascade to onDelete: SetNull
- Updated migration SQL to reflect these changes

This preserves wrong assignment reports even when the reporting user is deleted,
as the data is still useful for analysis.

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-02-10 08:00:01 -03:00
1 parent c3a8301b0c
commit c0504993a6
12 files changed
+513 -2

No files matched your search

@@ -16,6 +16,7 @@ import { ZGetRoutingTraceInputSchema } from "./getRoutingTrace.schema";
import { ZReportBookingInputSchema } from "./reportBooking.schema";
import { ZReportWrongAssignmentInputSchema } from "./reportWrongAssignment.schema";
import { ZRequestRescheduleInputSchema } from "./requestReschedule.schema";
import { ZHasWrongAssignmentReportInputSchema } from "./hasWrongAssignmentReport.schema";
import { bookingsProcedure } from "./util";
import { makeUserActor } from "@calcom/features/booking-audit/lib/makeActor";
export const bookingsRouter = router({
@@ -129,6 +130,16 @@ export const bookingsRouter = router({
input,
});
}),
hasWrongAssignmentReport: authedProcedure
.input(ZHasWrongAssignmentReportInputSchema)
.query(async ({ input, ctx }) => {
const { hasWrongAssignmentReportHandler } = await import("./hasWrongAssignmentReport.handler");
return hasWrongAssignmentReportHandler({
ctx,
input,
});
}),
getBookingHistory: authedProcedure.input(ZGetBookingHistoryInputSchema).query(async ({ input, ctx }) => {
const { getBookingHistoryHandler } = await import("./getBookingHistory.handler");
@@ -0,0 +1,33 @@
import { BookingAccessService } from "@calcom/features/bookings/services/BookingAccessService";
import { WrongAssignmentReportRepository } from "@calcom/features/bookings/repositories/WrongAssignmentReportRepository";
import prisma from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { TRPCError } from "@trpc/server";
import type { THasWrongAssignmentReportInputSchema } from "./hasWrongAssignmentReport.schema";
type HasWrongAssignmentReportOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: THasWrongAssignmentReportInputSchema;
};
export const hasWrongAssignmentReportHandler = async ({ ctx, input }: HasWrongAssignmentReportOptions) => {
const { user } = ctx;
const { bookingUid } = input;
const bookingAccessService = new BookingAccessService(prisma);
const hasAccess = await bookingAccessService.doesUserIdHaveAccessToBooking({
userId: user.id,
bookingUid,
});
if (!hasAccess) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "You don't have access to this booking" });
}
const repo = new WrongAssignmentReportRepository(prisma);
return { hasReport: await repo.existsByBookingUid(bookingUid) };
};
@@ -0,0 +1,7 @@
import { z } from "zod";
export const ZHasWrongAssignmentReportInputSchema = z.object({
bookingUid: z.string(),
});
export type THasWrongAssignmentReportInputSchema = z.infer<typeof ZHasWrongAssignmentReportInputSchema>;
@@ -1,4 +1,5 @@
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { WrongAssignmentReportRepository } from "@calcom/features/bookings/repositories/WrongAssignmentReportRepository";
import { BookingAccessService } from "@calcom/features/bookings/services/BookingAccessService";
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
import { sendGenericWebhookPayload } from "@calcom/features/webhooks/lib/sendPayload";
@@ -8,10 +9,19 @@ 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/repositories/WrongAssignmentReportRepository");
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/server/i18n", () => ({
getTranslation: vi.fn().mockResolvedValue((key: string) => {
const translations: Record<string, string> = {
wrong_assignment_already_reported: "A wrong assignment report has already been submitted for this booking",
};
return translations[key] || key;
}),
}));
vi.mock("@calcom/lib/logger", () => ({
default: {
getSubLogger: () => ({
@@ -49,6 +59,7 @@ describe("reportWrongAssignmentHandler", () => {
teamId: 5,
},
assignmentReason: [{ reasonString: "Matched by round-robin" }],
routedFromRoutingFormReponse: null,
};
const mockBookingRepo = {
@@ -59,12 +70,22 @@ describe("reportWrongAssignmentHandler", () => {
doesUserIdHaveAccessToBooking: vi.fn(),
};
const mockWrongAssignmentReportRepo = {
existsByBookingUid: vi.fn().mockResolvedValue(false),
createReport: vi.fn().mockResolvedValue({ id: "report-uuid-123" }),
};
beforeEach(() => {
vi.clearAllMocks();
mockWrongAssignmentReportRepo.existsByBookingUid.mockResolvedValue(false);
mockWrongAssignmentReportRepo.createReport.mockResolvedValue({ id: "report-uuid-123" });
vi.mocked(BookingRepository).mockImplementation(function () {
return mockBookingRepo;
});
vi.mocked(WrongAssignmentReportRepository).mockImplementation(function () {
return mockWrongAssignmentReportRepo;
});
vi.mocked(BookingAccessService).mockImplementation(function () {
return mockBookingAccessService;
});
@@ -117,6 +138,27 @@ describe("reportWrongAssignmentHandler", () => {
message: "Booking not found",
});
});
it("should throw BAD_REQUEST when a report already exists for the booking", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);
mockWrongAssignmentReportRepo.existsByBookingUid.mockResolvedValue(true);
await expect(
reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "Duplicate report",
},
})
).rejects.toMatchObject({
code: "BAD_REQUEST",
message: "A wrong assignment report has already been submitted for this booking",
});
expect(mockWrongAssignmentReportRepo.createReport).not.toHaveBeenCalled();
});
});
describe("successful report", () => {
@@ -241,6 +283,104 @@ describe("reportWrongAssignmentHandler", () => {
});
});
describe("database persistence", () => {
it("should persist report to database with all fields", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);
await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
correctAssignee: "[email protected]",
additionalNotes: "This booking should have gone to the sales team",
},
});
expect(mockWrongAssignmentReportRepo.createReport).toHaveBeenCalledWith({
bookingUid: "test-booking-uid",
reportedById: mockUser.id,
correctAssignee: "[email protected]",
additionalNotes: "This booking should have gone to the sales team",
teamId: mockBooking.eventType.teamId,
routingFormId: null,
});
});
it("should persist report with null optional fields", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue({
...mockBooking,
eventType: null,
});
await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "Wrong person",
},
});
expect(mockWrongAssignmentReportRepo.createReport).toHaveBeenCalledWith({
bookingUid: "test-booking-uid",
reportedById: mockUser.id,
correctAssignee: null,
additionalNotes: "Wrong person",
teamId: null,
routingFormId: null,
});
});
it("should return reportId in response", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);
const result = await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "Notes",
},
});
expect(result.reportId).toBe("report-uuid-123");
});
it("should throw if database write fails", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);
mockWrongAssignmentReportRepo.createReport.mockRejectedValue(new Error("Database error"));
await expect(
reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "Notes",
},
})
).rejects.toThrow("Database error");
});
it("should persist report even when webhooks fail", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);
vi.mocked(getWebhooks).mockRejectedValue(new Error("Webhook service down"));
const result = await reportWrongAssignmentHandler({
ctx: { user: mockUser },
input: {
bookingUid: "test-booking-uid",
additionalNotes: "Notes",
},
});
expect(mockWrongAssignmentReportRepo.createReport).toHaveBeenCalled();
expect(result.success).toBe(true);
});
});
describe("edge cases", () => {
it("should handle booking without assignmentReason", async () => {
mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);
@@ -1,9 +1,12 @@
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { WrongAssignmentReportRepository } from "@calcom/features/bookings/repositories/WrongAssignmentReportRepository";
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 { getTranslation } from "@calcom/lib/server/i18n";
import prisma from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
@@ -24,7 +27,9 @@ export const reportWrongAssignmentHandler = async ({ ctx, input }: ReportWrongAs
const { user } = ctx;
const { bookingUid, correctAssignee, additionalNotes } = input;
const t = await getTranslation(user.locale ?? "en", "common");
const bookingRepo = new BookingRepository(prisma);
const wrongAssignmentReportRepo = new WrongAssignmentReportRepository(prisma);
const bookingAccessService = new BookingAccessService(prisma);
const hasAccess = await bookingAccessService.doesUserIdHaveAccessToBooking({
@@ -49,6 +54,36 @@ export const reportWrongAssignmentHandler = async ({ ctx, input }: ReportWrongAs
const guestEmail = booking.attendees[0]?.email || "";
const hostEmail = booking.user?.email || "";
const hostName = booking.user?.name || null;
const routingFormId = booking.routedFromRoutingFormReponse?.formId || null;
const alreadyReported = await wrongAssignmentReportRepo.existsByBookingUid(booking.uid);
if (alreadyReported) {
throw new TRPCError({
code: "BAD_REQUEST",
message: t("wrong_assignment_already_reported"),
});
}
let report: { id: string };
try {
report = await wrongAssignmentReportRepo.createReport({
bookingUid: booking.uid,
reportedById: user.id,
correctAssignee: correctAssignee || null,
additionalNotes,
teamId,
routingFormId,
});
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
throw new TRPCError({
code: "BAD_REQUEST",
message: t("wrong_assignment_already_reported"),
});
}
throw error;
}
const webhookPayload = {
booking: {
@@ -118,5 +153,6 @@ export const reportWrongAssignmentHandler = async ({ ctx, input }: ReportWrongAs
return {
success: true,
message: "Wrong assignment reported successfully",
reportId: report.id,
};
};