Files
Hariom BalharaandGitHub 7ec8601bd6 chore: Integrate edit location booking audit (#26569)
## What does this PR do?

Integrates booking audit logging for the edit location functionality, following the pattern established in PR #26046 (booking creation/rescheduling audit).

This PR adds audit logging when a booking's location is changed through:
1. **Web app** (tRPC handler): `packages/trpc/server/routers/viewer/bookings/editLocation.handler.ts`
2. **API v2**: `apps/api/v2/src/ee/bookings/2024-08-13/services/booking-location.service.ts`

### Changes:
- Added `actionSource` as a **required** parameter to `editLocationHandler` (no fallback)
- Added optional `userUuid` parameter (defaults to logged-in user's uuid)
- Added `ValidActionSource` type that excludes "UNKNOWN" for client-facing APIs
- Captures old location before update for audit data
- Calls `BookingEventHandlerService.onLocationChanged()` after successful location update
- Web app uses `actionSource: "WEBAPP"`, API v2 uses `actionSource: "API_V2"`
- Updated router to explicitly pass `actionSource: "WEBAPP"`
- Updated test to pass `actionSource: "WEBAPP"`
- **API v2**: Uses NestJS dependency injection pattern with `BookingEventHandlerService` injected via constructor

### Updates since last revision:
- **Created `BookingEventHandlerModule`** (`apps/api/v2/src/lib/modules/booking-event-handler.module.ts`) to encapsulate `BookingEventHandlerService` and its dependencies (Logger, TaskerService, HashedLinkService, BookingAuditProducerService)
- Updated both bookings modules (2024-04-15 and 2024-08-13) to import `BookingEventHandlerModule` instead of listing individual providers
- This reduces code duplication and makes dependency management cleaner

## 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. N/A - using existing audit infrastructure that is already tested.

## How should this be tested?

1. Update a booking's location through the web app
2. Update a booking's location through API v2
3. Verify audit logs are created with:
   - Correct `bookingUid`
   - Correct `actor` (user who made the change)
   - Correct `source` ("WEBAPP" or "API_V2")
   - Correct `auditData.location.old` and `auditData.location.new` values

## Checklist

- [x] My code follows the style guidelines of this project
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have checked if my changes generate no new warnings

## Human Review Checklist

- [ ] Verify all callers of `editLocationHandler` pass `actionSource` (router updated, test updated)
- [ ] Verify `organizationId` derivation is correct in both handlers (tRPC uses `booking.user?.profiles?.[0]?.organizationId`, API v2 uses `existingBookingHost.organizationId`)
- [ ] Confirm audit call placement after location update is intentional (audit failures would fail the operation even though location was already updated)
- [ ] Note: API v2 has its own implementation and does NOT reuse `editLocationHandler` - this is correct
- [ ] Verify `BookingEventHandlerModule` properly exports `BookingEventHandlerService` and is imported in both bookings modules
- [ ] Verify the `updateBookingLocationInDb` return value (`{ updatedLocation }`) is destructured and used correctly for audit data
- [ ] Verify API v2 uses `bookingLocation` for audit `new` value, while tRPC uses `updatedLocation` from DB update

---


Link to Devin run: https://app.devin.ai/sessions/fd1d439779674050a26ea3fa7d799943
Requested by: @hariombalhara
2026-01-20 18:40:48 +05:30

249 lines
7.0 KiB
TypeScript

/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
// TODO: Bring this test back with the correct setup (no illegal imports)
// NOTE: All imports except vitest are deferred to inside the skipped describe blocks
// to prevent module loading side effects during test collection (which can cause
// "Closing rpc while fetch was pending" errors from watchlist module imports)
import { beforeEach, describe, expect, test, vi } from "vitest";
describe.skip("getLocationForOrganizerDefaultConferencingAppInEvtFormat", () => {
const mockTranslate = vi.fn((key: string) => key);
beforeEach(() => {
vi.resetAllMocks();
});
describe("Dynamic link apps", () => {
test("should return the app type for Zoom", () => {
const organizer = {
name: "Test Organizer",
metadata: {
defaultConferencingApp: {
appSlug: "zoom",
},
},
};
const result = getLocationForOrganizerDefaultConferencingAppInEvtFormat({
organizer,
loggedInUserTranslate: mockTranslate,
});
expect(result).toBe("integrations:zoom");
});
test("should return the app type for Google Meet", () => {
const organizer = {
name: "Test Organizer",
metadata: {
defaultConferencingApp: {
appSlug: "google-meet",
},
},
};
const result = getLocationForOrganizerDefaultConferencingAppInEvtFormat({
organizer,
loggedInUserTranslate: mockTranslate,
});
expect(result).toBe("integrations:google:meet");
});
});
describe("Static link apps", () => {
test("should return the app type for Campfire", () => {
const organizer = {
name: "Test Organizer",
metadata: {
defaultConferencingApp: {
appSlug: "campfire",
appLink: "https://campfire.com",
},
},
};
const result = getLocationForOrganizerDefaultConferencingAppInEvtFormat({
organizer,
loggedInUserTranslate: mockTranslate,
});
expect(result).toBe("https://campfire.com");
});
});
describe("Error handling", () => {
test("should throw a UserError if defaultConferencingApp is not set", () => {
const organizer = {
name: "Test Organizer",
metadata: null,
};
expect(() =>
getLocationForOrganizerDefaultConferencingAppInEvtFormat({
organizer,
loggedInUserTranslate: mockTranslate,
})
).toThrow(UserError);
expect(mockTranslate).toHaveBeenCalledWith("organizer_default_conferencing_app_not_found", {
organizer: "Test Organizer",
});
});
test("should throw a SystemError if the app is not found", () => {
const organizer = {
name: "Test Organizer",
metadata: {
defaultConferencingApp: {
appSlug: "invalid-app",
},
},
};
expect(() =>
getLocationForOrganizerDefaultConferencingAppInEvtFormat({
organizer,
loggedInUserTranslate: mockTranslate,
})
).toThrow(SystemError);
});
test("should throw a SystemError for static link apps if appLink is missing", () => {
const organizer = {
name: "Test Organizer",
metadata: {
defaultConferencingApp: {
appSlug: "no-link-app",
},
},
};
expect(() =>
getLocationForOrganizerDefaultConferencingAppInEvtFormat({
organizer,
loggedInUserTranslate: mockTranslate,
})
).toThrow(SystemError);
});
});
});
describe.skip("editLocation.handler", () => {
describe("Changing organizer default conferencing app", () => {
test("should update the booking location when organizer's default conferencing app changes", async ({
emails,
}) => {
const scenarioData = {
organizer: getOrganizer({
name: "Organizer",
email: "[email protected]",
id: 101,
schedules: [TestData.schedules.IstWorkHours],
credentials: [getZoomAppCredential()],
selectedCalendars: [TestData.selectedCalendars.google],
destinationCalendar: {
integration: "google_calendar",
externalId: "[email protected]",
},
metadata: {
defaultConferencingApp: {
appSlug: "campfire",
appLink: "https://campfire.com",
},
},
}),
eventTypes: [
{
id: 1,
slotInterval: 45,
length: 45,
users: [{ id: 101 }],
},
],
bookings: [
{
id: 1,
uid: "booking-1",
eventTypeId: 1,
status: BookingStatus.ACCEPTED,
startTime: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
endTime: new Date(Date.now() + 25 * 60 * 60 * 1000).toISOString(),
userId: 101,
attendees: [
{
id: 102,
name: "Attendee 1",
email: "[email protected]",
timeZone: "Asia/Kolkata",
},
],
},
],
// biome-ignore lint/complexity/useLiteralKeys: app keys contain hyphens
apps: [TestData.apps["zoom"], TestData.apps["google-meet"]],
};
await createBookingScenario(getScenarioData(scenarioData));
const booking = await prisma.booking.findFirst({
where: {
uid: scenarioData.bookings[0].uid,
},
include: {
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
user: true,
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
attendees: true,
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
references: true,
},
});
const organizerUser = await prisma.user.findFirst({
where: {
id: scenarioData.organizer.id,
},
});
expect(booking).not.toBeNull();
// Simulate changing the organizer's default conferencing app to Google Meet
const updatedOrganizer = {
...booking.user,
metadata: {
...booking.user.metadata,
defaultConferencingApp: {
appSlug: "google-meet",
},
},
};
await editLocationHandler({
ctx: {
booking,
user: organizerUser,
},
input: {
newLocation: "conferencing",
},
actionSource: "WEBAPP",
});
const updatedBooking = await prisma.booking.findFirstOrThrow({
where: {
uid: scenarioData.bookings[0].uid,
},
});
expect(updatedBooking.location).toBe("https://campfire.com");
expectSuccesfulLocationChangeEmails({
emails,
organizer: organizerUser,
location: {
href: "https://campfire.com",
linkText: "Link",
},
});
});
});
});