Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions apps/api/v1/lib/audit-log.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { AuditLogEvent } from "~/lib/types";

export const AuditLogService = {
async logEvent(event: AuditLogEvent): Promise<void> {
console.log("Audit Log Event:", event);
},
Comment on lines +4 to +6
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider production-ready logging implementation.

Console logging is not suitable for production environments. Consider implementing proper structured logging with log levels, error handling, and persistence.

-  async logEvent(event: AuditLogEvent): Promise<void> {
-    console.log("Audit Log Event:", event);
-  },
+  async logEvent(event: AuditLogEvent): Promise<void> {
+    try {
+      // TODO: Implement proper logging mechanism (database, external service, etc.)
+      console.log("Audit Log Event:", event);
+      
+      // Future implementation might include:
+      // - Database persistence
+      // - External audit service integration
+      // - Structured logging with proper log levels
+    } catch (error) {
+      console.error("Failed to log audit event:", error);
+      // Consider whether to throw or handle gracefully
+    }
+  },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async logEvent(event: AuditLogEvent): Promise<void> {
console.log("Audit Log Event:", event);
},
async logEvent(event: AuditLogEvent): Promise<void> {
try {
// TODO: Implement proper logging mechanism (database, external service, etc.)
console.log("Audit Log Event:", event);
// Future implementation might include:
// - Database persistence
// - External audit service integration
// - Structured logging with proper log levels
} catch (error) {
console.error("Failed to log audit event:", error);
// Consider whether to throw or handle gracefully
}
},
🤖 Prompt for AI Agents
In apps/api/v1/lib/audit-log.service.ts around lines 4 to 6, replace the
console.log statement with a production-ready logging solution. Integrate a
structured logger that supports log levels (e.g., info, error), handles errors
gracefully, and persists logs to a file or external logging service. Ensure the
logger formats the event data clearly and can be configured for different
environments.


async getEvents(filter?: any): Promise<AuditLogEvent[]> {
// Returning Expty array for now
return [];
},
Comment on lines +8 to +11
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve type safety for filter parameter.

The filter parameter is typed as any, which reduces type safety. Consider defining a proper filter interface or use a more specific type.

+interface AuditLogFilter {
+  orgId?: string;
+  userId?: string;
+  action?: string;
+  [key: string]: any;
+}
+
-  async getEvents(filter?: any): Promise<AuditLogEvent[]> {
+  async getEvents(filter?: AuditLogFilter): Promise<AuditLogEvent[]> {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async getEvents(filter?: any): Promise<AuditLogEvent[]> {
// Returning Expty array for now
return [];
},
interface AuditLogFilter {
orgId?: string;
userId?: string;
action?: string;
[key: string]: any;
}
async getEvents(filter?: AuditLogFilter): Promise<AuditLogEvent[]> {
// Returning Expty array for now
return [];
},
🤖 Prompt for AI Agents
In apps/api/v1/lib/audit-log.service.ts around lines 8 to 11, the filter
parameter in the getEvents method is typed as any, which reduces type safety.
Define a specific interface or type that describes the expected structure of the
filter object and update the method signature to use this type instead of any to
improve type safety and code clarity.

};
6 changes: 6 additions & 0 deletions apps/api/v1/lib/helpers/audit-log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { AuditLogService } from "~/lib/audit-log.service";
import type { AuditLogEvent } from "~/lib/types";

export async function EmitAuditLogEvent(event: AuditLogEvent) {
await AuditLogService.logEvent(event);
}
Comment on lines +4 to +6
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling to the wrapper function.

The wrapper function should handle potential errors from the underlying service call, especially since audit logging failures shouldn't typically break the main application flow.

-export async function EmitAuditLogEvent(event: AuditLogEvent) {
-  await AuditLogService.logEvent(event);
-}
+export async function EmitAuditLogEvent(event: AuditLogEvent) {
+  try {
+    await AuditLogService.logEvent(event);
+  } catch (error) {
+    console.error("Failed to emit audit log event:", error);
+    // Consider whether to throw or handle gracefully based on requirements
+  }
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export async function EmitAuditLogEvent(event: AuditLogEvent) {
await AuditLogService.logEvent(event);
}
export async function EmitAuditLogEvent(event: AuditLogEvent) {
try {
await AuditLogService.logEvent(event);
} catch (error) {
console.error("Failed to emit audit log event:", error);
// Consider whether to throw or handle gracefully based on requirements
}
}
🤖 Prompt for AI Agents
In apps/api/v1/lib/helpers/audit-log.ts around lines 4 to 6, the
EmitAuditLogEvent function lacks error handling for the awaited
AuditLogService.logEvent call. Wrap the await call in a try-catch block to catch
any errors thrown by logEvent, and handle them gracefully, such as logging the
error without rethrowing, to prevent audit logging failures from affecting the
main application flow.

12 changes: 12 additions & 0 deletions apps/api/v1/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,18 @@ interface EventTypeExtended extends Omit<EventType, "recurringEvent" | "location
| any;
}

//Audit Logs for Teams
export type AuditLogAction = "RENAME" | "DELETE" | "BOOK" | "CANCEL" | "CREATE";

export interface AuditLogEvent {
timestamp: string;
userId: string;
orgId: string;
action: AuditLogAction;
resource: string;
details: Record<string, any>;
}
Comment on lines +152 to +159
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Address interface inconsistencies and improve type safety.

The AuditLogEvent interface has several concerns:

  1. Missing fields: The PR objectives mention id, teamId, and description fields that are not present in this interface.
  2. Type safety: The details field uses Record<string, any> which reduces type safety.
  3. Field naming: Consider using resourceId instead of resource for clarity.
 export interface AuditLogEvent {
+  id: string;
   timestamp: string;
   userId: string;
   orgId: string;
+  teamId?: string;
   action: AuditLogAction;
-  resource: string;
+  resourceId: string;
+  resourceType: string;
+  description?: string;
-  details: Record<string, any>;
+  details: Record<string, unknown>;
 }

The details field should use unknown instead of any for better type safety, or consider defining specific detail types for different actions.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export interface AuditLogEvent {
timestamp: string;
userId: string;
orgId: string;
action: AuditLogAction;
resource: string;
details: Record<string, any>;
}
export interface AuditLogEvent {
id: string;
timestamp: string;
userId: string;
orgId: string;
teamId?: string;
action: AuditLogAction;
resourceId: string;
resourceType: string;
description?: string;
details: Record<string, unknown>;
}
🤖 Prompt for AI Agents
In apps/api/v1/lib/types.ts around lines 152 to 159, update the AuditLogEvent
interface to include the missing fields id, teamId, and description as specified
in the PR objectives. Rename the resource field to resourceId for clearer
semantics. Replace the details field type from Record<string, any> to
Record<string, unknown> to improve type safety, or alternatively define specific
types for details based on different AuditLogAction values to enforce stricter
typing.

Comment on lines +152 to +159
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Interface definition needs alignment with PR objectives.

The interface is missing several fields mentioned in the PR objectives and has some type considerations:

  1. Missing fields: The PR objectives mention id, teamId, and description fields that are not present in the interface.
  2. Timestamp type: Consider using Date type or specifying the string format (e.g., ISO 8601).
  3. Optional properties: Consider making some fields optional (e.g., orgId, details) for flexibility.

Apply this diff to align with PR objectives:

 export interface AuditLogEvent {
+  id: string;
-  timestamp: string;
+  timestamp: Date;
   userId: string;
-  orgId: string;
+  orgId?: string;
+  teamId?: string;
   action: AuditLogAction;
   resource: string;
+  description?: string;
-  details: Record<string, any>;
+  details?: Record<string, any>;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export interface AuditLogEvent {
timestamp: string;
userId: string;
orgId: string;
action: AuditLogAction;
resource: string;
details: Record<string, any>;
}
export interface AuditLogEvent {
id: string;
timestamp: Date;
userId: string;
orgId?: string;
teamId?: string;
action: AuditLogAction;
resource: string;
description?: string;
details?: Record<string, any>;
}
🤖 Prompt for AI Agents
In apps/api/v1/lib/types.ts around lines 152 to 159, the AuditLogEvent interface
is missing the id, teamId, and description fields as required by the PR
objectives. Update the interface to include these fields, change the timestamp
type to Date or specify its string format explicitly, and make orgId and details
optional properties to increase flexibility.


// EventType
export type EventTypeResponse = BaseResponse & {
event_type?: Partial<EventType | EventTypeExtended>;
Expand Down
29 changes: 29 additions & 0 deletions apps/api/v1/pages/api/audit-logs/_get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { NextApiRequest, NextApiResponse } from "next";

import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";

import { AuditLogService } from "~/lib/audit-log.service";
import type { AuditLogEvent } from "~/lib/types";

async function handler(req: NextApiRequest, res: NextApiResponse) {
const { orgId, userId, action } = req.query;

const filter: Record<string, string | undefined> = {
orgId: typeof orgId === "string" ? orgId : undefined,
userId: typeof userId === "string" ? userId : undefined,
action: typeof action === "string" ? action : undefined,
};

try {
const events: AuditLogEvent[] = await AuditLogService.getEvents?.(filter);
return res.status(200).json({ events });
} catch (error) {
throw new HttpError({
statusCode: 500,
message: "Failed to fetch audit logs",
});
}
}

export default defaultResponder(handler);
37 changes: 37 additions & 0 deletions apps/api/v1/pages/api/audit-logs/_post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { NextApiRequest, NextApiResponse } from "next";

import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";

import { AuditLogService } from "~/lib/audit-log.service";
import type { AuditLogEvent } from "~/lib/types";

async function handler(req: NextApiRequest, res: NextApiResponse) {
const body = req.body as Partial<AuditLogEvent>;
if (!body || typeof body !== "object") {
throw new HttpError({
statusCode: 400,
message: "Invalid/Missing JSON body",
});
}

// Required audit event fields
const requiredFields = ["timestamp", "userId", "orgId", "action", "resource", "details"];
for (const field of requiredFields) {
if (!body[field as keyof AuditLogEvent]) {
throw new HttpError({
statusCode: 400,
message: `Missing required field: ${field}`,
});
}
}

try {
await AuditLogService.logEvent(body as AuditLogEvent);
return res.status(201).json({ ok: true });
} catch (error: unknown) {
throw error;
}
Comment on lines +29 to +34
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove unnecessary try/catch clause.

The try/catch block that only rethrows the original error is unnecessary and can be confusing. The defaultResponder wrapper already handles error catching and response formatting.

-  try {
-    await AuditLogService.logEvent(body as AuditLogEvent);
-    return res.status(201).json({ ok: true });
-  } catch (error: unknown) {
-    throw error;
-  }
+  await AuditLogService.logEvent(body as AuditLogEvent);
+  return res.status(201).json({ ok: true });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
await AuditLogService.logEvent(body as AuditLogEvent);
return res.status(201).json({ ok: true });
} catch (error: unknown) {
throw error;
}
await AuditLogService.logEvent(body as AuditLogEvent);
return res.status(201).json({ ok: true });
🧰 Tools
🪛 Biome (1.9.4)

[error] 33-33: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the try/catch clause.

(lint/complexity/noUselessCatch)

🤖 Prompt for AI Agents
In apps/api/v1/pages/api/audit-logs/_post.ts around lines 29 to 34, remove the
try/catch block that only rethrows the error because it is redundant. The
defaultResponder wrapper already manages error catching and response formatting,
so simply call AuditLogService.logEvent and return the success response without
the try/catch.

}
Comment on lines +29 to +35
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove unnecessary try-catch block.

The catch clause only rethrows the original error without adding any value. Since the defaultResponder wrapper already handles errors appropriately, this try-catch block is unnecessary.

-  try {
-    await AuditLogService.logEvent(body as AuditLogEvent);
-    return res.status(201).json({ ok: true });
-  } catch (error: unknown) {
-    throw error;
-  }
+  await AuditLogService.logEvent(body as AuditLogEvent);
+  return res.status(201).json({ ok: true });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
await AuditLogService.logEvent(body as AuditLogEvent);
return res.status(201).json({ ok: true });
} catch (error: unknown) {
throw error;
}
}
await AuditLogService.logEvent(body as AuditLogEvent);
return res.status(201).json({ ok: true });
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 33-33: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the try/catch clause.

(lint/complexity/noUselessCatch)

🤖 Prompt for AI Agents
In apps/api/v1/pages/api/audit-logs/_post.ts around lines 29 to 35, remove the
try-catch block that wraps the call to AuditLogService.logEvent because the
catch block only rethrows the error without any additional handling. Since error
handling is already managed by the defaultResponder wrapper, simply call
AuditLogService.logEvent and return the response without the try-catch.


export default defaultResponder(handler);
10 changes: 10 additions & 0 deletions apps/api/v1/pages/api/audit-logs/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { defaultHandler } from "@calcom/lib/server/defaultHandler";

import { withMiddleware } from "~/lib/helpers/withMiddleware";

export default withMiddleware()(
defaultHandler({
POST: import("./_post"),
GET: import("./_get"),
})
);
1 change: 1 addition & 0 deletions apps/api/v2/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.1.1",
"@nestjs/core": "^10.0.0",
"@nestjs/event-emitter": "^3.0.1",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^10.0.2",
"@nestjs/platform-express": "^10.0.0",
Expand Down
2 changes: 2 additions & 0 deletions apps/api/v2/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ import { BullModule } from "@nestjs/bull";
import { MiddlewareConsumer, Module, NestModule, RequestMethod } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { APP_GUARD, APP_INTERCEPTOR, APP_FILTER } from "@nestjs/core";
import { EventEmitterModule } from "@nestjs/event-emitter";
import { seconds, ThrottlerModule } from "@nestjs/throttler";
import { SentryModule, SentryGlobalFilter } from "@sentry/nestjs/setup";

import { AppController } from "./app.controller";

@Module({
imports: [
EventEmitterModule.forRoot(),
SentryModule.forRoot(),
ConfigModule.forRoot({
ignoreEnvFile: true,
Expand Down
10 changes: 10 additions & 0 deletions apps/api/v2/src/ee/audit-logs/lib/audit-log.events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export const AUDIT_LOG_EVENT = "audit.log";

export type AuditLogPayload = {
teamId: number;
actorId: number;
action: string;
targetType: string;
targetId: string;
metadata?: Record<string, unknown>;
};
29 changes: 29 additions & 0 deletions apps/api/v2/src/ee/audit-logs/lib/audit-log.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { AuditLogPayload } from "@/ee/audit-logs/lib/audit-log.events";
import { Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { PrismaWriteService } from "src/modules/prisma/prisma-write.service";

export abstract class AuditLogService {
abstract log(payload: AuditLogPayload): Promise<void>;
}

@Injectable()
export class PrismaAuditLogService extends AuditLogService {
// Injecting the PrismaWriteService class
constructor(private readonly prismaWriteService: PrismaWriteService) {
super();
}

async log(payload: AuditLogPayload): Promise<void> {
await this.prismaWriteService.prisma.auditLog.create({
data: {
teamId: payload.teamId,
actorId: payload.actorId,
action: payload.action,
targetType: payload.targetType,
targetId: payload.targetId,
metadata: (payload.metadata || {}) as Prisma.InputJsonValue,
},
});
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { AUDIT_LOG_EVENT, AuditLogPayload } from "@/ee/audit-logs/lib/audit-log.events";
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.repository";
import { CalendarLink } from "@/ee/bookings/2024-08-13/outputs/calendar-links.output";
import { ErrorsBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/errors.service";
Expand All @@ -20,6 +21,7 @@ import { UsersService } from "@/modules/users/services/users.service";
import { UsersRepository, UserWithProfile } from "@/modules/users/users.repository";
import { ConflictException, Injectable, Logger, NotFoundException } from "@nestjs/common";
import { BadRequestException } from "@nestjs/common";
import { EventEmitter2 } from "@nestjs/event-emitter";
import { Request } from "express";
import { DateTime } from "luxon";
import { z } from "zod";
Expand Down Expand Up @@ -53,7 +55,7 @@ import {
CancelBookingInput,
} from "@calcom/platform-types";
import { PrismaClient } from "@calcom/prisma";
import { EventType, User, Team } from "@calcom/prisma/client";
import { Booking, EventType, User, Team } from "@calcom/prisma/client";

type CreatedBooking = {
hosts: { id: number }[];
Expand Down Expand Up @@ -95,7 +97,8 @@ export class BookingsService_2024_08_13 {
private readonly organizationsRepository: OrganizationsRepository,
private readonly teamsRepository: TeamsRepository,
private readonly teamsEventTypesRepository: TeamsEventTypesRepository,
private readonly errorsBookingsService: ErrorsBookingsService_2024_08_13
private readonly errorsBookingsService: ErrorsBookingsService_2024_08_13,
private readonly eventEmitter: EventEmitter2
) {}

async createBooking(request: Request, body: CreateBookingInput) {
Expand Down Expand Up @@ -385,6 +388,20 @@ export class BookingsService_2024_08_13 {
throw new Error(`Booking with id=${booking.bookingId} was not found in the database`);
}

// AUDIT LOG: Only emit an event if the event type belongs to a team.
if (eventType.teamId) {
this._emitAuditEvent({
action: "booking.created",
actorId: bookingRequest.userId,
teamId: eventType.teamId, // This is now guaranteed to be a number
booking: databaseBooking,
metadata: {
instant: true,
bookerEmail: body.attendee.email,
},
});
}

return this.outputService.getOutputBooking(databaseBooking);
}

Expand Down Expand Up @@ -1018,4 +1035,30 @@ export class BookingsService_2024_08_13 {
t: await getTranslation("en", "common"),
});
}

private _emitAuditEvent(data: {
action: string;
actorId: number;
teamId: number;
booking: Partial<Booking & { uid?: string }>;
metadata?: Record<string, unknown>;
}) {
if (!data.teamId) {
return; // Don't log if there's no associated team/org
}

const payload: AuditLogPayload = {
action: data.action,
actorId: data.actorId,
teamId: data.teamId,
targetType: "Booking",
targetId: String(data.booking.id),
metadata: {
bookingUid: data.booking.uid,
bookingTitle: data.booking.title,
...data.metadata,
},
};
this.eventEmitter.emit(AUDIT_LOG_EVENT, payload);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
-- CreateTable
CREATE TABLE "AuditLog" (
"id" SERIAL NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"teamId" INTEGER NOT NULL,
"actorId" INTEGER NOT NULL,
"action" TEXT NOT NULL,
"targetType" TEXT NOT NULL,
"targetId" TEXT NOT NULL,
"metadata" JSONB NOT NULL,

CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "AuditLog_teamId_idx" ON "AuditLog"("teamId");

-- CreateIndex
CREATE INDEX "AuditLog_actorId_idx" ON "AuditLog"("actorId");

-- CreateIndex
CREATE INDEX "AuditLog_targetType_targetId_idx" ON "AuditLog"("targetType", "targetId");

-- AddForeignKey
ALTER TABLE "AuditLog" ADD CONSTRAINT "AuditLog_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "AuditLog" ADD CONSTRAINT "AuditLog_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
29 changes: 29 additions & 0 deletions packages/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,9 @@ model User {
creditBalance CreditBalance?
whitelistWorkflows Boolean @default(false)

// Audit Logs
auditLogs AuditLog[] @relation("UserAuditLogs")

@@unique([email])
@@unique([email, username])
@@unique([username, organizationId])
Expand Down Expand Up @@ -546,6 +549,9 @@ model Team {
managedOrganizations ManagedOrganization[] @relation("ManagerOrganization")
filterSegments FilterSegment[]

// Audit logs
auditLogs AuditLog[]

@@unique([slug, parentId])
@@index([parentId])
}
Expand Down Expand Up @@ -2411,3 +2417,26 @@ model RolePermission {
// TODO: come back to this with indexs.
@@index([action])
}

model AuditLog {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())

// The organization/team this log belongs to.
teamId Int
team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)

// Who performed the action.
actorId Int
actor User @relation("UserAuditLogs", fields: [actorId], references: [id], onDelete: Cascade)

// What happened.
action String // e.g., "event_type.created", "booking.cancelled"
targetType String // e.g., "EventType", "Booking", "User"
targetId String
metadata Json // To store details like old/new values.

@@index([teamId])
@@index([actorId])
@@index([targetType, targetId])
}
20 changes: 20 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2532,6 +2532,7 @@ __metadata:
"@nestjs/common": ^10.0.0
"@nestjs/config": ^3.1.1
"@nestjs/core": ^10.0.0
"@nestjs/event-emitter": ^3.0.1
"@nestjs/jwt": ^10.2.0
"@nestjs/passport": ^10.0.2
"@nestjs/platform-express": ^10.0.0
Expand Down Expand Up @@ -8805,6 +8806,18 @@ __metadata:
languageName: node
linkType: hard

"@nestjs/event-emitter@npm:^3.0.1":
version: 3.0.1
resolution: "@nestjs/event-emitter@npm:3.0.1"
dependencies:
eventemitter2: 6.4.9
peerDependencies:
"@nestjs/common": ^10.0.0 || ^11.0.0
"@nestjs/core": ^10.0.0 || ^11.0.0
checksum: 9e916a3f983f37088d1b3cba3167b5b16032085b6949763cb14db604b259468c0aefe379d8911f4c8e1158c308fb761bd0ee8d08845f56d547cd649252637602
languageName: node
linkType: hard

"@nestjs/jwt@npm:^10.2.0":
version: 10.2.0
resolution: "@nestjs/jwt@npm:10.2.0"
Expand Down Expand Up @@ -26863,6 +26876,13 @@ __metadata:
languageName: node
linkType: hard

"eventemitter2@npm:6.4.9":
version: 6.4.9
resolution: "eventemitter2@npm:6.4.9"
checksum: be59577c1e1c35509c7ba0e2624335c35bbcfd9485b8a977384c6cc6759341ea1a98d3cb9dbaa5cea4fff9b687e504504e3f9c2cc1674cf3bd8a43a7c74ea3eb
languageName: node
linkType: hard

"eventemitter3@npm:^4.0.0, eventemitter3@npm:^4.0.1, eventemitter3@npm:^4.0.4":
version: 4.0.7
resolution: "eventemitter3@npm:4.0.7"
Expand Down
Loading