Files
cal.diy/packages/features/booking-audit/lib/actions/CreatedAuditActionService.ts
T
25857c07e1 feat(bookings): add booking audit logging to instant bookings (#28176)
* feat(bookings): add booking audit logging to instant bookings

wire up BookingEventHandlerService.onBookingCreated in
InstantBookingCreateService to emit audit events, matching the
pattern already used in RegularBookingService and
RecurringBookingService.

* refactor: extract fireBookingEvents and reuse existing orgId

* refactor: derive orgId once and pass to both webhook trigger and audit event

* fix: add missing return in webhook map callback

* refactor: make creationSource required for instant bookings

Both callers (WEBAPP and API_V2) always set creationSource, so validate
it upfront and use CreationSource enum type instead of string | null.

* fix: use ErrorWithCode instead of Error, pass userUuid to audit events

* fix: pass null for hostUserUuid in instant booking audit data

Instant bookings have status AWAITING_HOST with no assigned host,
so the booker's UUID should not be recorded as hostUserUuid.

* fix: address devin review - hostUserUuid and creationSource validation

* fix: address review - bookingMeta, getOrgIdFromMemberOrTeamId, required creationSource

- pass userUuid via bookingMeta instead of separate param (matches RegularBookingService pattern)
- restore getOrgIdFromMemberOrTeamId for proper org resolution instead of eventType.team.parentId
- make creationSource required with runtime validation instead of defaulting to WEBAPP

* fix: enforce creationSource at compile time instead of runtime

use Required<Pick<>> to make creationSource required in the type
signature. removes the runtime check since TypeScript catches
missing creationSource at build time.

* fix: simplify type signature and derive hostUserUuid from booking relation

- Replace Required<Pick<CreateInstantBookingData, 'creationSource'>> with inline { creationSource: CreationSource }
- Include user relation in booking create query to derive hostUserUuid
- Pass newBooking.user?.uuid instead of hardcoding null for userUuid in audit data

Co-Authored-By: [email protected] <[email protected]>

* chore: trigger CI

* fix: add missing impersonatedByUserUuid to instant booking meta

The CreateBookingMeta type requires impersonatedByUserUuid. Set it to
null for non-impersonated instant bookings.

* fix: show 'awaiting host' in audit log for instant bookings

Use booking status AWAITING_HOST to display "Booked (awaiting host)"
instead of "Booked with Unknown" when no host has accepted yet.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* feat: add booking audit for instant meeting accept via connect-and-join

Extract fireInstantBookingAcceptedAuditEvent to InstantBookingCreateService
and fire it right after the DB update, before side-effect notifications.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* test: add audit logging tests for instant booking creation

* fix: simulate audit failure in resilience test (identified by cubic)

The test 'should not throw when booking audit event fails' was not
actually simulating an audit failure. Added vi.spyOn on
BookingEventHandlerService.prototype.onBookingCreated to reject with
an error, and assert the spy was called, proving the try/catch in
fireBookingEvents properly catches the error without breaking the
booking flow.

Co-Authored-By: bot_apk <[email protected]>

* test: add audit event tests for connectAndJoin and fix InstantBooking audit test

* test

---------

Co-authored-by: Hariom Balhara <[email protected]>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: [email protected] <[email protected]>
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: bot_apk <[email protected]>
2026-04-04 13:30:03 -03:00

115 lines
3.9 KiB
TypeScript

import { z } from "zod";
import { BookingStatus } from "@calcom/prisma/enums";
import { AuditActionServiceHelper } from "./AuditActionServiceHelper";
import type {
IAuditActionService,
TranslationWithParams,
GetDisplayTitleParams,
GetDisplayJsonParams,
BaseStoredAuditData,
} from "./IAuditActionService";
import type { DataRequirements } from "../service/EnrichmentDataStore";
/**
* Created Audit Action Service
*
* Note: CREATED action captures initial state, so it doesn't use { old, new } pattern
*/
// Module-level because it is passed to IAuditActionService type outside the class scope
const fieldsSchemaV1 = z.object({
startTime: z.number(),
endTime: z.number(),
status: z.nativeEnum(BookingStatus),
hostUserUuid: z.string().nullable(),
// Allowing it to be optional because most of the time(non-seated booking) it won't be there
seatReferenceUid: z.string().nullish(),
});
export class CreatedAuditActionService implements IAuditActionService {
readonly VERSION = 1;
public static readonly TYPE = "CREATED" 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 = CreatedAuditActionService.dataSchemaV1;
// Union of all versions
public static readonly storedFieldsSchema = CreatedAuditActionService.fieldsSchemaV1;
private helper: AuditActionServiceHelper<
typeof CreatedAuditActionService.latestFieldsSchema,
typeof CreatedAuditActionService.storedDataSchema
>;
constructor() {
this.helper = new AuditActionServiceHelper({
latestVersion: this.VERSION,
latestFieldsSchema: CreatedAuditActionService.latestFieldsSchema,
storedDataSchema: CreatedAuditActionService.storedDataSchema,
});
}
getVersionedData(fields: unknown) {
return this.helper.getVersionedData(fields);
}
parseStored(data: unknown) {
return this.helper.parseStored(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 };
}
getDataRequirements(storedData: BaseStoredAuditData): DataRequirements {
const { fields } = this.parseStored(storedData);
return {
userUuids: fields.hostUserUuid ? [fields.hostUserUuid] : [],
};
}
async getDisplayTitle({ storedData, dbStore }: GetDisplayTitleParams): Promise<TranslationWithParams> {
const { fields } = this.parseStored(storedData);
if (fields.status === BookingStatus.AWAITING_HOST) {
return { key: "booking_audit_action.created_awaiting_host", params: {} };
}
const hostUser = fields.hostUserUuid ? dbStore.getUserByUuid(fields.hostUserUuid) : null;
const hostName = hostUser?.name ?? "Unknown";
if (fields.seatReferenceUid) {
return { key: "booking_audit_action.created_with_seat", params: { host: hostName } };
}
return { key: "booking_audit_action.created", params: { host: hostName } };
}
getDisplayJson({ storedData, userTimeZone }: GetDisplayJsonParams): CreatedAuditDisplayData {
const { fields } = this.parseStored({ version: storedData.version, fields: storedData.fields });
const timeZone = userTimeZone;
return {
startTime: AuditActionServiceHelper.formatDateTimeInTimeZone(fields.startTime, timeZone),
endTime: AuditActionServiceHelper.formatDateTimeInTimeZone(fields.endTime, timeZone),
status: fields.status,
...(fields.seatReferenceUid ? { seatReferenceUid: fields.seatReferenceUid } : {}),
};
}
}
export type CreatedAuditData = z.infer<typeof fieldsSchemaV1>;
export type CreatedAuditDisplayData = {
startTime: string;
endTime: string;
status: BookingStatus;
seatReferenceUid?: string;
};