Scheduling infrastructure for absolutely everyone.
fix: Improve wrong assignment report (#27162)
Joe Au-Yeung06bb99414521
diff --git a/apps/web/components/booking/BookingListItem.tsx b/apps/web/components/booking/BookingListItem.tsxindex ae32df69dba..1c3ca971c79 100644--- a/apps/web/components/booking/BookingListItem.tsx+++ b/apps/web/components/booking/BookingListItem.tsx@@ -552,19 +552,14 @@ function BookingListItem(booking: BookingItemProps) {userTimeZone={userTimeZone}isRescheduled={isRescheduled}onAssignmentReasonClick={- booking.assignmentReason.length > 0 ? () => setIsOpenRoutingTraceSheet(true) : undefined+ booking.assignmentReasonSortedByCreatedAt.length > 0 ? () => setIsOpenRoutingTraceSheet(true) : undefined}/>{isBookingFromRoutingForm && (<WrongAssignmentDialogisOpenDialog={isOpenWrongAssignmentDialog}setIsOpenDialog={setIsOpenWrongAssignmentDialog}- bookingUid={booking.uid}- routingReason={booking.assignmentReason[0]?.reasonString ?? null}- guestEmail={booking.attendees[0]?.email ?? ""}- hostEmail={booking.user?.email ?? ""}- hostName={booking.user?.name ?? null}- teamId={booking.eventType?.team?.id ?? null}+ booking={booking}/>)}</div>@@ -606,7 +601,7 @@ const BookingItemBadges = ({</Badge></Tooltip>)}- {isRejected && !isRescheduled && booking.assignmentReason.length === 0 && (+ {isRejected && !isRescheduled && booking.assignmentReasonSortedByCreatedAt.length === 0 && (<Badge variant="gray" className="ltr:mr-2 rtl:ml-2">{t("rejected")}</Badge>@@ -616,9 +611,9 @@ const BookingItemBadges = ({{booking.eventType.team.name}</Badge>)}- {booking?.assignmentReason.length > 0 && (+ {booking?.assignmentReasonSortedByCreatedAt.length > 0 && (<AssignmentReasonTooltip- assignmentReason={booking.assignmentReason[0]}+ assignmentReason={booking.assignmentReasonSortedByCreatedAt[booking.assignmentReasonSortedByCreatedAt.length - 1]}onClick={onAssignmentReasonClick}/>)}diff --git a/apps/web/components/booking/actions/BookingActionsDropdown.tsx b/apps/web/components/booking/actions/BookingActionsDropdown.tsxindex 9fa6cf76038..a9e029aea7c 100644--- a/apps/web/components/booking/actions/BookingActionsDropdown.tsx+++ b/apps/web/components/booking/actions/BookingActionsDropdown.tsx@@ -458,15 +458,10 @@ export function BookingActionsDropdown({<WrongAssignmentDialogisOpenDialog={isOpenWrongAssignmentDialog}setIsOpenDialog={setIsOpenWrongAssignmentDialog}- bookingUid={booking.uid}- routingReason={booking.assignmentReason[0]?.reasonString ?? null}- guestEmail={booking.attendees[0]?.email ?? ""}- hostEmail={booking.user?.email ?? ""}- hostName={booking.user?.name ?? null}- teamId={booking.eventType?.team?.id ?? null}+ booking={booking}/>)}- {booking.assignmentReason.length > 0 && (+ {booking.assignmentReasonSortedByCreatedAt.length > 0 && (<RoutingTraceSheetisOpen={isOpenRoutingTraceSheet}setIsOpen={setIsOpenRoutingTraceSheet}diff --git a/apps/web/components/booking/actions/bookingActions.test.ts b/apps/web/components/booking/actions/bookingActions.test.tsindex 1c8386d0919..80738880053 100644--- a/apps/web/components/booking/actions/bookingActions.test.ts+++ b/apps/web/components/booking/actions/bookingActions.test.ts@@ -84,7 +84,7 @@ function createMockContext(overrides: Partial<BookingActionContext> = {}): Bookilocation: "integrations:daily",payment: [],seatsReferences: [],- assignmentReason: [],+ assignmentReasonSortedByCreatedAt: [],metadata: null,routedFromRoutingFormReponse: null,listingStatus: "upcoming",diff --git a/apps/web/components/dialog/WrongAssignmentDialog.tsx b/apps/web/components/dialog/WrongAssignmentDialog.tsxindex 4a54339dfe7..8febd4f7bf3 100644--- a/apps/web/components/dialog/WrongAssignmentDialog.tsx+++ b/apps/web/components/dialog/WrongAssignmentDialog.tsx@@ -1,8 +1,10 @@import { Dialog } from "@calcom/features/components/controlled-dialog";import { useCopy } from "@calcom/lib/hooks/useCopy";import { useLocale } from "@calcom/lib/hooks/useLocale";+import type { AssignmentReasonEnum } from "@calcom/prisma/enums";import { trpc } from "@calcom/trpc/react";import { Alert } from "@calcom/ui/components/alert";+import { Badge } from "@calcom/ui/components/badge";import { Button } from "@calcom/ui/components/button";import { DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components/dialog";import { Label, Select, TextArea } from "@calcom/ui/components/form";@@ -12,15 +14,32 @@ import type { Dispatch, SetStateAction } from "react";import type { Control, ControllerRenderProps } from "react-hook-form";import { Controller, useForm } from "react-hook-form";+import assignmentReasonBadgeTitleMap from "@lib/booking/assignmentReasonBadgeTitleMap";++interface BookingData {+ uid: string;+ eventType?: {+ team?: {+ id: number;+ } | null;+ } | null;+ user?: {+ email: string;+ name: string | null;+ } | null;+ assignmentReasonSortedByCreatedAt: Array<{+ reasonString: string | null;+ reasonEnum: AssignmentReasonEnum | null;+ }>;+ attendees: Array<{+ email: string;+ }>;+}+interface IWrongAssignmentDialog {isOpenDialog: boolean;setIsOpenDialog: Dispatch<SetStateAction<boolean>>;- bookingUid: string;- routingReason: string | null;- guestEmail: string;- hostEmail: string;- hostName: string | null;- teamId: number | null;+ booking: BookingData;}interface FormValues {@@ -36,6 +55,7 @@ interface TeamMemberOption {interface RoutingInfoSectionProps {routingReason: string | null;+ routingReasonEnum: AssignmentReasonEnum | null;noRoutingReasonText: string;routingReasonLabel: string;guestEmail: string;@@ -48,8 +68,10 @@ interface RoutingInfoSectionProps {}function RoutingInfoSection(props: RoutingInfoSectionProps): JSX.Element {+ const { t } = useLocale();const {routingReason,+ routingReasonEnum,noRoutingReasonText,routingReasonLabel,guestEmail,@@ -79,9 +101,14 @@ function RoutingInfoSection(props: RoutingInfoSectionProps): JSX.Element {<div className="-mt-2 mb-4 space-y-3"><div><Label className="text-emphasis mb-1 block text-sm font-medium">{routingReasonLabel}</Label>- <p className="text-default bg-muted rounded-md px-3 py-2 text-sm">- {routingReason || noRoutingReasonText}- </p>+ <div className="text-default bg-muted flex items-center gap-2 rounded-md px-3 py-2 text-sm">+ {routingReasonEnum && (+ <Badge variant="gray" className="shrink-0">+ {t(assignmentReasonBadgeTitleMap(routingReasonEnum))}+ </Badge>+ )}+ <span className="flex-1">{routingReason || noRoutingReasonText}</span>+ </div></div><div>@@ -212,16 +239,15 @@ export function WrongAssignmentDialog(props: IWrongAssignmentDialog): JSX.Elemenconst { t } = useLocale();const utils = trpc.useUtils();const { copyToClipboard, isCopied } = useCopy();- const {- isOpenDialog,- setIsOpenDialog,- bookingUid,- routingReason,- guestEmail,- hostEmail,- hostName,- teamId,- } = props;+ const { isOpenDialog, setIsOpenDialog, booking } = props;++ const bookingUid = booking.uid;+ const teamId = booking.eventType?.team?.id ?? null;+ const routingReason = booking.assignmentReasonSortedByCreatedAt[0]?.reasonString ?? null;+ const routingReasonEnum = booking.assignmentReasonSortedByCreatedAt[0]?.reasonEnum ?? null;+ const guestEmail = booking.attendees[0]?.email ?? "";+ const hostEmail = booking.user?.email ?? "";+ const hostName = booking.user?.name ?? null;const {control,@@ -286,8 +312,9 @@ export function WrongAssignmentDialog(props: IWrongAssignmentDialog): JSX.Elemen<RoutingInfoSectionroutingReason={routingReason}+ routingReasonEnum={routingReasonEnum}noRoutingReasonText={t("no_routing_reason")}- routingReasonLabel={t("routing_reason")}+ routingReasonLabel={t("first_assignment_reason")}guestEmail={guestEmail}whoBookedItLabel={t("who_booked_it")}hostEmail={hostEmail}diff --git a/apps/web/modules/bookings/components/BookingDetailsSheet.tsx b/apps/web/modules/bookings/components/BookingDetailsSheet.tsxindex ca4a2191d54..3030428d1dd 100644--- a/apps/web/modules/bookings/components/BookingDetailsSheet.tsx+++ b/apps/web/modules/bookings/components/BookingDetailsSheet.tsx@@ -215,7 +215,7 @@ function BookingDetailsSheetInner({.map(([question, answer]) => [question, answer] as [string, unknown]): [];- const reason = booking.assignmentReason?.[0];+ const reason = booking.assignmentReasonSortedByCreatedAt?.[booking.assignmentReasonSortedByCreatedAt.length - 1];const reasonTitle = reason && assignmentReasonBadgeTitleMap(reason.reasonEnum);return (@@ -597,12 +597,12 @@ function RecurringInfoSection({function AssignmentReasonSection({ booking }: { booking: BookingOutput }) {const { t } = useLocale();- if (!booking.assignmentReason || booking.assignmentReason.length === 0) {+ if (!booking.assignmentReasonSortedByCreatedAt || booking.assignmentReasonSortedByCreatedAt.length === 0) {return null;}- // we fetch only one assignment reason.- const reason = booking.assignmentReason[0];+ const reason =+ booking.assignmentReasonSortedByCreatedAt[booking.assignmentReasonSortedByCreatedAt.length - 1];if (!reason.reasonString) {return null;}diff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.jsonindex 6b01c57918d..fc59e692700 100644--- a/apps/web/public/static/locales/en/common.json+++ b/apps/web/public/static/locales/en/common.json@@ -848,6 +848,7 @@"wrong_assignment_reported": "Wrong assignment reported successfully","wrong_assignment_already_reported": "A wrong assignment report has already been submitted for this booking.","routing_reason": "Routing Reason",+ "first_assignment_reason": "First Assignment Reason","no_routing_reason": "No routing reason available","who_booked_it": "Who booked it?","who_received_it": "Who received it?",diff --git a/packages/features/bookings/repositories/BookingRepository.ts b/packages/features/bookings/repositories/BookingRepository.tsindex fc2780312f9..cbf6a66896a 100644--- a/packages/features/bookings/repositories/BookingRepository.ts+++ b/packages/features/bookings/repositories/BookingRepository.ts@@ -2123,11 +2123,22 @@ export class BookingRepository implements IBookingRepository {});}- async findByUidIncludeEventTypeAndTeamAndAssignmentReason({ bookingUid }: { bookingUid: string }) {+ async updateRecordedStatus({+ bookingUid,+ isRecorded,+ }: {+ bookingUid: string;+ isRecorded: boolean;+ }): Promise<void> {+ await this.prismaClient.booking.update({+ where: { uid: bookingUid },+ data: { isRecorded },+ });+ }++ async findByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason({ bookingUid }: { bookingUid: string }) {return await this.prismaClient.booking.findUnique({- where: {- uid: bookingUid,- },+ where: { uid: bookingUid },select: {id: true,uid: true,@@ -2135,15 +2146,10 @@ export class BookingRepository implements IBookingRepository {startTime: true,endTime: true,status: true,+ userId: true,user: {select: {id: true,- name: true,- email: true,- },- },- attendees: {- select: {email: true,name: true,},@@ -2153,13 +2159,26 @@ export class BookingRepository implements IBookingRepository {id: true,title: true,slug: true,- teamId: true,+ team: {+ select: {+ id: true,+ parentId: true,+ },+ },+ },+ },+ attendees: {+ select: {+ email: true,},},assignmentReason: {select: {reasonString: true,- reasonEnum: true,+ },+ take: 1,+ orderBy: {+ createdAt: "asc" as const,},},routedFromRoutingFormReponse: {@@ -2170,17 +2189,4 @@ export class BookingRepository implements IBookingRepository {},});}-- async updateRecordedStatus({- bookingUid,- isRecorded,- }: {- bookingUid: string;- isRecorded: boolean;- }): Promise<void> {- await this.prismaClient.booking.update({- where: { uid: bookingUid },- data: { isRecorded },- });- }}diff --git a/packages/trpc/server/routers/viewer/bookings/get.handler.ts b/packages/trpc/server/routers/viewer/bookings/get.handler.tsindex 4c64b466bbd..fe51492b3cd 100644--- a/packages/trpc/server/routers/viewer/bookings/get.handler.ts+++ b/packages/trpc/server/routers/viewer/bookings/get.handler.ts@@ -631,9 +631,8 @@ export async function getBookings({.selectFrom("AssignmentReason").selectAll().whereRef("AssignmentReason.bookingId", "=", "Booking.id")- .orderBy("AssignmentReason.createdAt", "desc")- .limit(1)- ).as("assignmentReason"),+ .orderBy("AssignmentReason.createdAt", "asc")+ ).as("assignmentReasonSortedByCreatedAt"),jsonObjectFrom(eb.selectFrom("BookingReport")diff --git a/packages/trpc/server/routers/viewer/bookings/reportWrongAssignment.handler.test.ts b/packages/trpc/server/routers/viewer/bookings/reportWrongAssignment.handler.test.tsindex c8df4b6e12f..6e358c4cabc 100644--- a/packages/trpc/server/routers/viewer/bookings/reportWrongAssignment.handler.test.ts+++ b/packages/trpc/server/routers/viewer/bookings/reportWrongAssignment.handler.test.ts@@ -1,6 +1,3 @@-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 { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";@@ -8,12 +5,39 @@ 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/repositories/WrongAssignmentReportRepository");-vi.mock("@calcom/features/bookings/services/BookingAccessService");+const mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason = vi.fn();+const mockDoesUserIdHaveAccessToBooking = vi.fn();+const mockExistsByBookingUid = vi.fn();+const mockCreateReport = vi.fn();++vi.mock("@calcom/features/bookings/repositories/BookingRepository", () => {+ return {+ BookingRepository: class MockBookingRepository {+ findByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason =+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason;+ },+ };+});+vi.mock("@calcom/features/bookings/repositories/WrongAssignmentReportRepository", () => {+ return {+ WrongAssignmentReportRepository: class MockWrongAssignmentReportRepository {+ existsByBookingUid = mockExistsByBookingUid;+ createReport = mockCreateReport;+ },+ };+});+vi.mock("@calcom/features/bookings/services/BookingAccessService", () => {+ return {+ BookingAccessService: class MockBookingAccessService {+ doesUserIdHaveAccessToBooking = mockDoesUserIdHaveAccessToBooking;+ },+ };+});vi.mock("@calcom/features/webhooks/lib/getWebhooks");vi.mock("@calcom/features/webhooks/lib/sendPayload");-vi.mock("@calcom/prisma", () => ({ default: {} }));+vi.mock("@calcom/prisma", () => ({+ default: {},+}));vi.mock("@calcom/lib/server/i18n", () => ({getTranslation: vi.fn().mockResolvedValue((key: string) => {const translations: Record<string, string> = {@@ -39,6 +63,11 @@ describe("reportWrongAssignmentHandler", () => {name: "Reporter User",};+ const mockInput = {+ bookingUid: "test-booking-uid",+ additionalNotes: "This booking was assigned to me incorrectly",+ };+const mockBooking = {id: 100,uid: "test-booking-uid",@@ -46,74 +75,51 @@ describe("reportWrongAssignmentHandler", () => {startTime: new Date("2025-12-01T10:00:00Z"),endTime: new Date("2025-12-01T11:00:00Z"),status: BookingStatus.ACCEPTED,+ userId: 2,user: {id: 2,email: "[email protected]",name: "Host User",},- attendees: [{ email: "[email protected]" }],eventType: {id: 10,title: "Test Event",slug: "test-event",- teamId: 5,+ team: {+ id: 5,+ parentId: 1,+ },},+ attendees: [{ email: "[email protected]" }],assignmentReason: [{ reasonString: "Matched by round-robin" }],routedFromRoutingFormReponse: null,};- const mockBookingRepo = {- findByUidIncludeEventTypeAndTeamAndAssignmentReason: vi.fn(),- };-- const mockBookingAccessService = {- 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;- });+ mockExistsByBookingUid.mockResolvedValue(false);+ mockCreateReport.mockResolvedValue({ id: "report-uuid-123" });vi.mocked(getWebhooks).mockResolvedValue([]);vi.mocked(sendGenericWebhookPayload).mockResolvedValue({ ok: true, status: 200 });+ mockDoesUserIdHaveAccessToBooking.mockResolvedValue(true);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue(mockBooking);});describe("access control", () => {- it("should throw FORBIDDEN when user doesn't have access to booking", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(false);+ it("should throw FORBIDDEN when BookingAccessService denies access", async () => {+ mockDoesUserIdHaveAccessToBooking.mockResolvedValue(false);await expect(reportWrongAssignmentHandler({ctx: { user: mockUser },- input: {- bookingUid: "test-booking-uid",- additionalNotes: "This booking was assigned to me incorrectly",- },+ input: mockInput,})).rejects.toThrow(TRPCError);await expect(reportWrongAssignmentHandler({ctx: { user: mockUser },- input: {- bookingUid: "test-booking-uid",- additionalNotes: "This booking was assigned to me incorrectly",- },+ input: mockInput,})).rejects.toMatchObject({code: "FORBIDDEN",@@ -122,16 +128,20 @@ describe("reportWrongAssignmentHandler", () => {});it("should throw NOT_FOUND when booking doesn't exist", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(null);+ mockDoesUserIdHaveAccessToBooking.mockResolvedValue(true);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue(null);await expect(reportWrongAssignmentHandler({ctx: { user: mockUser },- input: {- bookingUid: "test-booking-uid",- additionalNotes: "This booking was assigned to me incorrectly",- },+ input: mockInput,+ })+ ).rejects.toThrow(TRPCError);++ await expect(+ reportWrongAssignmentHandler({+ ctx: { user: mockUser },+ input: mockInput,})).rejects.toMatchObject({code: "NOT_FOUND",@@ -139,10 +149,29 @@ describe("reportWrongAssignmentHandler", () => {});});+ it("should allow access when BookingAccessService grants access", async () => {+ mockDoesUserIdHaveAccessToBooking.mockResolvedValue(true);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue({+ ...mockBooking,+ userId: mockUser.id,+ });++ const result = await reportWrongAssignmentHandler({+ ctx: { user: mockUser },+ input: mockInput,+ });++ expect(result.success).toBe(true);+ expect(mockDoesUserIdHaveAccessToBooking).toHaveBeenCalledWith({+ userId: mockUser.id,+ bookingUid: mockInput.bookingUid,+ });+ });+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);+ mockDoesUserIdHaveAccessToBooking.mockResolvedValue(true);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue(mockBooking);+ mockExistsByBookingUid.mockResolvedValue(true);await expect(reportWrongAssignmentHandler({@@ -157,19 +186,21 @@ describe("reportWrongAssignmentHandler", () => {message: "A wrong assignment report has already been submitted for this booking",});- expect(mockWrongAssignmentReportRepo.createReport).not.toHaveBeenCalled();+ expect(mockCreateReport).not.toHaveBeenCalled();});});describe("successful report", () => {it("should successfully report with all fields", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue({+ ...mockBooking,+ userId: mockUser.id,+ });const result = await reportWrongAssignmentHandler({ctx: { user: mockUser },input: {- bookingUid: "test-booking-uid",+ ...mockInput,correctAssignee: "[email protected]",additionalNotes: "This booking should have gone to the sales team",},@@ -180,13 +211,15 @@ describe("reportWrongAssignmentHandler", () => {});it("should successfully report with only required fields (no correctAssignee)", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue({+ ...mockBooking,+ userId: mockUser.id,+ });const result = await reportWrongAssignmentHandler({ctx: { user: mockUser },input: {- bookingUid: "test-booking-uid",+ ...mockInput,additionalNotes: "Wrong person received this booking",},});@@ -198,8 +231,10 @@ describe("reportWrongAssignmentHandler", () => {describe("webhook integration", () => {it("should send webhook with correct payload structure", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue({+ ...mockBooking,+ userId: mockUser.id,+ });vi.mocked(getWebhooks).mockResolvedValue([{ id: "webhook-1", subscriberUrl: "https://example.com/webhook", secret: "secret123" },] as never);@@ -207,15 +242,16 @@ describe("reportWrongAssignmentHandler", () => {await reportWrongAssignmentHandler({ctx: { user: mockUser },input: {- bookingUid: "test-booking-uid",+ ...mockInput,correctAssignee: "[email protected]",additionalNotes: "Wrong assignment notes",},});expect(getWebhooks).toHaveBeenCalledWith({- userId: mockBooking.user.id,- teamId: mockBooking.eventType.teamId,+ userId: mockUser.id,+ teamId: mockBooking.eventType.team.id,+ orgId: mockBooking.eventType.team.parentId,triggerEvent: WebhookTriggerEvents.WRONG_ASSIGNMENT_REPORT,});@@ -233,10 +269,10 @@ describe("reportWrongAssignmentHandler", () => {id: mockUser.id,email: mockUser.email,}),- routingReason: "Matched by round-robin",- guest: "[email protected]",+ firstAssignmentReason: mockBooking.assignmentReason[0].reasonString,+ guest: mockBooking.attendees[0].email,host: expect.objectContaining({- email: "[email protected]",+ email: mockBooking.user.email,}),correctAssignee: "[email protected]",additionalNotes: "Wrong assignment notes",@@ -247,8 +283,10 @@ describe("reportWrongAssignmentHandler", () => {});it("should handle webhook failures gracefully", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue({+ ...mockBooking,+ userId: mockUser.id,+ });vi.mocked(getWebhooks).mockResolvedValue([{ id: "webhook-1", subscriberUrl: "https://example.com/webhook", secret: "secret123" },] as never);@@ -256,10 +294,7 @@ describe("reportWrongAssignmentHandler", () => {const result = await reportWrongAssignmentHandler({ctx: { user: mockUser },- input: {- bookingUid: "test-booking-uid",- additionalNotes: "Notes",- },+ input: mockInput,});expect(result.success).toBe(true);@@ -267,16 +302,15 @@ describe("reportWrongAssignmentHandler", () => {});it("should not fail when getWebhooks throws", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue({+ ...mockBooking,+ userId: mockUser.id,+ });vi.mocked(getWebhooks).mockRejectedValue(new Error("Database error"));const result = await reportWrongAssignmentHandler({ctx: { user: mockUser },- input: {- bookingUid: "test-booking-uid",- additionalNotes: "Notes",- },+ input: mockInput,});expect(result.success).toBe(true);@@ -285,8 +319,8 @@ describe("reportWrongAssignmentHandler", () => {describe("database persistence", () => {it("should persist report to database with all fields", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);+ mockDoesUserIdHaveAccessToBooking.mockResolvedValue(true);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue(mockBooking);await reportWrongAssignmentHandler({ctx: { user: mockUser },@@ -297,19 +331,19 @@ describe("reportWrongAssignmentHandler", () => {},});- expect(mockWrongAssignmentReportRepo.createReport).toHaveBeenCalledWith({+ expect(mockCreateReport).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,+ teamId: mockBooking.eventType.team.id,routingFormId: null,});});it("should persist report with null optional fields", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue({+ mockDoesUserIdHaveAccessToBooking.mockResolvedValue(true);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue({...mockBooking,eventType: null,});@@ -322,7 +356,7 @@ describe("reportWrongAssignmentHandler", () => {},});- expect(mockWrongAssignmentReportRepo.createReport).toHaveBeenCalledWith({+ expect(mockCreateReport).toHaveBeenCalledWith({bookingUid: "test-booking-uid",reportedById: mockUser.id,correctAssignee: null,@@ -333,8 +367,8 @@ describe("reportWrongAssignmentHandler", () => {});it("should return reportId in response", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);+ mockDoesUserIdHaveAccessToBooking.mockResolvedValue(true);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue(mockBooking);const result = await reportWrongAssignmentHandler({ctx: { user: mockUser },@@ -348,9 +382,9 @@ describe("reportWrongAssignmentHandler", () => {});it("should throw if database write fails", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);- mockWrongAssignmentReportRepo.createReport.mockRejectedValue(new Error("Database error"));+ mockDoesUserIdHaveAccessToBooking.mockResolvedValue(true);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue(mockBooking);+ mockCreateReport.mockRejectedValue(new Error("Database error"));await expect(reportWrongAssignmentHandler({@@ -364,8 +398,8 @@ describe("reportWrongAssignmentHandler", () => {});it("should persist report even when webhooks fail", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue(mockBooking);+ mockDoesUserIdHaveAccessToBooking.mockResolvedValue(true);+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue(mockBooking);vi.mocked(getWebhooks).mockRejectedValue(new Error("Webhook service down"));const result = await reportWrongAssignmentHandler({@@ -376,16 +410,16 @@ describe("reportWrongAssignmentHandler", () => {},});- expect(mockWrongAssignmentReportRepo.createReport).toHaveBeenCalled();+ expect(mockCreateReport).toHaveBeenCalled();expect(result.success).toBe(true);});});describe("edge cases", () => {it("should handle booking without assignmentReason", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue({+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue({...mockBooking,+ userId: mockUser.id,assignmentReason: [],});vi.mocked(getWebhooks).mockResolvedValue([@@ -394,17 +428,14 @@ describe("reportWrongAssignmentHandler", () => {await reportWrongAssignmentHandler({ctx: { user: mockUser },- input: {- bookingUid: "test-booking-uid",- additionalNotes: "Notes",- },+ input: mockInput,});expect(sendGenericWebhookPayload).toHaveBeenCalledWith(expect.objectContaining({data: expect.objectContaining({report: expect.objectContaining({- routingReason: null,+ firstAssignmentReason: null,}),}),})@@ -412,18 +443,16 @@ describe("reportWrongAssignmentHandler", () => {});it("should handle booking without user", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue({+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue({...mockBooking,+ userId: null,user: null,+ attendees: [{ email: mockUser.email }],});const result = await reportWrongAssignmentHandler({ctx: { user: mockUser },- input: {- bookingUid: "test-booking-uid",- additionalNotes: "Notes",- },+ input: mockInput,});expect(result.success).toBe(true);@@ -435,9 +464,9 @@ describe("reportWrongAssignmentHandler", () => {});it("should handle booking without eventType", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue({+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue({...mockBooking,+ userId: mockUser.id,eventType: null,});vi.mocked(getWebhooks).mockResolvedValue([@@ -446,15 +475,13 @@ describe("reportWrongAssignmentHandler", () => {await reportWrongAssignmentHandler({ctx: { user: mockUser },- input: {- bookingUid: "test-booking-uid",- additionalNotes: "Notes",- },+ input: mockInput,});expect(getWebhooks).toHaveBeenCalledWith(expect.objectContaining({teamId: null,+ orgId: null,}));expect(sendGenericWebhookPayload).toHaveBeenCalledWith(@@ -469,9 +496,9 @@ describe("reportWrongAssignmentHandler", () => {});it("should handle booking without attendees", async () => {- mockBookingAccessService.doesUserIdHaveAccessToBooking.mockResolvedValue(true);- mockBookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason.mockResolvedValue({+ mockFindByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason.mockResolvedValue({...mockBooking,+ userId: mockUser.id,attendees: [],});vi.mocked(getWebhooks).mockResolvedValue([@@ -480,17 +507,14 @@ describe("reportWrongAssignmentHandler", () => {await reportWrongAssignmentHandler({ctx: { user: mockUser },- input: {- bookingUid: "test-booking-uid",- additionalNotes: "Notes",- },+ input: mockInput,});expect(sendGenericWebhookPayload).toHaveBeenCalledWith(expect.objectContaining({data: expect.objectContaining({report: expect.objectContaining({- guest: "",+ guest: null,}),}),})diff --git a/packages/trpc/server/routers/viewer/bookings/reportWrongAssignment.handler.ts b/packages/trpc/server/routers/viewer/bookings/reportWrongAssignment.handler.tsindex 26eef6a62bc..885df86fc89 100644--- a/packages/trpc/server/routers/viewer/bookings/reportWrongAssignment.handler.ts+++ b/packages/trpc/server/routers/viewer/bookings/reportWrongAssignment.handler.ts@@ -28,7 +28,7 @@ export const reportWrongAssignmentHandler = async ({ ctx, input }: ReportWrongAsconst { bookingUid, correctAssignee, additionalNotes } = input;const t = await getTranslation(user.locale ?? "en", "common");- const bookingRepo = new BookingRepository(prisma);+ const bookingRepository = new BookingRepository(prisma);const wrongAssignmentReportRepo = new WrongAssignmentReportRepository(prisma);const bookingAccessService = new BookingAccessService(prisma);@@ -41,19 +41,16 @@ export const reportWrongAssignmentHandler = async ({ ctx, input }: ReportWrongAsthrow new TRPCError({ code: "FORBIDDEN", message: "You don't have access to this booking" });}- const booking = await bookingRepo.findByUidIncludeEventTypeAndTeamAndAssignmentReason({ bookingUid });+ const booking = await bookingRepository.findByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason({+ 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 teamId = booking.eventType?.team?.id ?? null;+ const orgId = booking.eventType?.team?.parentId ?? null;const routingFormId = booking.routedFromRoutingFormReponse?.formId || null;const alreadyReported = await wrongAssignmentReportRepo.existsByBookingUid(booking.uid);@@ -98,7 +95,7 @@ export const reportWrongAssignmentHandler = async ({ ctx, input }: ReportWrongAsid: booking.eventType.id,title: booking.eventType.title,slug: booking.eventType.slug,- teamId: booking.eventType.teamId,+ teamId: teamId,}: null,},@@ -108,11 +105,11 @@ export const reportWrongAssignmentHandler = async ({ ctx, input }: ReportWrongAsemail: user.email,name: user.name,},- routingReason: assignmentReason?.reasonString || null,- guest: guestEmail,+ firstAssignmentReason: booking.assignmentReason[0]?.reasonString ?? null,+ guest: booking.attendees[0]?.email ?? null,host: {- email: hostEmail,- name: hostName,+ email: booking.user?.email ?? null,+ name: booking.user?.name ?? null,},correctAssignee: correctAssignee || null,additionalNotes: additionalNotes || null,@@ -121,8 +118,9 @@ export const reportWrongAssignmentHandler = async ({ ctx, input }: ReportWrongAstry {const webhooks = await getWebhooks({- userId: bookingUserId,+ userId: booking.userId,teamId,+ orgId,triggerEvent: WebhookTriggerEvents.WRONG_ASSIGNMENT_REPORT,});@@ -141,9 +139,9 @@ export const reportWrongAssignmentHandler = async ({ ctx, input }: ReportWrongAsawait Promise.allSettled(webhookPromises);- log.info(`Wrong assignment report sent for booking ${bookingUid}`, {+ log.info(`Wrong assignment report sent for booking ${booking.uid}`, {teamId,- userId: bookingUserId,+ userId: booking.userId,webhookCount: webhooks.length,});} catch (error) {diff --git a/packages/trpc/server/routers/viewer/bookings/reportWrongAssignment.schema.ts b/packages/trpc/server/routers/viewer/bookings/reportWrongAssignment.schema.tsindex 70caaa6dc28..fa426af5c32 100644--- a/packages/trpc/server/routers/viewer/bookings/reportWrongAssignment.schema.ts+++ b/packages/trpc/server/routers/viewer/bookings/reportWrongAssignment.schema.ts@@ -2,7 +2,7 @@ import { z } from "zod";export const ZReportWrongAssignmentInputSchema = z.object({bookingUid: z.string(),- correctAssignee: z.string().email().optional(),+ correctAssignee: z.union([z.string().email(), z.literal("").transform(() => undefined)]).optional(),additionalNotes: z.string().min(1),});