From c9bb03b602e44909fb4b2324a8f93e662b9d9e85 Mon Sep 17 00:00:00 2001 From: Hariom Balhara Date: Mon, 12 Jan 2026 16:41:33 +0530 Subject: [PATCH] chore: Integrate add guests booking audit (#26568) * chore: Integrate add guests booking audit Co-Authored-By: hariom@cal.com * chore: Add actionSource parameter to support API_V2 audit logging Co-Authored-By: hariom@cal.com * refactor: update attendee audit action service to use new email schema - Modified the `AttendeeAddedAuditActionService` to replace the old attendees schema with a new `emailSchema` for better validation. - Adjusted the `addGuestsHandler` to pass the action source explicitly and updated the audit logging to reflect the new structure. - Cleaned up the code for better readability and consistency. * test: add happy path integration test for attendee added action Co-Authored-By: hariom@cal.com --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../services/booking-guests.service.ts | 1 + .../AttendeeAddedAuditActionService.ts | 111 ++++++++-------- .../attendee-added-action.integration-test.ts | 122 ++++++++++++++++++ .../routers/viewer/bookings/_router.tsx | 1 + .../viewer/bookings/addGuests.handler.ts | 31 ++++- 5 files changed, 206 insertions(+), 60 deletions(-) create mode 100644 packages/features/booking-audit/lib/service/__tests__/attendee-added-action.integration-test.ts diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/services/booking-guests.service.ts b/apps/api/v2/src/ee/bookings/2024-08-13/services/booking-guests.service.ts index a89773441b..7fca9186c7 100644 --- a/apps/api/v2/src/ee/bookings/2024-08-13/services/booking-guests.service.ts +++ b/apps/api/v2/src/ee/bookings/2024-08-13/services/booking-guests.service.ts @@ -33,6 +33,7 @@ export class BookingGuestsService_2024_08_13 { ctx: { user }, input: { bookingId: booking.id, guests: input.guests }, emailsEnabled, + actionSource: "API_V2", }); if (res.message === "Guests added") { return await this.bookingsService.getBooking(bookingUid, user); diff --git a/packages/features/booking-audit/lib/actions/AttendeeAddedAuditActionService.ts b/packages/features/booking-audit/lib/actions/AttendeeAddedAuditActionService.ts index 7df6c3cebc..9802a3e278 100644 --- a/packages/features/booking-audit/lib/actions/AttendeeAddedAuditActionService.ts +++ b/packages/features/booking-audit/lib/actions/AttendeeAddedAuditActionService.ts @@ -1,8 +1,13 @@ import { z } from "zod"; +import { emailSchema } from "@calcom/lib/emailSchema"; -import { StringArrayChangeSchema } from "../common/changeSchemas"; import { AuditActionServiceHelper } from "./AuditActionServiceHelper"; -import type { IAuditActionService, TranslationWithParams, GetDisplayTitleParams, GetDisplayJsonParams } from "./IAuditActionService"; +import type { + IAuditActionService, + TranslationWithParams, + GetDisplayTitleParams, + GetDisplayJsonParams, +} from "./IAuditActionService"; /** * Attendee Added Audit Action Service @@ -11,73 +16,67 @@ import type { IAuditActionService, TranslationWithParams, GetDisplayTitleParams, // Module-level because it is passed to IAuditActionService type outside the class scope const fieldsSchemaV1 = z.object({ - attendees: StringArrayChangeSchema, + added: z.array(emailSchema), }); export class AttendeeAddedAuditActionService implements IAuditActionService { - readonly VERSION = 1; - public static readonly TYPE = "ATTENDEE_ADDED" as const; - private static dataSchemaV1 = z.object({ - version: z.literal(1), - fields: fieldsSchemaV1, + readonly VERSION = 1; + public static readonly TYPE = "ATTENDEE_ADDED" as const; + private static dataSchemaV1 = z.object({ + version: z.literal(1), + fields: fieldsSchemaV1, + }); + private static fieldsSchemaV1 = fieldsSchemaV1; + public static readonly latestFieldsSchema = fieldsSchemaV1; + // Union of all versions + public static readonly storedDataSchema = AttendeeAddedAuditActionService.dataSchemaV1; + // Union of all versions + public static readonly storedFieldsSchema = AttendeeAddedAuditActionService.fieldsSchemaV1; + private helper: AuditActionServiceHelper< + typeof AttendeeAddedAuditActionService.latestFieldsSchema, + typeof AttendeeAddedAuditActionService.storedDataSchema + >; + + constructor() { + this.helper = new AuditActionServiceHelper({ + latestVersion: this.VERSION, + latestFieldsSchema: AttendeeAddedAuditActionService.latestFieldsSchema, + storedDataSchema: AttendeeAddedAuditActionService.storedDataSchema, }); - private static fieldsSchemaV1 = fieldsSchemaV1; - public static readonly latestFieldsSchema = fieldsSchemaV1; - // Union of all versions - public static readonly storedDataSchema = AttendeeAddedAuditActionService.dataSchemaV1; - // Union of all versions - public static readonly storedFieldsSchema = AttendeeAddedAuditActionService.fieldsSchemaV1; - private helper: AuditActionServiceHelper< - typeof AttendeeAddedAuditActionService.latestFieldsSchema, - typeof AttendeeAddedAuditActionService.storedDataSchema - >; + } - constructor() { - this.helper = new AuditActionServiceHelper({ - latestVersion: this.VERSION, - latestFieldsSchema: AttendeeAddedAuditActionService.latestFieldsSchema, - storedDataSchema: AttendeeAddedAuditActionService.storedDataSchema, - }); - } + getVersionedData(fields: unknown) { + return this.helper.getVersionedData(fields); + } - getVersionedData(fields: unknown) { - return this.helper.getVersionedData(fields); - } + parseStored(data: unknown) { + return this.helper.parseStored(data); + } - parseStored(data: unknown) { - return this.helper.parseStored(data); - } + getVersion(data: unknown): number { + return this.helper.getVersion(data); + } - getVersion(data: unknown): number { - return this.helper.getVersion(data); - } + migrateToLatest(data: unknown) { + // V1-only: validate and return as-is (no migration needed) + const validated = fieldsSchemaV1.parse(data); + return { isMigrated: false, latestData: validated }; + } - migrateToLatest(data: unknown) { - // V1-only: validate and return as-is (no migration needed) - const validated = fieldsSchemaV1.parse(data); - return { isMigrated: false, latestData: validated }; - } + async getDisplayTitle(_: GetDisplayTitleParams): Promise { + return { key: "booking_audit_action.attendee_added" }; + } - async getDisplayTitle(_: GetDisplayTitleParams): Promise { - return { key: "booking_audit_action.attendee_added" }; - } - - getDisplayJson({ - storedData, - }: GetDisplayJsonParams): AttendeeAddedAuditDisplayData { - const { fields } = this.parseStored({ version: storedData.version, fields: storedData.fields }); - const previousAttendeesSet = new Set(fields.attendees.old ?? []); - const addedAttendees = fields.attendees.new.filter( - (email) => !previousAttendeesSet.has(email) - ); - return { - addedAttendees, - }; - } + getDisplayJson({ storedData }: GetDisplayJsonParams): AttendeeAddedAuditDisplayData { + const { fields } = this.parseStored({ version: storedData.version, fields: storedData.fields }); + return { + addedAttendees: fields.added, + }; + } } export type AttendeeAddedAuditData = z.infer; export type AttendeeAddedAuditDisplayData = { - addedAttendees: string[]; + addedAttendees: string[]; }; diff --git a/packages/features/booking-audit/lib/service/__tests__/attendee-added-action.integration-test.ts b/packages/features/booking-audit/lib/service/__tests__/attendee-added-action.integration-test.ts new file mode 100644 index 0000000000..144d3564a3 --- /dev/null +++ b/packages/features/booking-audit/lib/service/__tests__/attendee-added-action.integration-test.ts @@ -0,0 +1,122 @@ +import { describe, expect, it, beforeEach, afterEach } from "vitest"; + +import type { BookingStatus } from "@calcom/prisma/enums"; +import type { BookingAuditTaskConsumer } from "../BookingAuditTaskConsumer"; +import type { BookingAuditViewerService } from "../BookingAuditViewerService"; +import { makeUserActor } from "../../makeActor"; +import { getBookingAuditTaskConsumer } from "../../../di/BookingAuditTaskConsumer.container"; +import { getBookingAuditViewerService } from "../../../di/BookingAuditViewerService.container"; +import { + createTestUser, + createTestOrganization, + createTestMembership, + createTestEventType, + createTestBooking, + enableFeatureForOrganization, + cleanupTestData, +} from "./integration-utils"; + +describe("Attendee Added Action Integration", () => { + let bookingAuditTaskConsumer: BookingAuditTaskConsumer; + let bookingAuditViewerService: BookingAuditViewerService; + + let testData: { + owner: { id: number; uuid: string; email: string }; + attendee: { id: number; email: string }; + organization: { id: number }; + eventType: { id: number }; + booking: { uid: string; startTime: Date; endTime: Date; status: BookingStatus }; + }; + + beforeEach(async () => { + bookingAuditTaskConsumer = getBookingAuditTaskConsumer(); + bookingAuditViewerService = getBookingAuditViewerService(); + + const owner = await createTestUser({ name: "Test Audit User" }); + const organization = await createTestOrganization(); + await createTestMembership(owner.id, organization.id); + await enableFeatureForOrganization(organization.id, "booking-audit"); + const eventType = await createTestEventType(owner.id); + const attendee = await createTestUser({ name: "Test Attendee" }); + + const booking = await createTestBooking(owner.id, eventType.id, { + attendees: [ + { + email: attendee.email, + name: attendee.name || "Test Attendee", + timeZone: "UTC", + }, + ], + }); + + testData = { + owner: { id: owner.id, uuid: owner.uuid, email: owner.email }, + attendee: { id: attendee.id, email: attendee.email }, + organization: { id: organization.id }, + eventType: { id: eventType.id }, + booking: { + uid: booking.uid, + startTime: booking.startTime, + endTime: booking.endTime, + status: booking.status, + }, + }; + }); + + afterEach(async () => { + if (!testData) return; + + await cleanupTestData({ + bookingUid: testData.booking?.uid, + userUuids: testData.owner?.uuid ? [testData.owner.uuid] : [], + attendeeEmails: testData.attendee?.email ? [testData.attendee.email] : [], + eventTypeId: testData.eventType?.id, + organizationId: testData.organization?.id, + userIds: [testData.owner?.id, testData.attendee?.id].filter((id): id is number => id !== undefined), + featureSlug: "booking-audit", + }); + }); + + describe("when guests are added to a booking", () => { + it("should create audit record with correct added attendees data", async () => { + const actor = makeUserActor(testData.owner.uuid); + const newGuestEmails = ["guest1@example.com", "guest2@example.com"]; + + await bookingAuditTaskConsumer.onBookingAction({ + bookingUid: testData.booking.uid, + actor, + action: "ATTENDEE_ADDED", + source: "WEBAPP", + operationId: `op-${Date.now()}`, + data: { + added: newGuestEmails, + }, + timestamp: Date.now(), + }); + + const result = await bookingAuditViewerService.getAuditLogsForBooking({ + bookingUid: testData.booking.uid, + userId: testData.owner.id, + userEmail: testData.owner.email, + userTimeZone: "UTC", + organizationId: testData.organization.id, + }); + + expect(result.bookingUid).toBe(testData.booking.uid); + expect(result.auditLogs).toHaveLength(1); + + const auditLog = result.auditLogs[0]; + expect(auditLog.bookingUid).toBe(testData.booking.uid); + expect(auditLog.action).toBe("ATTENDEE_ADDED"); + expect(auditLog.type).toBe("RECORD_UPDATED"); + + const displayData = auditLog.displayJson as { addedAttendees: string[] }; + expect(displayData).toBeDefined(); + expect(displayData.addedAttendees).toEqual(newGuestEmails); + + expect(auditLog.actor.displayName).toBe("Test Audit User"); + expect(auditLog.actor.displayEmail).toBe(testData.owner.email); + expect(auditLog.actor.userUuid).toBe(testData.owner.uuid); + }); + }); +}); diff --git a/packages/trpc/server/routers/viewer/bookings/_router.tsx b/packages/trpc/server/routers/viewer/bookings/_router.tsx index 6d7f5fee85..8ef8c4efa2 100644 --- a/packages/trpc/server/routers/viewer/bookings/_router.tsx +++ b/packages/trpc/server/routers/viewer/bookings/_router.tsx @@ -51,6 +51,7 @@ export const bookingsRouter = router({ return addGuestsHandler({ ctx, input, + actionSource: "WEBAPP", }); }), diff --git a/packages/trpc/server/routers/viewer/bookings/addGuests.handler.ts b/packages/trpc/server/routers/viewer/bookings/addGuests.handler.ts index 447a253d74..6b8b560ddc 100644 --- a/packages/trpc/server/routers/viewer/bookings/addGuests.handler.ts +++ b/packages/trpc/server/routers/viewer/bookings/addGuests.handler.ts @@ -1,6 +1,9 @@ import { getUsersCredentialsIncludeServiceAccountKey } from "@calcom/app-store/delegationCredential"; import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils"; import dayjs from "@calcom/dayjs"; +import { makeUserActor } from "@calcom/features/booking-audit/lib/makeActor"; +import type { ActionSource } from "@calcom/features/booking-audit/lib/types/actionSource"; +import { getBookingEventHandlerService } from "@calcom/features/bookings/di/BookingEventHandlerService.container"; import { BookingEmailSmsHandler } from "@calcom/features/bookings/lib/BookingEmailSmsHandler"; import EventManager from "@calcom/features/bookings/lib/EventManager"; import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository"; @@ -21,7 +24,7 @@ import { TRPCError } from "@trpc/server"; import type { TrpcSessionUser } from "../../../types"; import type { TAddGuestsInputSchema } from "./addGuests.schema"; -type TUser = Pick, "id" | "email" | "organizationId"> & +type TUser = Pick, "id" | "email" | "organizationId" | "uuid"> & Partial, "profile">>; type AddGuestsOptions = { @@ -30,12 +33,18 @@ type AddGuestsOptions = { }; input: TAddGuestsInputSchema; emailsEnabled?: boolean; + actionSource: ActionSource; }; type Booking = NonNullable>>; type OrganizerData = Awaited>; -export const addGuestsHandler = async ({ ctx, input, emailsEnabled = true }: AddGuestsOptions) => { +export const addGuestsHandler = async ({ + ctx, + input, + emailsEnabled = true, + actionSource, +}: AddGuestsOptions) => { const { user } = ctx; const { bookingId, guests } = input; @@ -65,6 +74,9 @@ export const addGuestsHandler = async ({ ctx, input, emailsEnabled = true }: Add booking ); + // Capture new attendee emails after update for audit logging + const newAttendeeEmails = bookingAttendees.attendees.map((attendee) => attendee.email); + const attendeesList = await prepareAttendeesList(bookingAttendees.attendees); const evt = await buildCalendarEvent(booking, organizer, attendeesList); @@ -75,6 +87,17 @@ export const addGuestsHandler = async ({ ctx, input, emailsEnabled = true }: Add await sendGuestNotifications(evt, booking, uniqueGuestEmails); } + const bookingEventHandlerService = getBookingEventHandlerService(); + await bookingEventHandlerService.onAttendeeAdded({ + bookingUid: booking.uid, + actor: makeUserActor(user.uuid), + organizationId: user.organizationId ?? null, + source: actionSource, + auditData: { + added: uniqueGuestEmails, + }, + }); + return { message: "Guests added" }; }; @@ -286,8 +309,8 @@ async function buildCalendarEvent( destinationCalendar: booking?.destinationCalendar ? [booking?.destinationCalendar] : booking?.user?.destinationCalendar - ? [booking?.user?.destinationCalendar] - : [], + ? [booking?.user?.destinationCalendar] + : [], seatsPerTimeSlot: booking.eventType?.seatsPerTimeSlot, seatsShowAttendees: booking.eventType?.seatsShowAttendees, customReplyToEmail: booking.eventType?.customReplyToEmail,