Skip to content

feat: add initial AuditLogService and /audit-logs API endpoint #22578

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

ParagGhatage
Copy link

What does this PR do?

This PR introduces the initial groundwork for an Audit Log system.

Changes Introduced:

  • Adds a utility function logEvent that logs actions/events to the Console (For now).
  • Adds a dummy getEvents function for future listing of audit events.
  • Introduced an AuditLogEvent interface with fields: id, orgId, teamId, userId, action, description, timestamp.

This setup will be expanded later to include:

  • Filters by team/org/user
  • Pagination and sorting
  • UI integration

Visual Demo

Since this is just a backend utility setup and there is no UI impact, no video/image is provided. Future commits will demonstrate visual changes (if any).

Overall flow:

graph TD
  A[User action: Renamed/Deleted/Booked/Cancelled] --> B(Event Emitter)
  B --> C{AuditLogService Interface}
  C -->|DB Storage| D[AuditLogDbImpl]
  C -->|3rd party| E[AuditLogExternalImpl]
  D & E --> F[Store/Send logs]
  F --> G[Audit log API endpoint]
  H[Optional: Telemetry service] --- F
Loading

Implementation till now:

graph TD
  E[EventEmitter emits event] --> A[AuditLogService]
  A --> T[Console logs event]
Loading

Mandatory Tasks (DO NOT REMOVE)

  • I have self-reviewed the code (A decent size PR without self-review might be rejected).
  • N/A
  • I confirm automated tests are in place that prove my fix is effective or that my feature works.

How should this be tested?

  • ✅ Confirm getEvents returns the dummy mocked data (for now).
  • ✅ Test event logging with dummy inputs like:
    logEvent({
      timestamp: "timeatamp",
      orgId: "team_456",
      userId: "user_789",
      action: "CANCEL",
      resource: "resources"
      details: "User logged in"
    })

Test Config

  • No new environment variables added.
  • No UI changes yet.

@ParagGhatage ParagGhatage requested review from a team as code owners July 17, 2025 06:21
Copy link

vercel bot commented Jul 17, 2025

@ParagGhatage is attempting to deploy a commit to the cal Team on Vercel.

A member of the Team first needs to authorize it.

@CLAassistant
Copy link

CLAassistant commented Jul 17, 2025

CLA assistant check
All committers have signed the CLA.

Copy link
Contributor

coderabbitai bot commented Jul 17, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes introduce a basic audit logging system for team or organization user activities. New type definitions for audit log actions and events are added. An AuditLogService provides asynchronous methods to log and retrieve audit events, currently implemented with console logging and a placeholder for retrieval. A helper function wraps the logging call. Two new API endpoints are created: one for posting new audit log events and one for retrieving them, with appropriate validation and error handling. An index route delegates GET and POST requests to these handlers using middleware.

Assessment against linked issues

Objective Addressed Explanation
Simple log that records all user activity of a team/org (1461)
Should be event-based (1461)
There should be a single endpoint for all events (1461)
Should use dependency injection pattern (1461) Service is instantiated as a constant, not injected or swappable.
Service should be swappable for a different implementation (e.g., third party) (1461) No abstraction/interface or injection mechanism for swapping service implementations is present.
Logs storage should be configurable (internal DB or external service) (1461) Storage is hardcoded to console log and not configurable.
Optionally could be tied to telemetry service (1461) No explicit integration or hooks for telemetry observed; unclear if intended for future implementation.

Assessment against linked issues: Out-of-scope changes

No out-of-scope functional code changes were found. All changes are directly related to implementing the audit logging functionality as described in the linked issue.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@graphite-app graphite-app bot added the community Created by Linear-GitHub Sync label Jul 17, 2025
@graphite-app graphite-app bot requested a review from a team July 17, 2025 06:21
@github-actions github-actions bot added 3 points Created by SyncLinear.com enterprise area: enterprise, audit log, organisation, SAML, SSO foundation Medium priority Created by Linear-GitHub Sync organizations area: organizations, orgs ✨ feature New feature or request 🎨 needs design Before engineering kick-off, a designer needs to submit a mockup 💎 Bounty A bounty on Algora.io 🚧 wip / in the making This is currently being worked on labels Jul 17, 2025
Copy link
Contributor

Hey there and thank you for opening this pull request! 👋🏼

We require pull request titles to follow the Conventional Commits specification and it looks like your proposed title needs to be adjusted.

Details:

No release type found in pull request title "add initial AuditLogService and /audit-logs API endpoint". Add a prefix to indicate what kind of release this pull request corresponds to. For reference, see https://www.conventionalcommits.org/

Available types:
 - feat: A new feature
 - fix: A bug fix
 - docs: Documentation only changes
 - style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
 - refactor: A code change that neither fixes a bug nor adds a feature
 - perf: A code change that improves performance
 - test: Adding missing tests or correcting existing tests
 - build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
 - ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
 - chore: Other changes that don't modify src or test files
 - revert: Reverts a previous commit

@dosubot dosubot bot added this to the v5.6 milestone Jul 17, 2025
@ParagGhatage ParagGhatage marked this pull request as draft July 17, 2025 06:24
Copy link

graphite-app bot commented Jul 17, 2025

Graphite Automations

"Add consumer team as reviewer" took an action on this PR • (07/17/25)

1 reviewer was added to this PR based on Keith Williams's automation.

"Add community label" took an action on this PR • (07/17/25)

1 label was added to this PR based on Keith Williams's automation.

@ParagGhatage ParagGhatage changed the title add initial AuditLogService and /audit-logs API endpoint feat: add initial AuditLogService and /audit-logs API endpoint Jul 17, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (6)
apps/api/v1/lib/audit-log.service.ts (1)

9-9: Fix typo in comment.

The comment contains a typo: "Expty" should be "Empty".

-    // Returning Expty array for now
+    // Returning Empty array for now
apps/api/v1/lib/helpers/audit-log.ts (1)

4-6: Consider function naming convention and utility.

The function name EmitAuditLogEvent uses PascalCase, which is typically reserved for classes/constructors in JavaScript/TypeScript. Consider using camelCase. Also, evaluate if this wrapper function adds sufficient value or if direct service calls would be more appropriate.

-export async function EmitAuditLogEvent(event: AuditLogEvent) {
+export async function emitAuditLogEvent(event: AuditLogEvent) {
   await AuditLogService.logEvent(event);
 }

Alternatively, consider whether this wrapper is necessary or if calling AuditLogService.logEvent directly would be more straightforward.

apps/api/v1/pages/api/audit-logs/_get.ts (2)

19-19: Remove unnecessary optional chaining.

The optional chaining operator (?.) is unnecessary since AuditLogService.getEvents is a defined method. This could indicate uncertainty about the API or be a remnant from development.

-    const events: AuditLogEvent[] = await AuditLogService.getEvents?.(filter);
+    const events: AuditLogEvent[] = await AuditLogService.getEvents(filter);

18-26: Consider more specific error handling.

While the current error handling is functional, you might consider logging the original error for debugging purposes while still providing a clean response to the client.

   try {
     const events: AuditLogEvent[] = await AuditLogService.getEvents(filter);
     return res.status(200).json({ events });
   } catch (error) {
+    console.error("Error fetching audit logs:", error);
     throw new HttpError({
       statusCode: 500,
       message: "Failed to fetch audit logs",
     });
   }
apps/api/v1/pages/api/audit-logs/_post.ts (1)

10-16: Consider more robust type validation.

While the current validation checks for object presence, consider adding more specific type validation for the request body to ensure it matches the expected structure more closely.

   const body = req.body as Partial<AuditLogEvent>;
-  if (!body || typeof body !== "object") {
+  if (!body || typeof body !== "object" || Array.isArray(body)) {
     throw new HttpError({
       statusCode: 400,
       message: "Invalid/Missing JSON body",
     });
   }
apps/api/v1/lib/types.ts (1)

149-150: Consider improving comment formatting and expanding action types.

The comment format should be consistent with the rest of the file. Also, consider if the current action types cover all necessary team audit scenarios.

-//Audit Logs for Teams
+// Audit Logs for Teams

Additionally, you might want to consider adding more specific actions like "EDIT", "INVITE", "REMOVE_MEMBER", etc., based on your team management requirements.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ec58e59 and e35a735.

📒 Files selected for processing (6)
  • apps/api/v1/lib/audit-log.service.ts (1 hunks)
  • apps/api/v1/lib/helpers/audit-log.ts (1 hunks)
  • apps/api/v1/lib/types.ts (1 hunks)
  • apps/api/v1/pages/api/audit-logs/_get.ts (1 hunks)
  • apps/api/v1/pages/api/audit-logs/_post.ts (1 hunks)
  • apps/api/v1/pages/api/audit-logs/index.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
apps/api/v1/lib/audit-log.service.ts (2)
packages/trpc/server/routers/publicViewer/procedures/event.ts (1)
  • event (8-12)
apps/api/v1/lib/types.ts (1)
  • AuditLogEvent (152-159)
apps/api/v1/pages/api/audit-logs/index.ts (2)
apps/api/v1/lib/helpers/withMiddleware.ts (1)
  • withMiddleware (54-54)
packages/lib/server/defaultHandler.ts (1)
  • defaultHandler (8-24)
apps/api/v1/lib/helpers/audit-log.ts (2)
apps/api/v1/lib/types.ts (1)
  • AuditLogEvent (152-159)
apps/api/v1/lib/audit-log.service.ts (1)
  • AuditLogService (3-12)
apps/api/v1/pages/api/audit-logs/_post.ts (3)
apps/api/v1/lib/types.ts (1)
  • AuditLogEvent (152-159)
apps/api/v1/lib/audit-log.service.ts (1)
  • AuditLogService (3-12)
packages/lib/server/defaultResponder.ts (1)
  • defaultResponder (11-42)
🪛 Biome (1.9.4)
apps/api/v1/pages/api/audit-logs/_post.ts

[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)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Install dependencies / Yarn install & cache
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Security Check
🔇 Additional comments (3)
apps/api/v1/pages/api/audit-logs/index.ts (1)

5-10: Clean API route implementation.

The implementation follows established patterns with proper middleware integration and HTTP method delegation. The structure is clean and maintainable.

apps/api/v1/pages/api/audit-logs/_get.ts (1)

12-16: Well-implemented query parameter filtering.

The type checking and filtering logic for query parameters is well-implemented, ensuring only string values are passed to the service while filtering out undefined values.

apps/api/v1/pages/api/audit-logs/_post.ts (1)

18-27: Well-implemented field validation.

The validation logic for required fields is thorough and provides clear error messages. The approach of iterating through required fields and checking each one is clean and maintainable.

Comment on lines +4 to +6
async logEvent(event: AuditLogEvent): Promise<void> {
console.log("Audit Log Event:", event);
},
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.

Comment on lines +8 to +11
async getEvents(filter?: any): Promise<AuditLogEvent[]> {
// Returning Expty array for now
return [];
},
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.

Comment on lines +4 to +6
export async function EmitAuditLogEvent(event: AuditLogEvent) {
await AuditLogService.logEvent(event);
}
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.

Comment on lines +29 to +34
try {
await AuditLogService.logEvent(body as AuditLogEvent);
return res.status(201).json({ ok: true });
} catch (error: unknown) {
throw error;
}
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 +152 to +159
export interface AuditLogEvent {
timestamp: string;
userId: string;
orgId: string;
action: AuditLogAction;
resource: string;
details: Record<string, any>;
}
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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (4)
apps/api/v1/lib/helpers/audit-log.ts (1)

4-6: Consider using camelCase for function names and add error handling documentation.

The function name EmitAuditLogEvent uses PascalCase, which is unconventional for function names in JavaScript/TypeScript. Consider renaming to emitAuditLogEvent to follow standard naming conventions.

Additionally, since this function doesn't handle errors from AuditLogService.logEvent, consider documenting that errors will propagate to the caller.

-export async function EmitAuditLogEvent(event: AuditLogEvent) {
+/**
+ * Emits an audit log event. Errors from the underlying service will propagate to the caller.
+ */
+export async function emitAuditLogEvent(event: AuditLogEvent) {
   await AuditLogService.logEvent(event);
 }
apps/api/v1/lib/audit-log.service.ts (1)

8-11: Fix typo in comment.

There's a typo in the comment on line 9.

-    // Returning Expty array for now
+    // Returning Empty array for now
apps/api/v1/pages/api/audit-logs/_get.ts (2)

19-19: Remove unnecessary optional chaining.

The optional chaining operator (?.) is unnecessary here since getEvents is a defined method on the AuditLogService object.

-    const events: AuditLogEvent[] = await AuditLogService.getEvents?.(filter);
+    const events: AuditLogEvent[] = await AuditLogService.getEvents(filter);

18-26: Consider improving error handling to preserve error details.

The current error handling catches all errors and throws a generic 500 error, which might mask important error details useful for debugging. Consider either removing the try-catch block to let defaultResponder handle errors, or preserving the original error details.

Option 1 - Remove try-catch and let defaultResponder handle errors:

-  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",
-    });
-  }
+  const events: AuditLogEvent[] = await AuditLogService.getEvents(filter);
+  return res.status(200).json({ events });

Option 2 - Preserve original error details:

   } catch (error) {
+    console.error("Failed to fetch audit logs:", error);
     throw new HttpError({
       statusCode: 500,
-      message: "Failed to fetch audit logs",
+      message: `Failed to fetch audit logs: ${error instanceof Error ? error.message : 'Unknown error'}`,
     });
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ec58e59 and e35a735.

📒 Files selected for processing (6)
  • apps/api/v1/lib/audit-log.service.ts (1 hunks)
  • apps/api/v1/lib/helpers/audit-log.ts (1 hunks)
  • apps/api/v1/lib/types.ts (1 hunks)
  • apps/api/v1/pages/api/audit-logs/_get.ts (1 hunks)
  • apps/api/v1/pages/api/audit-logs/_post.ts (1 hunks)
  • apps/api/v1/pages/api/audit-logs/index.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
apps/api/v1/pages/api/audit-logs/index.ts (2)
apps/api/v1/lib/helpers/withMiddleware.ts (1)
  • withMiddleware (54-54)
packages/lib/server/defaultHandler.ts (1)
  • defaultHandler (8-24)
apps/api/v1/lib/audit-log.service.ts (2)
packages/trpc/server/routers/publicViewer/procedures/event.ts (1)
  • event (8-12)
apps/api/v1/lib/types.ts (1)
  • AuditLogEvent (152-159)
apps/api/v1/pages/api/audit-logs/_get.ts (3)
apps/api/v1/lib/types.ts (1)
  • AuditLogEvent (152-159)
apps/api/v1/lib/audit-log.service.ts (1)
  • AuditLogService (3-12)
packages/lib/server/defaultResponder.ts (1)
  • defaultResponder (11-42)
🪛 Biome (1.9.4)
apps/api/v1/pages/api/audit-logs/_post.ts

[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)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Linters / lint
  • GitHub Check: Tests / Unit
  • GitHub Check: Type check / check-types
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Security Check
🔇 Additional comments (6)
apps/api/v1/pages/api/audit-logs/index.ts (1)

5-10: LGTM! Well-structured API route setup.

The implementation follows good practices:

  • Uses dynamic imports for code splitting
  • Separates concerns with middleware wrapper
  • Delegates to method-specific handlers
  • Leverages the existing defaultHandler pattern
apps/api/v1/lib/audit-log.service.ts (1)

4-6: LGTM! Appropriate placeholder implementation for initial development.

The console logging approach is suitable for the initial audit log system setup. This aligns with the PR objectives to establish the foundational components.

apps/api/v1/pages/api/audit-logs/_post.ts (2)

10-16: LGTM! Proper request body validation.

The validation correctly checks for the presence and type of the request body, with appropriate error handling using HTTP 400 status codes.


18-27: LGTM! Comprehensive field validation with clear error messages.

The dynamic field validation approach is maintainable and provides clear feedback about missing required fields.

apps/api/v1/pages/api/audit-logs/_get.ts (1)

10-16: LGTM! Proper query parameter handling.

The implementation correctly handles Next.js query parameters, which can be strings or arrays, and builds an appropriate filter object with type safety.

apps/api/v1/lib/types.ts (1)

150-150: LGTM! Well-defined audit action types.

The string literal union type provides good type safety and covers the essential actions for a calendar/booking system audit log.

Comment on lines +29 to +35
try {
await AuditLogService.logEvent(body as AuditLogEvent);
return res.status(201).json({ ok: true });
} catch (error: unknown) {
throw error;
}
}
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.

Comment on lines +152 to +159
export interface AuditLogEvent {
timestamp: string;
userId: string;
orgId: string;
action: AuditLogAction;
resource: string;
details: Record<string, any>;
}
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.

@ParagGhatage ParagGhatage force-pushed the feat/audit-logs branch 2 times, most recently from 17027df to f3c7256 Compare July 18, 2025 10:17
@github-actions github-actions bot added the ❗️ migrations contains migration files label Jul 18, 2025
@ParagGhatage ParagGhatage force-pushed the feat/audit-logs branch 2 times, most recently from 5cc3e5d to 7d2b2af Compare July 25, 2025 00:28
Copy link
Contributor

This PR is being marked as stale due to inactivity.

@github-actions github-actions bot added the Stale label Aug 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3 points Created by SyncLinear.com 💎 Bounty A bounty on Algora.io community Created by Linear-GitHub Sync enterprise area: enterprise, audit log, organisation, SAML, SSO ✨ feature New feature or request foundation Medium priority Created by Linear-GitHub Sync ❗️ migrations contains migration files 🎨 needs design Before engineering kick-off, a designer needs to submit a mockup organizations area: organizations, orgs Stale 🚧 wip / in the making This is currently being worked on
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[CAL-1710] Audit log
2 participants