chore: Integrate round-robin reassignment booking audit (#26586)

## What does this PR do?

Implements booking audit logging for round-robin reassignment events (both manual and automatic). This is part of the booking audit integration plan (PR 7).

Changes:
- Added audit logging to `roundRobinManualReassignment.ts` for manual host reassignments
- Added audit logging to `roundRobinReassignment.ts` for automatic round-robin reassignments
- Updated tRPC handlers to pass `actionSource: "WEBAPP"` and `reassignedByUuid`
- Updated API v2 bookings service to pass `actionSource: "API_V2"` and `reassignedByUuid`
- Updated `ReassignmentAuditActionService.ts` with proper field schemas and translation keys

The audit logging uses `BookingEventHandlerService.onReassignment()` with proper actor identification and action source tracking.

## Updates since last revision

Addressed review feedback:
- Renamed `title` field to `hostName` for semantic clarity (tracks host name changes, not booking titles)
- Fixed `assignedById` schema: changed from `NumberChangeSchema` to `z.number()` (no old/new pattern needed - it's always the user who performed the reassignment)
- Fixed `reassignmentReason` schema: changed from `StringChangeSchema` to `z.string().nullable()` (no old/new pattern needed)
- Added `ValidActionSource` type that excludes `UNKNOWN` - clients must pass explicit action sources
- Made `actionSource` required in both reassignment functions (no longer optional)
- Added integration tests for `ReassignmentAuditActionService` (15 tests covering all methods)
- Updated `roundRobinManualReassign.handler.ts` to pass required `actionSource` and `reassignedByUuid` params

**Latest fixes:**
- Fixed `hasAttendeeUpdated` check in `ReassignmentAuditActionService.ts`: changed from `!== null` to `!= null` to properly handle undefined values
- Updated test expectations in `ReassignmentAuditActionService.test.ts` to match the new display JSON field names (`hostAttendeeUserUuidNew`/`hostAttendeeUserUuidOld` instead of `newAssignedRRHostUuid`/`previousAssignedRRHostUuid`)
- Fixed async `getDisplayFields` tests to properly await the Promise and include the `previous_assignee` field
- Fixed `hasAttendeeUpdated` to check for `hostAttendeeUpdated` object presence instead of optional `id` field - host changes with only `withUserUuid` populated were being ignored (identified by Cubic AI, confidence 9/10)
- Fixed test expectation in `getDisplayJson` test: removed incorrect null expectations for `hostAttendeeIdUpdated`, `hostAttendeeUserUuidNew`, `hostAttendeeUserUuidOld` - the implementation uses conditional spreading to omit these fields when `hostAttendeeUpdated` is not present, rather than setting them to null

## Mandatory Tasks (DO NOT REMOVE)

- [x] I have self-reviewed the code (A decent size PR without self-review might be rejected).
- [x] I have updated the developer docs in /docs if this PR makes changes that would require a [documentation change](https://cal.com/docs). N/A - no documentation changes needed.
- [x] I confirm automated tests are in place that prove my fix is effective or that my feature works.

## How should this be tested?

1. Trigger a manual round-robin reassignment via the webapp and verify audit logs are created with `actionSource: "WEBAPP"`
2. Trigger an automatic round-robin reassignment and verify audit logs are created
3. Use API v2 to reassign a booking and verify audit logs are created with `actionSource: "API_V2"`
4. Verify the audit data contains correct values for `organizerUuid`, `hostAttendeeUpdated`, `reassignmentReason`, and `reassignmentType`

## Checklist

- [x] My code follows the style guidelines of this project
- [x] I have checked if my changes generate no new warnings

## Human Review Checklist


- [x] Verify the `hasAttendeeUpdated` fix is correct: now checks `fields.hostAttendeeUpdated != null` to detect any host attendee update regardless of whether `id` is populated
- [x] Verify `getDisplayJson` test fix: fields are correctly omitted (not set to null) when `hostAttendeeUpdated` is not present, matching the conditional spreading implementation
- [ ] Verify all callers of reassignment functions pass required `actionSource` and `reassignedByUuid`
- [ ] Confirm `getDisplayFields` is properly awaited in all call sites (it's now async)
- [ ] Check that `ValidActionSource` type properly excludes `UNKNOWN` for client-side validation

## Important Notes for Reviewer

1. **Dependency on base PR**: The translation key changes use the format from base PR (#26046). This PR should be merged after the base PR.

2. **Schema changes**: The `organizerUuid` and `hostAttendeeUpdated` fields track both organizer changes and round-robin host attendee changes separately for complete audit trail.

---


Link to Devin run: https://app.devin.ai/sessions/e4353e2ec6ea4a51ab33313bdc630aba
Requested by: @hariombalhara
This commit is contained in:
Hariom Balhara authored and GitHub committed 2026-01-23 08:13:22 +05:30
1 parent 45c9f19b70
commit 95f7f03f0e
14 files changed
+1142 -244

No files matched your search

@@ -1,33 +1,35 @@
import prismaMock from "@calcom/testing/lib/__mocks__/prisma";
import {
getDate,
createBookingScenario,
getScenarioData,
getMockBookingAttendee,
TestData,
addWorkflowReminders,
createBookingScenario,
getDate,
getMockBookingAttendee,
getScenarioData,
TestData,
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { OrganizerDefaultConferencingAppType } from "@calcom/app-store/locations";
import { getBookingEventHandlerService } from "@calcom/features/bookings/di/BookingEventHandlerService.container";
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { BookingStatus, SchedulingType, WorkflowMethods } from "@calcom/prisma/enums";
import {
expectBookingToBeInDatabase,
expectSuccessfulRoundRobinReschedulingEmails,
expectWorkflowToBeTriggered,
} from "@calcom/testing/lib/bookingScenario/expects";
import { setupAndTeardown } from "@calcom/testing/lib/bookingScenario/setupAndTeardown";
import { describe, vi, expect } from "vitest";
import { v4 as uuidv4 } from "uuid";
import { parse } from "node-html-parser";
import { OrganizerDefaultConferencingAppType } from "@calcom/app-store/locations";
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { SchedulingType, BookingStatus, WorkflowMethods } from "@calcom/prisma/enums";
import { test } from "@calcom/testing/lib/fixtures/fixtures";
import { parse } from "node-html-parser";
import { v4 as uuidv4 } from "uuid";
import { beforeEach, describe, expect, vi } from "vitest";
import type { BookingEventHandlerService } from "../../bookings/lib/onBookingEvents/BookingEventHandlerService";
vi.mock("@calcom/features/bookings/lib/EventManager");
vi.mock("@calcom/app-store/utils", () => ({
getAppFromSlug: vi.fn(),
}));
vi.mock("@calcom/features/bookings/di/BookingEventHandlerService.container", () => ({
getBookingEventHandlerService: vi.fn(),
}));
// Type definitions
type TestUserMetadata = {
@@ -58,6 +60,7 @@ const createTestUser = (overrides?: {
email?: string;
destinationCalendar?: { integration: string; externalId: string };
metadata?: TestUserMetadata;
uuid?: string;
}) => ({
id: overrides?.id ?? 1,
name: overrides?.name ?? `user-${overrides?.id ?? 1}`,
@@ -79,6 +82,7 @@ const createTestUser = (overrides?: {
completedOnboarding: true,
locked: false,
organizationId: null,
uuid: overrides?.uuid ?? `uuid-${overrides?.id ?? 1}`,
});
const createTestDestinationCalendar = (overrides?: { integration?: string; externalId?: string }) => ({
@@ -222,8 +226,8 @@ const mockEventManagerReschedule = async (config?: MockEventManagerConfig) => {
conferenceType === "zoom"
? "https://zoom.us/j/123456789"
: conferenceType === "google"
? "https://meet.google.com/test-meeting"
: `https://${conferenceType}.co/test-room`,
? "https://meet.google.com/test-meeting"
: `https://${conferenceType}.co/test-room`,
},
});
}
@@ -243,6 +247,14 @@ const mockGetAppFromSlug = async () => {
describe("roundRobinManualReassignment test", () => {
setupAndTeardown();
beforeEach(() => {
// Set up default mock for BookingEventHandlerService
const mockOnReassignment = vi.fn().mockResolvedValue(undefined);
vi.mocked(getBookingEventHandlerService).mockReturnValue({
onReassignment: mockOnReassignment,
} as unknown as BookingEventHandlerService);
});
test("should reassign round robin booking to new host and update workflows", async ({ emails }) => {
const roundRobinManualReassignment = (await import("./roundRobinManualReassignment")).default;
const eventManagerRescheduleSpy = await mockEventManagerReschedule();
@@ -302,6 +314,8 @@ describe("roundRobinManualReassignment test", () => {
newUserId: newHost.id,
orgId: null,
reassignedById: 1,
actionSource: "WEBAPP",
reassignedByUuid: originalHost.uuid,
});
expectEventManagerCalledWith(eventManagerRescheduleSpy, {
@@ -370,6 +384,8 @@ describe("roundRobinManualReassignment test", () => {
newUserId: newHost.id,
orgId: null,
reassignedById: 1,
actionSource: "WEBAPP",
reassignedByUuid: originalHost.uuid,
});
// Verify that EventManager.reschedule was called with an event containing conferenceCredentialId
@@ -446,6 +462,8 @@ describe("roundRobinManualReassignment test", () => {
newUserId: newHost.id,
orgId: null,
reassignedById: 1,
actionSource: "WEBAPP",
reassignedByUuid: fixedHost.uuid,
});
expectEventManagerCalledWith(eventManagerRescheduleSpy, {
@@ -526,6 +544,8 @@ describe("roundRobinManualReassignment test", () => {
newUserId: newHost.id,
orgId: null,
reassignedById: 1,
actionSource: "WEBAPP",
reassignedByUuid: originalHost.uuid,
});
expect(sendReassignedEmailsAndSMSSpy).toHaveBeenCalledTimes(1);
@@ -535,6 +555,14 @@ describe("roundRobinManualReassignment test", () => {
describe("roundRobinManualReassignment - Location Changes", () => {
setupAndTeardown();
beforeEach(() => {
// Set up default mock for BookingEventHandlerService
const mockOnReassignment = vi.fn().mockResolvedValue(undefined);
vi.mocked(getBookingEventHandlerService).mockReturnValue({
onReassignment: mockOnReassignment,
} as any);
});
const createConferencingUsers = () => {
return {
googleMeetHost: createTestUser({
@@ -655,6 +683,8 @@ describe("roundRobinManualReassignment - Location Changes", () => {
orgId: null,
reassignReason: "Host unavailable",
reassignedById: 999,
actionSource: "WEBAPP",
reassignedByUuid: "uuid-999",
});
expectEventManagerCalledWith(eventManagerRescheduleSpy, {
@@ -720,6 +750,8 @@ describe("roundRobinManualReassignment - Location Changes", () => {
orgId: null,
reassignReason: "Host unavailable",
reassignedById: 999,
actionSource: "WEBAPP",
reassignedByUuid: "uuid-999",
});
const calledEvent = eventManagerRescheduleSpy.mock.calls[0][0];
@@ -771,6 +803,8 @@ describe("roundRobinManualReassignment - Location Changes", () => {
orgId: null,
reassignReason: "Host unavailable",
reassignedById: 999,
actionSource: "WEBAPP",
reassignedByUuid: "uuid-999",
});
const calledEvent = eventManagerRescheduleSpy.mock.calls[0][0];
@@ -821,6 +855,8 @@ describe("roundRobinManualReassignment - Location Changes", () => {
orgId: null,
reassignReason: "Host unavailable",
reassignedById: 999,
actionSource: "WEBAPP",
reassignedByUuid: "uuid-999",
});
const calledEvent = eventManagerRescheduleSpy.mock.calls[0][0];
@@ -876,6 +912,8 @@ describe("roundRobinManualReassignment - Location Changes", () => {
orgId: null,
reassignReason: "Host unavailable",
reassignedById: 999,
actionSource: "WEBAPP",
reassignedByUuid: "uuid-999",
})
).rejects.toThrow("Failed to set video conferencing link, but the meeting has been rescheduled");
});
@@ -884,6 +922,14 @@ describe("roundRobinManualReassignment - Location Changes", () => {
describe("roundRobinManualReassignment - Seated Events", () => {
setupAndTeardown();
beforeEach(() => {
// Set up default mock for BookingEventHandlerService
const mockOnReassignment = vi.fn().mockResolvedValue(undefined);
vi.mocked(getBookingEventHandlerService).mockReturnValue({
onReassignment: mockOnReassignment,
} as any);
});
test("should not expose other attendees in updated email when seatsShowAttendees is disabled for seated round-robin event", async ({
emails,
}) => {
@@ -975,6 +1021,8 @@ describe("roundRobinManualReassignment - Seated Events", () => {
newUserId: newHost.id,
orgId: null,
reassignedById: 1,
actionSource: "WEBAPP",
reassignedByUuid: originalHost.uuid,
});
// Verify that updated emails were sent to all attendees
@@ -1032,3 +1080,161 @@ describe("roundRobinManualReassignment - Seated Events", () => {
}
});
});
describe("roundRobinManualReassignment - Audit Data Verification", () => {
setupAndTeardown();
test("should call BookingEventHandlerService.onReassignment with correct audit data when organizer changes", async () => {
const roundRobinManualReassignment = (await import("./roundRobinManualReassignment")).default;
await mockEventManagerReschedule();
const mockOnReassignment = vi.fn().mockResolvedValue(undefined);
vi.mocked(getBookingEventHandlerService).mockReturnValue({
onReassignment: mockOnReassignment,
} as any);
const testDestinationCalendar = createTestDestinationCalendar();
const originalHost = createTestUser({
id: 1,
uuid: "uuid-1",
destinationCalendar: testDestinationCalendar,
});
const newHost = createTestUser({ id: 2, uuid: "uuid-2" });
const reassigningUser = createTestUser({ id: 3, uuid: "uuid-3" });
const users = [originalHost, newHost, reassigningUser];
const bookingToReassignUid = "booking-audit-test";
await createBookingScenario(
getScenarioData({
eventTypes: [
createRoundRobinEventType({
id: 1,
slug: "round-robin-event",
users,
}),
],
bookings: [
await createTestBooking({
eventTypeId: 1,
userId: originalHost.id,
bookingId: 123,
bookingUid: bookingToReassignUid,
}),
],
organizer: originalHost,
usersApartFromOrganizer: users.slice(1),
})
);
await roundRobinManualReassignment({
bookingId: 123,
newUserId: newHost.id,
orgId: null,
reassignedById: reassigningUser.id,
actionSource: "WEBAPP",
reassignedByUuid: reassigningUser.uuid,
reassignReason: "Test reassignment reason",
});
expect(mockOnReassignment).toHaveBeenCalledTimes(1);
expect(mockOnReassignment).toHaveBeenCalledWith({
bookingUid: bookingToReassignUid,
actor: { identifiedBy: "user", userUuid: reassigningUser.uuid },
organizationId: null,
source: "WEBAPP",
auditData: {
organizerUuid: { old: originalHost.uuid, new: newHost.uuid },
reassignmentReason: "Test reassignment reason",
reassignmentType: "manual",
},
});
});
test("should call BookingEventHandlerService.onReassignment with correct audit data when only attendee changes (fixed host scenario)", async () => {
const roundRobinManualReassignment = (await import("./roundRobinManualReassignment")).default;
await mockEventManagerReschedule();
const mockOnReassignment = vi.fn().mockResolvedValue(undefined);
vi.mocked(getBookingEventHandlerService).mockReturnValue({
onReassignment: mockOnReassignment,
} as any);
const testDestinationCalendar = createTestDestinationCalendar();
const fixedHost = createTestUser({ id: 1, uuid: "uuid-1", destinationCalendar: testDestinationCalendar });
const currentRRHost = createTestUser({ id: 2, uuid: "uuid-2" });
const newHost = createTestUser({ id: 3, uuid: "uuid-3" });
const reassigningUser = createTestUser({ id: 4, uuid: "uuid-4" });
const users = [fixedHost, currentRRHost, newHost, reassigningUser];
const bookingToReassignUid = "booking-audit-fixed-host-test";
await createBookingScenario(
getScenarioData({
eventTypes: [
createRoundRobinEventType({
id: 1,
slug: "round-robin-event",
users: [fixedHost, currentRRHost, newHost],
hosts: users.slice(0, 3).map((user) => ({
userId: user.id,
isFixed: user.id === fixedHost.id,
})),
}),
],
bookings: [
await createTestBooking({
eventTypeId: 1,
userId: fixedHost.id,
bookingId: 123,
bookingUid: bookingToReassignUid,
attendees: [
getMockBookingAttendee({
id: 1,
name: "attendee",
email: "[email protected]",
locale: "en",
timeZone: "Asia/Kolkata",
}),
getMockBookingAttendee({
id: currentRRHost.id,
name: currentRRHost.name,
email: currentRRHost.email,
locale: "en",
timeZone: currentRRHost.timeZone,
}),
],
}),
],
organizer: fixedHost,
usersApartFromOrganizer: users.slice(1, 3),
})
);
await roundRobinManualReassignment({
bookingId: 123,
newUserId: newHost.id,
orgId: null,
reassignedById: reassigningUser.id,
actionSource: "WEBAPP",
reassignedByUuid: reassigningUser.uuid,
reassignReason: "Test reason",
});
expect(mockOnReassignment).toHaveBeenCalledTimes(1);
const callArgs = mockOnReassignment.mock.calls[0][0];
expect(callArgs.bookingUid).toBe(bookingToReassignUid);
expect(callArgs.actor).toEqual({ identifiedBy: "user", userUuid: reassigningUser.uuid });
expect(callArgs.organizationId).toBe(null);
expect(callArgs.source).toBe("WEBAPP");
// organizerUuid should NOT be included when organizer hasn't changed (fixed host scenario)
expect(callArgs.auditData.organizerUuid).toBeUndefined();
expect(callArgs.auditData.reassignmentType).toBe("manual");
expect(callArgs.auditData.reassignmentReason).toBe("Test reason");
expect(callArgs.auditData.hostAttendeeUpdated).toBeDefined();
expect(callArgs.auditData.hostAttendeeUpdated?.withUserUuid).toEqual({
old: currentRRHost.uuid,
new: newHost.uuid,
});
});
});
@@ -1,5 +1,3 @@
import { cloneDeep } from "lodash";
import { enrichUserWithDelegationCredentialsIncludeServiceAccountKey } from "@calcom/app-store/delegationCredential";
import { eventTypeAppMetadataOptionalSchema } from "@calcom/app-store/zod-utils";
import dayjs from "@calcom/dayjs";
@@ -8,6 +6,9 @@ import {
sendReassignedScheduledEmailsAndSMS,
sendReassignedUpdatedEmailsAndSMS,
} from "@calcom/emails/email-manager";
import { makeUserActor } from "@calcom/features/booking-audit/lib/makeActor";
import type { ValidActionSource } from "@calcom/features/booking-audit/lib/types/actionSource";
import { getBookingEventHandlerService } from "@calcom/features/bookings/di/BookingEventHandlerService.container";
import EventManager from "@calcom/features/bookings/lib/EventManager";
import { getAllCredentialsIncludeServiceAccountKey } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
import { getBookingResponsesPartialSchema } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
@@ -20,8 +21,8 @@ import AssignmentReasonRecorder, {
} from "@calcom/features/ee/round-robin/assignmentReason/AssignmentReasonRecorder";
import { BookingLocationService } from "@calcom/features/ee/round-robin/lib/bookingLocationService";
import {
scheduleEmailReminder,
deleteScheduledEmailReminder,
scheduleEmailReminder,
} from "@calcom/features/ee/workflows/lib/reminders/emailReminderManager";
import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/reminders/reminderScheduler";
import { getEventName } from "@calcom/features/eventtypes/lib/eventNaming";
@@ -36,7 +37,7 @@ import { prisma } from "@calcom/prisma";
import { WorkflowActions, WorkflowMethods, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import type { EventTypeMetadata, PlatformClientParams } from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
import { cloneDeep } from "lodash";
import { handleRescheduleEventManager } from "./handleRescheduleEventManager";
import type { BookingSelectResult } from "./utils/bookingSelect";
import { bookingSelect } from "./utils/bookingSelect";
@@ -56,6 +57,8 @@ export const roundRobinManualReassignment = async ({
reassignedById,
emailsEnabled = true,
platformClientParams,
actionSource,
reassignedByUuid,
}: {
bookingId: number;
newUserId: number;
@@ -64,6 +67,8 @@ export const roundRobinManualReassignment = async ({
reassignedById: number;
emailsEnabled?: boolean;
platformClientParams?: PlatformClientParams;
actionSource: ValidActionSource;
reassignedByUuid: string;
}) => {
const roundRobinReassignLogger = logger.getSubLogger({
prefix: ["roundRobinManualReassign", `${bookingId}`],
@@ -113,9 +118,20 @@ export const roundRobinManualReassignment = async ({
}));
const fixedHost = eventTypeHosts.find((host) => host.isFixed);
const currentRRHost = booking.attendees.find((attendee) =>
eventTypeHosts.some((host) => !host.isFixed && host.user.email === attendee.email)
);
let currentRRHostUserUuid = null;
let attendeeUpdatedId = null;
const currentRRHostAttendee = booking.attendees.find((attendee) => {
const matchingEventTypeHost = eventTypeHosts.find(
(host) => !host.isFixed && host.user.email === attendee.email
);
if (matchingEventTypeHost) {
currentRRHostUserUuid = matchingEventTypeHost.user.uuid;
return true;
}
return false;
});
const newUserHost = eventTypeHosts.find((host) => host.user.id === newUserId);
if (!newUserHost) {
@@ -152,7 +168,7 @@ export const roundRobinManualReassignment = async ({
let bookingLocation = booking.location;
let conferenceCredentialId: number | null = null;
const organizer = hasOrganizerChanged ? newUser : booking.user ?? newUser;
const organizer = hasOrganizerChanged ? newUser : (booking.user ?? newUser);
const teamMembers = await getTeamMembers({
eventTypeHosts,
@@ -224,10 +240,10 @@ export const roundRobinManualReassignment = async ({
reassignById: reassignedById,
reassignmentType: RRReassignmentType.MANUAL,
});
} else if (currentRRHost) {
} else if (currentRRHostAttendee) {
// Update the round-robin host attendee
await prisma.attendee.update({
where: { id: currentRRHost.id },
where: { id: currentRRHostAttendee.id },
data: {
name: newUser.name || "",
email: newUser.email,
@@ -235,8 +251,36 @@ export const roundRobinManualReassignment = async ({
locale: newUser.locale,
},
});
attendeeUpdatedId = currentRRHostAttendee.id;
}
const bookingEventHandlerService = getBookingEventHandlerService();
await bookingEventHandlerService.onReassignment({
bookingUid: booking.uid,
actor: makeUserActor(reassignedByUuid),
organizationId: orgId,
source: actionSource,
auditData: {
...(hasOrganizerChanged
? { organizerUuid: { old: originalOrganizer.uuid, new: newUser.uuid } }
: null),
...(attendeeUpdatedId
? {
hostAttendeeUpdated: {
id: attendeeUpdatedId,
withUserUuid: {
old: currentRRHostUserUuid,
new: newUser.uuid,
},
},
}
: null),
reassignmentReason: reassignReason ?? null,
reassignmentType: "manual",
},
});
// When organizer hasn't changed, still extract conferenceCredentialId from event type locations
if (!hasOrganizerChanged && bookingLocation) {
const { conferenceCredentialId: extractedCredentialId } =
@@ -257,7 +301,6 @@ export const roundRobinManualReassignment = async ({
});
const organizerT = await getTranslation(organizer?.locale || "en", "common");
const attendeePromises = [];
for (const attendee of booking.attendees) {
if (
@@ -1,29 +1,31 @@
import prismaMock from "@calcom/testing/lib/__mocks__/prisma";
import {
getDate,
createBookingScenario,
getScenarioData,
getMockBookingAttendee,
TestData,
addWorkflowReminders,
createBookingScenario,
getDate,
getMockBookingAttendee,
getScenarioData,
TestData,
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { getBookingEventHandlerService } from "@calcom/features/bookings/di/BookingEventHandlerService.container";
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { BookingStatus, SchedulingType, WorkflowMethods } from "@calcom/prisma/enums";
import {
expectBookingToBeInDatabase,
expectSuccessfulRoundRobinReschedulingEmails,
expectWorkflowToBeTriggered,
} from "@calcom/testing/lib/bookingScenario/expects";
import { setupAndTeardown } from "@calcom/testing/lib/bookingScenario/setupAndTeardown";
import { describe, vi, expect } from "vitest";
import { v4 as uuidv4 } from "uuid";
import { parse } from "node-html-parser";
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { SchedulingType, BookingStatus, WorkflowMethods } from "@calcom/prisma/enums";
import { test } from "@calcom/testing/lib/fixtures/fixtures";
import { parse } from "node-html-parser";
import { v4 as uuidv4 } from "uuid";
import { beforeEach, describe, expect, vi } from "vitest";
import type { BookingEventHandlerService } from "../../bookings/lib/onBookingEvents/BookingEventHandlerService";
vi.mock("@calcom/features/bookings/lib/EventManager");
vi.mock("@calcom/features/bookings/di/BookingEventHandlerService.container", () => ({
getBookingEventHandlerService: vi.fn(),
}));
const testDestinationCalendar = {
integration: "test-calendar",
@@ -39,6 +41,7 @@ const testUsers = [
email: "[email protected]",
schedules: [TestData.schedules.IstWorkHours],
destinationCalendar: testDestinationCalendar,
uuid: "uuid-1",
},
{
id: 2,
@@ -47,6 +50,7 @@ const testUsers = [
username: "host-2",
email: "[email protected]",
schedules: [TestData.schedules.IstWorkHours],
uuid: "uuid-2",
},
{
id: 3,
@@ -55,12 +59,21 @@ const testUsers = [
username: "host-3",
email: "[email protected]",
schedules: [TestData.schedules.IstWorkHours],
uuid: "uuid-3",
},
];
describe("roundRobinReassignment test", () => {
setupAndTeardown();
beforeEach(() => {
// Set up default mock for BookingEventHandlerService
const mockOnReassignment = vi.fn().mockResolvedValue(undefined);
vi.mocked(getBookingEventHandlerService).mockReturnValue({
onReassignment: mockOnReassignment,
} as unknown as BookingEventHandlerService);
});
test("reassign new round robin organizer", async ({ emails }) => {
const roundRobinReassignment = (await import("./roundRobinReassignment")).default;
const EventManager = (await import("@calcom/features/bookings/lib/EventManager")).default;
@@ -168,6 +181,8 @@ describe("roundRobinReassignment test", () => {
bookingId: 123,
orgId: null,
reassignedById: originalHost.id,
actionSource: "WEBAPP",
reassignedByUuid: originalHost.uuid,
});
expect(eventManagerSpy).toBeCalledTimes(1);
@@ -425,6 +440,8 @@ describe("roundRobinReassignment test", () => {
bookingId: 123,
orgId: null,
reassignedById: originalHost.id,
actionSource: "WEBAPP",
reassignedByUuid: originalHost.uuid,
});
expect(eventManagerSpy).toBeCalledTimes(1);
@@ -484,3 +501,203 @@ describe("roundRobinReassignment test", () => {
}
});
});
describe("roundRobinReassignment - Audit Data Verification", () => {
setupAndTeardown();
test("should call BookingEventHandlerService.onReassignment with correct audit data when organizer changes", async () => {
const roundRobinReassignment = (await import("./roundRobinReassignment")).default;
const EventManager = (await import("@calcom/features/bookings/lib/EventManager")).default;
const eventManagerSpy = vi.spyOn(EventManager.prototype as any, "reschedule");
eventManagerSpy.mockClear();
eventManagerSpy.mockResolvedValue({ referencesToCreate: [] });
const mockOnReassignment = vi.fn().mockResolvedValue(undefined);
vi.mocked(getBookingEventHandlerService).mockReturnValue({
onReassignment: mockOnReassignment,
} as any);
const users = testUsers;
const originalHost = users[0];
const newHost = users[1];
const reassigningUser = users[0]; // originalHost is doing the reassignment
const { dateString: dateStringPlusOne } = getDate({ dateIncrement: 1 });
const { dateString: dateStringMinusOne } = getDate({ dateIncrement: -1 });
const { dateString: dateStringPlusTwo } = getDate({ dateIncrement: 2 });
const bookingToReassignUid = "booking-audit-test";
await createBookingScenario(
getScenarioData({
eventTypes: [
{
id: 1,
slug: "round-robin-event",
schedulingType: SchedulingType.ROUND_ROBIN,
length: 45,
users: users.map((user) => ({ id: user.id })),
hosts: users.map((user) => ({ userId: user.id, isFixed: false })),
},
],
bookings: [
{
id: 123,
eventTypeId: 1,
userId: originalHost.id,
uid: bookingToReassignUid,
status: BookingStatus.ACCEPTED,
startTime: `${dateStringPlusOne}T05:00:00.000Z`,
endTime: `${dateStringPlusOne}T05:15:00.000Z`,
attendees: [
getMockBookingAttendee({
id: 2,
name: "attendee",
email: "[email protected]",
locale: "en",
timeZone: "Asia/Kolkata",
}),
],
},
{
id: 456,
eventTypeId: 1,
userId: users[2].id,
uid: "other-booking",
status: BookingStatus.ACCEPTED,
startTime: `${dateStringMinusOne}T05:00:00.000Z`,
endTime: `${dateStringMinusOne}T05:15:00.000Z`,
attendees: [
getMockBookingAttendee({
id: 2,
name: "attendee",
email: "[email protected]",
locale: "en",
timeZone: "Asia/Kolkata",
}),
],
},
],
organizer: originalHost,
usersApartFromOrganizer: users.slice(1),
})
);
await roundRobinReassignment({
bookingId: 123,
orgId: null,
reassignedById: reassigningUser.id,
actionSource: "WEBAPP",
reassignedByUuid: reassigningUser.uuid,
});
expect(mockOnReassignment).toHaveBeenCalledTimes(1);
expect(mockOnReassignment).toHaveBeenCalledWith({
bookingUid: bookingToReassignUid,
actor: { identifiedBy: "user", userUuid: reassigningUser.uuid },
organizationId: null,
source: "WEBAPP",
auditData: {
organizerUuid: { old: originalHost.uuid, new: newHost.uuid },
reassignmentReason: null,
reassignmentType: "roundRobin",
},
});
});
test("should call BookingEventHandlerService.onReassignment with correct audit data when only attendee changes (fixed host scenario)", async () => {
const roundRobinReassignment = (await import("./roundRobinReassignment")).default;
const EventManager = (await import("@calcom/features/bookings/lib/EventManager")).default;
const eventManagerSpy = vi.spyOn(EventManager.prototype as any, "reschedule");
eventManagerSpy.mockClear();
eventManagerSpy.mockResolvedValue({ referencesToCreate: [] });
const mockOnReassignment = vi.fn().mockResolvedValue(undefined);
vi.mocked(getBookingEventHandlerService).mockReturnValue({
onReassignment: mockOnReassignment,
} as any);
const users = testUsers;
const fixedHost = users[0];
const currentRRHost = users[1];
const newHost = users[2];
const reassigningUser = fixedHost;
const { dateString: dateStringPlusOne } = getDate({ dateIncrement: 1 });
const bookingToReassignUid = "booking-audit-fixed-host-test";
await createBookingScenario(
getScenarioData({
eventTypes: [
{
id: 1,
slug: "round-robin-event",
schedulingType: SchedulingType.ROUND_ROBIN,
length: 45,
users: users.map((user) => ({ id: user.id })),
hosts: users.map((user) => ({
userId: user.id,
isFixed: user.id === fixedHost.id,
})),
},
],
bookings: [
{
id: 123,
eventTypeId: 1,
userId: fixedHost.id,
uid: bookingToReassignUid,
status: BookingStatus.ACCEPTED,
startTime: `${dateStringPlusOne}T05:00:00.000Z`,
endTime: `${dateStringPlusOne}T05:15:00.000Z`,
attendees: [
getMockBookingAttendee({
id: 1,
name: "attendee",
email: "[email protected]",
locale: "en",
timeZone: "Asia/Kolkata",
}),
getMockBookingAttendee({
id: currentRRHost.id,
name: currentRRHost.name,
email: currentRRHost.email,
locale: "en",
timeZone: currentRRHost.timeZone,
}),
],
},
],
organizer: fixedHost,
usersApartFromOrganizer: users.slice(1),
})
);
await roundRobinReassignment({
bookingId: 123,
orgId: null,
reassignedById: reassigningUser.id,
actionSource: "WEBAPP",
reassignedByUuid: reassigningUser.uuid,
});
expect(mockOnReassignment).toHaveBeenCalledTimes(1);
const callArgs = mockOnReassignment.mock.calls[0][0];
expect(callArgs.bookingUid).toBe(bookingToReassignUid);
expect(callArgs.actor).toEqual({ identifiedBy: "user", userUuid: reassigningUser.uuid });
expect(callArgs.organizationId).toBe(null);
expect(callArgs.source).toBe("WEBAPP");
// organizerUuid should NOT be included when organizer hasn't changed (fixed host scenario)
expect(callArgs.auditData.organizerUuid).toBeUndefined();
expect(callArgs.auditData.reassignmentType).toBe("roundRobin");
expect(callArgs.auditData.reassignmentReason).toBe(null);
expect(callArgs.auditData.hostAttendeeUpdated).toBeDefined();
expect(callArgs.auditData.hostAttendeeUpdated?.withUserUuid).toEqual({
old: currentRRHost.uuid,
new: newHost.uuid,
});
});
});
@@ -1,10 +1,8 @@
import { cloneDeep } from "lodash";
import {
enrichHostsWithDelegationCredentials,
enrichUserWithDelegationCredentialsIncludeServiceAccountKey,
} from "@calcom/app-store/delegationCredential";
import { OrganizerDefaultConferencingAppType, getLocationValueForDB } from "@calcom/app-store/locations";
import { getLocationValueForDB, OrganizerDefaultConferencingAppType } from "@calcom/app-store/locations";
import { eventTypeAppMetadataOptionalSchema } from "@calcom/app-store/zod-utils";
import dayjs from "@calcom/dayjs";
import {
@@ -12,6 +10,9 @@ import {
sendReassignedScheduledEmailsAndSMS,
sendReassignedUpdatedEmailsAndSMS,
} from "@calcom/emails/email-manager";
import { makeUserActor } from "@calcom/features/booking-audit/lib/makeActor";
import type { ValidActionSource } from "@calcom/features/booking-audit/lib/types/actionSource";
import { getBookingEventHandlerService } from "@calcom/features/bookings/di/BookingEventHandlerService.container";
import EventManager from "@calcom/features/bookings/lib/EventManager";
import { getAllCredentialsIncludeServiceAccountKey } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
import { getBookingResponsesPartialSchema } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
@@ -31,10 +32,10 @@ import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import { prisma } from "@calcom/prisma";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import type { EventTypeMetadata, PlatformClientParams } from "@calcom/prisma/zod-utils";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
import { cloneDeep } from "lodash";
import { handleRescheduleEventManager } from "./handleRescheduleEventManager";
import { handleWorkflowsUpdate } from "./roundRobinManualReassignment";
import { bookingSelect } from "./utils/bookingSelect";
@@ -47,12 +48,16 @@ export const roundRobinReassignment = async ({
emailsEnabled = true,
platformClientParams,
reassignedById,
actionSource,
reassignedByUuid,
}: {
bookingId: number;
orgId: number | null;
emailsEnabled?: boolean;
platformClientParams?: PlatformClientParams;
reassignedById: number;
actionSource: ValidActionSource;
reassignedByUuid: string;
}) => {
const roundRobinReassignLogger = logger.getSubLogger({
prefix: ["roundRobinReassign", `${bookingId}`],
@@ -203,6 +208,8 @@ export const roundRobinReassignment = async ({
const attendeeList = await Promise.all(attendeePromises);
let bookingLocation = booking.location;
let attendeeUpdatedId = null;
let previousRRHostUserUuid = null;
if (hasOrganizerChanged) {
const bookingResponses = booking.responses;
@@ -268,19 +275,49 @@ export const roundRobinReassignment = async ({
const previousRRHostAttendee = booking.attendees.find(
(attendee) => attendee.email === previousRRHost.email
);
await prisma.attendee.update({
where: {
id: previousRRHostAttendee!.id,
},
data: {
name: reassignedRRHost.name || "",
email: reassignedRRHost.email,
timeZone: reassignedRRHost.timeZone,
locale: reassignedRRHost.locale,
},
});
if (previousRRHostAttendee) {
previousRRHostUserUuid = previousRRHost?.uuid ?? null;
attendeeUpdatedId = previousRRHostAttendee.id;
await prisma.attendee.update({
where: {
id: previousRRHostAttendee.id,
},
data: {
name: reassignedRRHost.name || "",
email: reassignedRRHost.email,
timeZone: reassignedRRHost.timeZone,
locale: reassignedRRHost.locale,
},
});
}
}
const bookingEventHandlerService = getBookingEventHandlerService();
await bookingEventHandlerService.onReassignment({
bookingUid: booking.uid,
actor: makeUserActor(reassignedByUuid),
organizationId: orgId,
source: actionSource,
auditData: {
...(hasOrganizerChanged
? { organizerUuid: { old: originalOrganizer.uuid, new: reassignedRRHost.uuid } }
: null),
...(attendeeUpdatedId
? {
hostAttendeeUpdated: {
id: attendeeUpdatedId,
withUserUuid: {
old: previousRRHostUserUuid,
new: reassignedRRHost.uuid ?? null,
},
},
}
: null),
reassignmentReason: null,
reassignmentType: "roundRobin",
},
});
roundRobinReassignLogger.info(`Successfully reassigned to user ${reassignedRRHost.id}`);
await AssignmentReasonRecorder.roundRobinReassignment({
@@ -26,6 +26,7 @@ export const bookingSelect = {
credentials: {
select: credentialForCalendarServiceSelect,
},
uuid: true,
},
},
attendees: true,