Files
e04a394e1c fix: (booking-audit) Remove IS_PRODUCTION gate and add feature flag check in producer (#26524)
* fix: remove IS_PRODUCTION gate from BookingAuditProducer

Remove the IS_PRODUCTION check that was preventing booking audits from
being queued in production. Audits are still properly gated by:

1. Organization check: Audits are skipped for non-organization bookings
   (organizationId === null)
2. Feature flag: The BookingAuditTaskConsumer checks if the 'booking-audit'
   feature is enabled for the organization via featuresRepository.checkIfTeamHasFeature()

The IS_PRODUCTION gate was intentionally added to prevent logs from being
created in production while the action data versioning was being actively
reviewed and finalized. Without proper versioning handling, the Booking
History UI could crash when encountering unversioned data. Now that the
versioning system is in place, this gate can be safely removed.

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: revert formatting, keep only IS_PRODUCTION removal

Reverts the unintended formatting changes from the previous commit.
Only removes the IS_PRODUCTION gate without changing indentation.

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: add booking-audit feature flag check in producer to avoid unnecessary task creation

- Query booking-audit and booking-email-sms-tasker flags in parallel before fireBookingEvents
- Pass isBookingAuditEnabled through BookingEventHandler to producer's queueTask method
- Add conditional check in queueTask with debug log when skipping audit
- Reuse pre-queried isBookingEmailSmsTaskerEnabled flag instead of querying again

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: make isBookingAuditEnabled required and pass it through all booking audit flows

- Make isBookingAuditEnabled a required property in BookingAuditProducerService interface
- Update all BookingEventHandler methods to require isBookingAuditEnabled
- Add feature flag check in all flows that call booking audit:
  - handleSeats (seat booking/rescheduling)
  - RecurringBookingService (bulk bookings)
  - handleCancelBooking (booking cancellation)
  - handleConfirmation (booking acceptance)
  - roundRobinReassignment (automatic reassignment)
  - roundRobinManualReassignment (manual reassignment)
  - trpc handlers: addGuests, confirm, editLocation, requestReschedule
- Skip queueing audit tasks when feature is disabled with debug logging

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: add featuresRepository dependency to RecurringBookingService DI module

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: make isBookingAuditEnabled optional for non-main flows

Keep feature flag check only in main flows (handleSeats, RegularBookingService, RecurringBookingService) which are frequently triggered. For other flows (handleCancelBooking, handleConfirmation, roundRobinReassignment, etc.), rely on the existing consumer-level check.

Changes:
- Revert feature flag check from non-main flows
- Make isBookingAuditEnabled optional in interface for non-main flow methods
- Keep isBookingAuditEnabled required for main flow methods (queueCreatedAudit, queueRescheduledAudit, queueSeatBookedAudit, queueSeatRescheduledAudit, queueBulkCreatedAudit, queueBulkRescheduledAudit)
- Update BookingEventHandlerService to use required params for main flows and optional for non-main flows

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: remove isBookingAuditEnabled from non-main flow methods

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: make isBookingAuditEnabled required in all BookingEventHandlerService methods

- Add isBookingAuditEnabled as required parameter in all BookingAuditProducerService interface methods
- Update BookingAuditTaskerProducerService to use simplified check (!params.isBookingAuditEnabled)
- Update BookingEventHandlerService to require isBookingAuditEnabled in all methods
- Update all callers to query booking-audit feature flag and pass isBookingAuditEnabled:
  - handleCancelBooking
  - handleConfirmation
  - roundRobinReassignment
  - roundRobinManualReassignment
  - addGuests.handler
  - confirm.handler
  - editLocation.handler
  - requestReschedule.handler
- Inject featuresRepository in API V2's booking-location.service.ts

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* test: update roundRobinReassignment tests to include isBookingAuditEnabled

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* test: update roundRobinManualReassignment tests to include isBookingAuditEnabled

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: inject featuresRepository in API V2 RecurringBookingService

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: import PrismaWorkerModule for PrismaFeaturesRepository dependency

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: use booking's organization for feature flag check in addGuests handler

Use booking.user?.profiles?.[0]?.organizationId instead of user.organizationId
to check the booking-audit feature flag. This ensures the feature flag is
checked against the booking's organization rather than the actor's organization,
which is consistent with other handlers in this PR.

Addresses Cubic AI review feedback (confidence 9/10).

Co-Authored-By: unknown <>

* Add comment

* fix: use user.organizationId for feature flag check in addGuests handler

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: use booking's organizationId for feature flag check in addGuests handler

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: revert to user.organizationId for feature flag check in addGuests handler

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: add isBookingAuditEnabled to onNoShowUpdated calls after main merge

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: add isBookingAuditEnabled to onNoShowUpdated calls and update tests

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 09:25:33 -03:00

316 lines
11 KiB
TypeScript

import type { CreateBookingMeta, CreateRecurringBookingData } from "@calcom/features/bookings/lib/dto/types";
import type { BookingResponse } from "@calcom/features/bookings/types";
import type { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { CreationSource, SchedulingType } from "@calcom/prisma/enums";
import type { AppsStatus } from "@calcom/types/Calendar";
import { v4 as uuidv4 } from "uuid";
import type { BookingStatus } from "@calcom/prisma/enums";
import type { IBookingService } from "../interfaces/IBookingService";
import type { RegularBookingService } from "./RegularBookingService";
import type { BookingEventHandlerService } from "../onBookingEvents/BookingEventHandlerService";
import { getBookingAuditActorForNewBooking } from "../handleNewBooking/getBookingAuditActorForNewBooking";
import { criticalLogger } from "@calcom/lib/logger.server";
import { getAuditActionSource } from "../handleNewBooking/getAuditActionSource";
import { safeStringify } from "@calcom/lib/safeStringify";
import {
buildBookingCreatedAuditData,
buildBookingRescheduledAuditData,
} from "../handleNewBooking/buildBookingEventAuditData";
export type BookingHandlerInput = {
bookingData: CreateRecurringBookingData;
} & CreateBookingMeta;
export const handleNewRecurringBooking = async function (
this: RecurringBookingService,
{
input,
deps,
creationSource,
}: {
input: BookingHandlerInput;
deps: IRecurringBookingServiceDependencies;
creationSource: CreationSource;
}
): Promise<BookingResponse[]> {
const data = input.bookingData;
const { regularBookingService } = deps;
const createdBookings: BookingResponse[] = [];
const allRecurringDates: { start: string; end: string | undefined }[] = data.map((booking) => {
return { start: booking.start, end: booking.end };
});
const appsStatus: AppsStatus[] | undefined = undefined;
const numSlotsToCheckForAvailability = 1;
let thirdPartyRecurringEventId = null;
// for round robin, the first slot needs to be handled first to define the lucky user
const firstBooking = data[0];
const isRoundRobin = firstBooking.schedulingType === SchedulingType.ROUND_ROBIN;
let luckyUsers = undefined;
const handleBookingMeta = {
userId: input.userId,
platformClientId: input.platformClientId,
platformRescheduleUrl: input.platformRescheduleUrl,
platformCancelUrl: input.platformCancelUrl,
platformBookingUrl: input.platformBookingUrl,
platformBookingLocation: input.platformBookingLocation,
areCalendarEventsEnabled: input.areCalendarEventsEnabled,
};
if (isRoundRobin) {
const recurringEventData = {
...firstBooking,
appsStatus,
allRecurringDates,
isFirstRecurringSlot: true,
thirdPartyRecurringEventId,
numSlotsToCheckForAvailability,
currentRecurringIndex: 0,
noEmail: input.noEmail !== undefined ? input.noEmail : false,
};
const firstBookingResult = await regularBookingService.createBooking({
bookingData: recurringEventData,
bookingMeta: {
hostname: input.hostname || "",
forcedSlug: input.forcedSlug as string | undefined,
...handleBookingMeta,
},
});
luckyUsers = firstBookingResult.luckyUsers;
}
for (let key = isRoundRobin ? 1 : 0; key < data.length; key++) {
const booking = data[key];
// Disable AppStatus in Recurring Booking Email as it requires us to iterate backwards to be able to compute the AppsStatus for all the bookings except the very first slot and then send that slot's email with statuses
// It is also doubtful that how useful is to have the AppsStatus of all the bookings in the email.
// It is more important to iterate forward and check for conflicts for only first few bookings defined by 'numSlotsToCheckForAvailability'
// if (key === 0) {
// const calcAppsStatus: { [key: string]: AppsStatus } = createdBookings
// .flatMap((book) => (book.appsStatus !== undefined ? book.appsStatus : []))
// .reduce((prev, curr) => {
// if (prev[curr.type]) {
// prev[curr.type].failures += curr.failures;
// prev[curr.type].success += curr.success;
// } else {
// prev[curr.type] = curr;
// }
// return prev;
// }, {} as { [key: string]: AppsStatus });
// appsStatus = Object.values(calcAppsStatus);
// }
const recurringEventData = {
...booking,
appsStatus,
allRecurringDates,
isFirstRecurringSlot: key == 0,
thirdPartyRecurringEventId,
numSlotsToCheckForAvailability,
currentRecurringIndex: key,
noEmail: input.noEmail !== undefined ? input.noEmail : key !== 0,
luckyUsers,
};
const promiseEachRecurringBooking = regularBookingService.createBooking({
bookingData: recurringEventData,
bookingMeta: {
hostname: input.hostname || "",
forcedSlug: input.forcedSlug as string | undefined,
...handleBookingMeta,
},
});
const eachRecurringBooking = await promiseEachRecurringBooking;
createdBookings.push(eachRecurringBooking);
if (!thirdPartyRecurringEventId) {
if (eachRecurringBooking.references && eachRecurringBooking.references.length > 0) {
for (const reference of eachRecurringBooking.references) {
if (reference.thirdPartyRecurringEventId) {
thirdPartyRecurringEventId = reference.thirdPartyRecurringEventId;
break;
}
}
}
}
}
if (createdBookings.length > 0) {
await this.fireBookingEvents({
createdBookings,
eventTypeId: firstBooking.eventTypeId,
rescheduleUid: firstBooking.rescheduleUid ?? null,
actorUserUuid: input.userUuid ?? null,
rescheduledBy: firstBooking.rescheduledBy ?? null,
creationSource,
});
}
return createdBookings;
};
export interface IRecurringBookingServiceDependencies {
regularBookingService: RegularBookingService;
bookingEventHandler: BookingEventHandlerService;
featuresRepository: FeaturesRepository;
}
/**
* Recurring Booking Service takes care of creating/rescheduling recurring bookings.
*/
export class RecurringBookingService implements IBookingService {
constructor(private readonly deps: IRecurringBookingServiceDependencies) {}
async fireBookingEvents({
createdBookings,
eventTypeId,
rescheduleUid,
actorUserUuid,
rescheduledBy,
creationSource,
}: {
createdBookings: BookingResponse[];
eventTypeId: number;
rescheduleUid: string | null;
actorUserUuid: string | null;
rescheduledBy: string | null;
creationSource: CreationSource | undefined;
}) {
try {
type ValidBooking = BookingResponse & {
uid: string;
startTime: Date;
endTime: Date;
status: BookingStatus;
userUuid: string | null;
};
type ValidRescheduledBooking = ValidBooking & {
previousBooking: ValidBooking & { status: BookingStatus };
};
const isReschedule = !!rescheduleUid;
const firstCreatedBooking = createdBookings[0];
const eventOrganizationId = firstCreatedBooking.organizationId;
const bookerAttendee = firstCreatedBooking.attendees?.[0];
const bookerAttendeeId = bookerAttendee?.id;
const bookerName = bookerAttendee?.name || "";
const bookerEmail = bookerAttendee?.email || "";
const isBookingAuditEnabled = eventOrganizationId
? await this.deps.featuresRepository.checkIfTeamHasFeature(eventOrganizationId, "booking-audit")
: false;
const rescheduledByAttendeeId = firstCreatedBooking.attendees?.find(
(attendee) => attendee.email === rescheduledBy
)?.id;
// TODO: Note that user.email is always null here as RegularBookingService intentionally sets it to null. To fix, we need to separate out external facing .createBooking and one that is used by RecurringBookingService, so that if we expose something there it doesn't get exposed elsewhere
const rescheduledByUserUuid =
firstCreatedBooking.user?.email === rescheduledBy ? firstCreatedBooking.userUuid : null;
const auditActor = getBookingAuditActorForNewBooking({
bookerAttendeeId: bookerAttendeeId ?? null,
actorUserUuid,
bookerEmail,
bookerName,
rescheduledBy: rescheduledBy
? {
attendeeId: rescheduledByAttendeeId ?? null,
userUuid: rescheduledByUserUuid ?? null,
email: rescheduledBy,
}
: null,
logger: criticalLogger,
});
const actionSource = getAuditActionSource({ creationSource, eventTypeId, rescheduleUid });
const operationId = uuidv4();
const isValidBooking = (booking: BookingResponse): booking is ValidBooking => {
return !!(booking.uid && booking.startTime && booking.endTime && booking.status);
};
const isValidRescheduledBooking = (booking: BookingResponse): booking is ValidRescheduledBooking => {
return !!(
isValidBooking(booking) &&
booking.previousBooking &&
booking.previousBooking.uid &&
booking.previousBooking.startTime &&
booking.previousBooking.endTime
);
};
if (isReschedule) {
const bulkRescheduledBookings = createdBookings.filter(isValidRescheduledBooking).map((booking) => ({
bookingUid: booking.previousBooking.uid,
auditData: buildBookingRescheduledAuditData({
oldBooking: booking.previousBooking,
newBooking: booking,
}),
}));
if (bulkRescheduledBookings.length > 0) {
await this.deps.bookingEventHandler.onBulkBookingsRescheduled({
bookings: bulkRescheduledBookings,
actor: auditActor,
organizationId: eventOrganizationId,
operationId,
source: actionSource,
isBookingAuditEnabled,
});
}
} else {
// For new bookings
const bulkCreatedBookings = createdBookings.filter(isValidBooking).map((booking) => ({
bookingUid: booking.uid,
auditData: buildBookingCreatedAuditData({ booking, attendeeSeatId: null }),
}));
if (bulkCreatedBookings.length > 0) {
await this.deps.bookingEventHandler.onBulkBookingsCreated({
bookings: bulkCreatedBookings,
actor: auditActor,
organizationId: eventOrganizationId,
operationId,
source: actionSource,
isBookingAuditEnabled,
});
}
}
} catch (error) {
criticalLogger.error("Error while firing booking events", safeStringify(error));
}
}
async createBooking(input: {
bookingData: CreateRecurringBookingData;
bookingMeta?: CreateBookingMeta;
creationSource: CreationSource;
}): Promise<BookingResponse[]> {
const handlerInput = { bookingData: input.bookingData, ...(input.bookingMeta || {}) };
return handleNewRecurringBooking.bind(this)({
input: handlerInput,
deps: this.deps,
creationSource: input.creationSource,
});
}
async rescheduleBooking(input: {
bookingData: CreateRecurringBookingData;
bookingMeta?: CreateBookingMeta;
creationSource: CreationSource;
}): Promise<BookingResponse[]> {
const handlerInput = { bookingData: input.bookingData, ...(input.bookingMeta || {}) };
return handleNewRecurringBooking.bind(this)({
input: handlerInput,
deps: this.deps,
creationSource: input.creationSource,
});
}
}