Scheduling infrastructure for absolutely everyone.
chore: Integrate add guests booking audit (#26568)
Hariom Balharac9bb03b602e4
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.tsindex a89773441bc..7fca9186c7e 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.tsindex 7df6c3cebc7..9802a3e2788 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 scopeconst 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,- });- 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- >;+ 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,- });- }+ 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<TranslationWithParams> {- return { key: "booking_audit_action.attendee_added" };- }+ async getDisplayTitle(_: GetDisplayTitleParams): Promise<TranslationWithParams> {+ 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<typeof fieldsSchemaV1>;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.tsnew file mode 100644index 00000000000..144d3564a3e--- /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 = ["[email protected]", "[email protected]"];++ 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.tsxindex 6d7f5fee855..8ef8c4efa2b 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.tsindex 447a253d74f..6b8b560ddc4 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<NonNullable<TrpcSessionUser>, "id" | "email" | "organizationId"> &+type TUser = Pick<NonNullable<TrpcSessionUser>, "id" | "email" | "organizationId" | "uuid"> &Partial<Pick<NonNullable<TrpcSessionUser>, "profile">>;type AddGuestsOptions = {@@ -30,12 +33,18 @@ type AddGuestsOptions = {};input: TAddGuestsInputSchema;emailsEnabled?: boolean;+ actionSource: ActionSource;};type Booking = NonNullable<Awaited<ReturnType<BookingRepository["findByIdIncludeDestinationCalendar"]>>>;type OrganizerData = Awaited<ReturnType<typeof getOrganizerData>>;-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 }: Addbooking);+ // 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 }: Addawait 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,