Skip to content
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

[Fix] Activity Log Event use generic method #8449

Merged
merged 9 commits into from
Oct 17, 2024

Conversation

GloireMutaliko21
Copy link
Contributor

@GloireMutaliko21 GloireMutaliko21 commented Oct 17, 2024

PR

Please note: we will close your PR without comment if you do not check the boxes above and provide ALL requested information.


Summary by CodeRabbit

  • New Features

    • Enhanced activity logging functionality with new methods for logging entity creation and updates.
    • Introduced a method to generate formatted activity log descriptions based on action types.
  • Bug Fixes

    • Improved error handling in the TaskViewService.
  • Refactor

    • Updated methods across multiple services to utilize new logging functions, simplifying the codebase.
    • Changed method names and signatures for improved clarity.
    • Streamlined logging processes in various services by integrating ActivityLogService directly.
  • Documentation

    • Updated method signatures for clarity and consistency across services.

Copy link
Contributor

coderabbitai bot commented Oct 17, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes in this pull request focus on enhancing activity logging across various services in the application. Key updates include the introduction of two new functions, activityLogCreateAction and activityLogUpdateAction, to streamline logging operations. Several existing methods have been refactored to utilize these new functions, improving the clarity and efficiency of activity log generation. Additionally, some method signatures have been updated for consistency and clarity, and the ActivityLogModule has been made global for easier access.

Changes

File Path Change Summary
packages/core/src/activity-log/activity-log.helper.ts - Added imports for EventBus, ActorTypeEnum, ID, and ActivityLogEvent.
- Renamed parameter original to originalValues in activityLogUpdatedFieldsAndValues.
- Added generateActivityLogDescription, activityLogCreateAction, and activityLogUpdateAction functions.
packages/core/src/activity-log/activity-log.module.ts - Updated ActivityLogModule with @Global() decorator for global accessibility.
packages/core/src/activity-log/activity-log.service.ts - Added imports for enums and EventBus.
- Renamed logActivity to create and added new logActivity method for flexible logging.
packages/core/src/activity-log/events/handlers/activity-log.handler.ts - Updated handle method to call this.activityLogService.create(event.input).
packages/core/src/organization-project-module/organization-project-module.service.ts - Updated create and update methods to use logActivity for activity logging.
packages/core/src/organization-sprint/organization-sprint.service.ts - Updated create and update methods to use logActivity for activity logging.
packages/core/src/resource-link/resource-link.service.ts - Removed previous logging method and updated to use logActivity for activity logging.
packages/core/src/tasks/commands/handlers/automation-task.sync.handler.ts - Added ActivityLogService and updated createTask and updateTask methods to include logging.
packages/core/src/tasks/task.service.ts - Updated update method to use logActivity and explicitly return the updated task.
packages/core/src/tasks/views/view.service.ts - Added NotFoundException import and updated logging in create and update methods.

Possibly related PRs

Suggested reviewers

  • rahul-rocket

Poem

🐇 In the meadow where logs do play,
Activity dances, come what may.
With actions logged both new and bright,
Our code hops forward, a joyful sight!
So let us cheer for each new line,
A log of actions, simply divine! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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 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.

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: 4

🧹 Outside diff range and nitpick comments (6)
packages/core/src/tasks/commands/handlers/task-create.handler.ts (1)

81-81: Address TODO comment regarding actor type.

The TODO comment indicates that the actor type needs to be reviewed to account for GitHub Integration. Consider implementing a mechanism to determine the correct actor type (User or System) based on the context of the task creation.

Would you like assistance in implementing a solution to handle both User and System actor types?

packages/core/src/tasks/views/view.service.ts (2)

47-55: Add Error Handling for Activity Log Creation

If activityLogCreateAction fails, it could cause unhandled errors. Consider adding error handling to prevent exceptions from interrupting the operation.

Suggested addition:

try {
    // Generate the activity log
    activityLogCreateAction(
        this._eventBus,
        BaseEntityEnum.TaskView,
        view.name,
        ActorTypeEnum.User,
        organizationId,
        tenantId,
        view
    );
} catch (error) {
    // Handle or log the error as needed
    console.error('Failed to create activity log:', error);
}

91-102: Add Error Handling for Activity Log Update

Similarly, wrap activityLogUpdateAction in a try-catch block to handle potential errors during the logging process.

Suggested addition:

try {
    // Generate the activity log
    const { organizationId } = updatedTaskView;
    activityLogUpdateAction(
        this._eventBus,
        BaseEntityEnum.TaskView,
        updatedTaskView.name,
        ActorTypeEnum.User,
        organizationId,
        tenantId,
        existingView,
        input,
        updatedTaskView
    );
} catch (error) {
    // Handle or log the error as needed
    console.error('Failed to update activity log:', error);
}
packages/core/src/tasks/commands/handlers/automation-task.sync.handler.ts (1)

148-157: Consider Using Consistent Sources for organizationId and tenantId

In the createTask method, you're destructuring organizationId and tenantId from createdTask. To ensure consistency and avoid potential issues if these properties are undefined on createdTask, consider using options.organizationId and options.tenantId, which are already available.

packages/core/src/organization-sprint/organization-sprint.service.ts (1)

Line range hint 151-193: Ensure the organization sprint updates when member IDs are empty

In the update method, the current logic only updates the organization sprint if memberIds or managerIds are provided. If both arrays are empty, the sprint's other properties from input will not be updated, and the activity log will not be generated. This could lead to updates being ignored when only sprint details (like name, status, etc.) are changed without modifying members.

Consider restructuring the code to ensure that the sprint updates occur regardless of whether memberIds or managerIds are provided. Here's a suggested refactor:

 try {
     // Search for existing Organization Sprint
     const organizationSprint = await super.findOneByIdString(id, {
         where: { organizationId, tenantId, projectId },
         relations: {
             members: true,
             modules: true
         }
     });

-    // Retrieve members and managers IDs
     if (isNotEmpty(memberIds) || isNotEmpty(managerIds)) {
         // Combine memberIds and managerIds into a single array
         const employeeIds = [...memberIds, ...managerIds].filter(Boolean);

         // Retrieve a collection of employees based on specified criteria.
         const sprintMembers = await this._employeeService.findActiveEmployeesByEmployeeIds(
             employeeIds,
             organizationId,
             tenantId
         );

         // Update nested entity (Organization Sprint Members)
         await this.updateOrganizationSprintMembers(id, organizationId, sprintMembers, managerIds, memberIds);
     }

+    // Update the organization sprint with the provided input
+    const { id: organizationSprintId } = organizationSprint;
+    const updatedSprint = await super.create({
+        ...input,
+        organizationId,
+        tenantId,
+        id: organizationSprintId
+    });

+    // Generate the activity log
+    activityLogUpdateAction(
+        this._eventBus,
+        BaseEntityEnum.OrganizationSprint,
+        updatedSprint.name,
+        ActorTypeEnum.User,
+        organizationId,
+        tenantId,
+        organizationSprint,
+        input,
+        updatedSprint
+    );

     // Return the updated sprint
     return updatedSprint;
 } catch (error) {
     // Handle errors and return an appropriate error response
     throw new HttpException(`Failed to update organization sprint: ${error.message}`, HttpStatus.BAD_REQUEST);
 }

This refactor ensures that the sprint is updated and the activity log is generated even when there are no changes to the members.

packages/core/src/tasks/task.service.ts (1)

102-114: Address the TODO: Handle 'System' actor type for GitHub integration

As noted in the TODO comment on line 108, since there is GitHub integration, consider implementing logic to set the actor type to ActorTypeEnum.System when actions are performed by the system via GitHub. This ensures accurate logging of the actor responsible for the action.

Would you like assistance in implementing this functionality or opening a new GitHub issue to track this task?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2975fe6 and 290f558.

📒 Files selected for processing (8)
  • packages/core/src/activity-log/activity-log.helper.ts (2 hunks)
  • packages/core/src/organization-project-module/organization-project-module.service.ts (3 hunks)
  • packages/core/src/organization-sprint/organization-sprint.service.ts (4 hunks)
  • packages/core/src/resource-link/resource-link.service.ts (3 hunks)
  • packages/core/src/tasks/commands/handlers/automation-task.sync.handler.ts (5 hunks)
  • packages/core/src/tasks/commands/handlers/task-create.handler.ts (2 hunks)
  • packages/core/src/tasks/task.service.ts (2 hunks)
  • packages/core/src/tasks/views/view.service.ts (4 hunks)
🧰 Additional context used
🔇 Additional comments (21)
packages/core/src/tasks/commands/handlers/task-create.handler.ts (2)

3-4: LGTM: Import changes are appropriate.

The new imports for BaseEntityEnum, ActorTypeEnum, ITask, and activityLogCreateAction are correctly added and align with the changes in the execute method. The import paths are consistent with the project structure.


76-84: LGTM: Activity log generation simplified.

The new implementation using activityLogCreateAction simplifies the activity log creation process. It consolidates the logging functionality into a single method call, improving code clarity and maintainability.

packages/core/src/organization-project-module/organization-project-module.service.ts (4)

20-20: LGTM: Import changes for activity logging.

The import of activityLogCreateAction and activityLogUpdateAction functions suggests a good refactoring of the activity logging process. This change likely improves code organization and reusability.


52-60: LGTM: Refactored activity logging in create method.

The implementation of activity logging has been improved by using the activityLogCreateAction helper function. This change enhances code readability and maintainability by centralizing the logging logic.


101-112: LGTM: Refactored activity logging in update method.

The activity logging in the update method has been improved using the activityLogUpdateAction helper function. This change is consistent with the modifications in the create method and enhances the overall code quality.


Line range hint 1-424: Overall LGTM: Improved activity logging implementation.

The changes in this file consistently enhance the activity logging process across the OrganizationProjectModuleService. By introducing and utilizing the activityLogCreateAction and activityLogUpdateAction helper functions, the code becomes more maintainable and consistent. This refactoring likely improves the overall quality of the codebase and aligns with best practices for logging and event tracking.

packages/core/src/resource-link/resource-link.service.ts (3)

14-14: Importing activity log helper functions

The import statement correctly adds activityLogCreateAction and activityLogUpdateAction from '../activity-log/activity-log.helper', which are used for logging activities in the create and update methods.


56-64: Proper usage of activityLogCreateAction in create method

The activityLogCreateAction function is appropriately called to log the creation of a new resource link. All necessary parameters are provided, ensuring consistent activity logging.


93-104: Correct implementation of activityLogUpdateAction in update method

The activityLogUpdateAction function is correctly used to log updates to resource links. The destructuring of organizationId and tenantId from updatedResourceLink, as well as the parameters passed to the function, are appropriate.

packages/core/src/tasks/views/view.service.ts (4)

2-2: Appropriate Import of Exception Classes

The addition of BadRequestException, HttpException, HttpStatus, and Injectable from @nestjs/common is necessary for error handling and dependency injection in the service class.


15-15: Importing Activity Log Helper Functions

The import of activityLogCreateAction and activityLogUpdateAction from ../../activity-log/activity-log.helper is appropriate and required for logging activities in the create and update methods.


47-55: Ensure Correct Parameters in activityLogCreateAction

The usage of activityLogCreateAction appears correct. However, please verify that the parameters passed align with the function's expected signature to ensure accurate logging.

If needed, refer to the activityLogCreateAction definition to confirm the parameter order and types.


91-102: Ensure Correct Parameters in activityLogUpdateAction

Please verify that the parameters passed to activityLogUpdateAction match the function's expected signature to ensure accurate logging of the update action.

Confirm that:

  • existingView, input, and updatedTaskView are correctly placed.
  • All necessary parameters are included and correctly ordered.
packages/core/src/activity-log/activity-log.helper.ts (2)

78-105: Well-Implemented Activity Log Creation

The activityLogCreateAction function is well-structured and correctly emits the ActivityLogEvent with all necessary details. This enhances the clarity and consistency of activity logging.


120-156: Effective Activity Log for Updates

The activityLogUpdateAction function appropriately handles updated entities by logging the changed fields and their values. The use of activityLogUpdatedFieldsAndValues ensures that all modifications are accurately recorded.

packages/core/src/tasks/commands/handlers/automation-task.sync.handler.ts (2)

35-37: EventBus Dependency Successfully Injected

The EventBus has been correctly injected into the constructor, enabling the dispatch of events within the handler.


188-199: Verify organizationId and tenantId Values in updateTask

In the updateTask method, you're extracting organizationId and tenantId from updatedTask. Ensure that these properties are reliably present after the update operation. If there's a risk they might be undefined, consider using the values from existingTask or ensure they are correctly set in the entity before merging.

packages/core/src/organization-sprint/organization-sprint.service.ts (3)

19-19: Importing activity log helpers

The import statement correctly adds activityLogCreateAction and activityLogUpdateAction from '../activity-log/activity-log.helper', which are necessary for activity logging.


183-193: Verify parameters in activityLogUpdateAction

In the update method, the activityLogUpdateAction function is called to log updates to the organization sprint. Please confirm that the parameters—especially organizationSprint, input, and updatedSprint—are correctly ordered and appropriate for this function.

You can use the following script to check the function definition and verify parameter usage:

#!/bin/bash
# Description: Verify the parameter order of activityLogUpdateAction

# Search for the function definition of activityLogUpdateAction
rg --type typescript -A 10 -B 2 "function activityLogUpdateAction"

116-124: Ensure correct parameters in activityLogCreateAction

In the create method, the activityLogCreateAction function is used to generate an activity log. Please verify that the parameters passed to this function match its expected signature and order.

To confirm the correctness of the parameters, you can run the following script:

✅ Verification successful

Parameters in activityLogCreateAction are correctly ordered and match the expected signature.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the parameter order of activityLogCreateAction

# Search for the function definition of activityLogCreateAction
rg --type typescript -A 5 -B 2 "function activityLogCreateAction"

Length of output: 103


Script:

#!/bin/bash
# Description: Verify the parameter order of activityLogCreateAction

# Search for the function definition of activityLogCreateAction in .ts and .tsx files
rg --files | rg '\.ts$|\.tsx$' | xargs rg "function activityLogCreateAction"

Length of output: 499


Script:

#!/bin/bash
# Description: Extract the complete function definition of activityLogCreateAction

# Extract lines starting from the function definition, capturing the full parameter list
rg "export function activityLogCreateAction" packages/core/src/activity-log/activity-log.helper.ts -A 10

Length of output: 436

packages/core/src/tasks/task.service.ts (1)

31-31: Import statement for 'activityLogUpdateAction'

The import of activityLogUpdateAction from '../activity-log/activity-log.helper' is appropriate and necessary for the added activity logging functionality.

Comment on lines +48 to +59
export function activityLogUpdatedFieldsAndValues<T>(originalValues: T, updated: Partial<T>) {
const updatedFields: string[] = [];
const previousValues: IActivityLogUpdatedValues[] = [];
const updatedValues: IActivityLogUpdatedValues[] = [];

for (const key of Object.keys(updated)) {
if (original[key] !== updated[key]) {
if (originalValues[key] !== updated[key]) {
// Add updated field
updatedFields.push(key);

// Add old and new values
previousValues.push({ [key]: original[key] });
previousValues.push({ [key]: originalValues[key] });
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

Ensure Deep Comparison for Accurate Change Detection

In the activityLogUpdatedFieldsAndValues function, the equality check originalValues[key] !== updated[key] uses shallow comparison. This may not accurately detect changes in nested objects or arrays because it compares references rather than their contents. Consider using a deep equality check to ensure all changes are captured.

Apply this diff to use deep equality comparison:

+import { isEqual } from 'lodash';

 // ...

 for (const key of Object.keys(updated)) {
-	if (originalValues[key] !== updated[key]) {
+	if (!isEqual(originalValues[key], updated[key])) {
 		// Add updated field
 		updatedFields.push(key);

 		// Add old and new values
 		previousValues.push({ [key]: originalValues[key] });
 		updatedValues.push({ [key]: updated[key] });
 	}
 }
📝 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 function activityLogUpdatedFieldsAndValues<T>(originalValues: T, updated: Partial<T>) {
const updatedFields: string[] = [];
const previousValues: IActivityLogUpdatedValues[] = [];
const updatedValues: IActivityLogUpdatedValues[] = [];
for (const key of Object.keys(updated)) {
if (original[key] !== updated[key]) {
if (originalValues[key] !== updated[key]) {
// Add updated field
updatedFields.push(key);
// Add old and new values
previousValues.push({ [key]: original[key] });
previousValues.push({ [key]: originalValues[key] });
import { isEqual } from 'lodash';
export function activityLogUpdatedFieldsAndValues<T>(originalValues: T, updated: Partial<T>) {
const updatedFields: string[] = [];
const previousValues: IActivityLogUpdatedValues[] = [];
const updatedValues: IActivityLogUpdatedValues[] = [];
for (const key of Object.keys(updated)) {
if (!isEqual(originalValues[key], updated[key])) {
// Add updated field
updatedFields.push(key);
// Add old and new values
previousValues.push({ [key]: originalValues[key] });
updatedValues.push({ [key]: updated[key] });
}
}

Copy link

nx-cloud bot commented Oct 17, 2024

☁️ Nx Cloud Report

CI is running/has finished running commands for commit ec297ab. As they complete they will appear below. Click to see the status, the terminal output, and the build insights.

📂 See all runs for this CI Pipeline Execution


🟥 Failed Commands
nx build gauzy -c=production --prod --verbose
nx build desktop --prod --base-href ./
✅ Successfully ran 1 target

Sent with 💌 from NxCloud.

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: 4

🧹 Outside diff range and nitpick comments (3)
packages/core/src/tasks/commands/handlers/automation-task.sync.handler.ts (2)

147-160: LGTM: Activity logging for task creation is well-implemented.

The activity logging for task creation is correctly placed and includes all relevant information. However, consider wrapping the logging call in a try-catch block to prevent any potential errors in logging from affecting the task creation process.

Consider adding error handling:

 // Activity Log Task Creation
 const { organizationId, tenantId } = createdTask;
-this.activityLogService.logActivity(
-  BaseEntityEnum.Task,
-  createdTask.title,
-  ActorTypeEnum.System,
-  organizationId,
-  tenantId,
-  ActionTypeEnum.Created,
-  createdTask
-);
+try {
+  await this.activityLogService.logActivity(
+    BaseEntityEnum.Task,
+    createdTask.title,
+    ActorTypeEnum.System,
+    organizationId,
+    tenantId,
+    ActionTypeEnum.Created,
+    createdTask
+  );
+} catch (error) {
+  console.error('Failed to log task creation activity:', error);
+}

188-203: LGTM: Activity logging for task update is well-implemented.

The activity logging for task update is correctly placed and includes all relevant information, including the existing task and new entity data for change tracking. As with the create method, consider wrapping the logging call in a try-catch block for error handling.

Consider adding error handling:

 // Activity Log Task Update
 const { organizationId, tenantId } = updatedTask;
-this.activityLogService.logActivity(
-  BaseEntityEnum.Task,
-  updatedTask.title,
-  ActorTypeEnum.System,
-  organizationId,
-  tenantId,
-  ActionTypeEnum.Updated,
-  updatedTask,
-  existingTask,
-  entity
-);
+try {
+  await this.activityLogService.logActivity(
+    BaseEntityEnum.Task,
+    updatedTask.title,
+    ActorTypeEnum.System,
+    organizationId,
+    tenantId,
+    ActionTypeEnum.Updated,
+    updatedTask,
+    existingTask,
+    entity
+  );
+} catch (error) {
+  console.error('Failed to log task update activity:', error);
+}
packages/core/src/tasks/task.service.ts (1)

102-116: Address the TODO regarding ActorTypeEnum in activity logging

There's a TODO comment indicating the need to handle the ActorTypeEnum for GitHub Integration in the logActivity method call. Specifically, to accommodate scenarios where the actor might be 'System' instead of 'User'. Consider updating the ActorTypeEnum or the logic to support system-generated events.

Would you like assistance in implementing this functionality or should we open a GitHub issue to track this task?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 290f558 and 6eca1d2.

📒 Files selected for processing (10)
  • packages/core/src/activity-log/activity-log.module.ts (2 hunks)
  • packages/core/src/activity-log/activity-log.service.ts (4 hunks)
  • packages/core/src/activity-log/events/handlers/activity-log.handler.ts (1 hunks)
  • packages/core/src/organization-project-module/organization-project-module.service.ts (4 hunks)
  • packages/core/src/organization-project/organization-project.service.ts (3 hunks)
  • packages/core/src/organization-sprint/organization-sprint.service.ts (5 hunks)
  • packages/core/src/resource-link/resource-link.service.ts (4 hunks)
  • packages/core/src/tasks/commands/handlers/automation-task.sync.handler.ts (4 hunks)
  • packages/core/src/tasks/task.service.ts (3 hunks)
  • packages/core/src/tasks/views/view.service.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/core/src/organization-project-module/organization-project-module.service.ts
  • packages/core/src/organization-sprint/organization-sprint.service.ts
  • packages/core/src/resource-link/resource-link.service.ts
  • packages/core/src/tasks/views/view.service.ts
🧰 Additional context used
🔇 Additional comments (13)
packages/core/src/activity-log/events/handlers/activity-log.handler.ts (1)

18-18: LGTM! Consider verifying method name change impact.

The change from logActivity to create is a good improvement in naming convention and aligns well with standard CRUD operations. The explicit return of the created log entry is also beneficial, as it allows for potential error handling or further processing by the caller.

To ensure this change doesn't introduce any issues, please verify that all calls to logActivity have been updated to create throughout the codebase. You can use the following script to check for any remaining occurrences of logActivity:

If any occurrences are found, they should be updated to use the new create method.

packages/core/src/activity-log/activity-log.module.ts (2)

2-2: LGTM: ActivityLogModule is now globally available.

The changes to import and use the @Global() decorator are correct and will make the ActivityLogModule globally available throughout the application. This can simplify its usage in other modules.

Also applies to: 12-12


Line range hint 1-24: Verify the necessity of global scope for ActivityLogModule.

While making the module global can simplify its usage, it's important to ensure this is the intended behavior. Global modules can potentially make dependencies less explicit and affect maintainability.

Please run the following script to analyze the usage of ActivityLogModule across the application:

Based on the results, we can determine if the global scope is necessary or if it might be better to keep the module's scope more limited.

✅ Verification successful

Global Scope Confirmation

Based on the analysis, ActivityLogModule is appropriately set as a global module to provide ActivityLogService across the application without requiring explicit imports in every consuming module.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Analyze the usage of ActivityLogModule across the application

# Test 1: Check for explicit imports of ActivityLogModule
echo "Explicit imports of ActivityLogModule:"
rg --type typescript "import.*ActivityLogModule" --glob "!**/activity-log.module.ts"

# Test 2: Check for usage of ActivityLog entity or service
echo "\nUsage of ActivityLog entity or service:"
rg --type typescript "ActivityLog[^M]" --glob "!**/activity-log*"

# Test 3: Check for any remaining imports from the activity-log module
echo "\nOther imports from activity-log module:"
rg --type typescript "from ['\"].*activity-log" --glob "!**/activity-log*"

Length of output: 611


Script:

#!/bin/bash
# Description: Re-analyze the usage of ActivityLogModule across the application with corrected file type

# Test 1: Check for explicit imports of ActivityLogModule
echo "Explicit imports of ActivityLogModule:"
rg --type ts "import.*ActivityLogModule" --glob "!**/activity-log.module.ts"

# Test 2: Check for usage of ActivityLog entity or service
echo "\nUsage of ActivityLog entity or service:"
rg --type ts "ActivityLog[^M]" --glob "!**/activity-log*"

# Test 3: Check for any remaining imports from the activity-log module
echo "\nOther imports from activity-log module:"
rg --type ts "from ['\"].*activity-log" --glob "!**/activity-log*"

Length of output: 5114

packages/core/src/tasks/commands/handlers/automation-task.sync.handler.ts (2)

4-13: LGTM: Import statements and constructor changes are appropriate.

The new imports and the addition of ActivityLogService to the constructor are consistent with the implementation of activity logging functionality. This change follows good dependency injection practices.

Also applies to: 18-18, 36-38


Line range hint 1-210: Overall changes look good, consider updating tests.

The addition of activity logging in the AutomationTaskSyncHandler class enhances the traceability of task-related actions. The implementation is consistent for both create and update operations. However, it's important to ensure that the test suite is updated to cover this new functionality.

Please verify that the test suite has been updated to cover the new activity logging functionality. Run the following script to check for test files related to this handler:

If no results are found for the second command, consider updating the test files to include coverage for the new activity logging functionality.

packages/core/src/organization-project/organization-project.service.ts (4)

25-25: LGTM: Import statement added correctly.

The import for ActivityLogService is properly placed and aligns with the changes made in the class.


48-48: LGTM: Constructor updated to use ActivityLogService.

The constructor parameter has been correctly updated to use ActivityLogService instead of EventBus, maintaining consistent naming conventions.


125-133: LGTM: Activity logging updated to use ActivityLogService.

The implementation for logging activity has been successfully updated to use the ActivityLogService. This change provides a more direct method of logging and is consistent with the removal of EventBus. All necessary parameters are correctly passed to the logActivity method.


Line range hint 1-693: Overall assessment: Changes improve activity logging mechanism.

The modifications in this file successfully replace the EventBus with ActivityLogService for logging activities. The changes are consistent throughout the file and align with the PR objectives. The new implementation provides a more direct and potentially more efficient way of logging activities for organization projects.

packages/core/src/activity-log/activity-log.service.ts (1)

Line range hint 82-90: Verify the correctness of pagination 'skip' calculation

The calculation of the skip value for pagination starts from 1:

const skip = filters.skip && Number.isInteger(filters.skip) && filters.skip > 0 ? filters.skip : 1;

And then calculates the offset:

skip: take * (skip - 1) // Calculate offset (skip) based on validated skip value

Since TypeORM uses zero-based indexing for the skip option, starting skip from 1 may lead to confusion or unintended behavior. Consider adjusting the logic to ensure accurate pagination and that no records are unintentionally skipped.

packages/core/src/tasks/task.service.ts (3)

24-25: Imports are appropriate

The addition of PermissionsEnum and ActionTypeEnum to the imports ensures that the necessary enums are available for use in the code.


32-32: Correctly imported ActivityLogService

The import statement for ActivityLogService is correctly added, allowing access to activity logging functionalities.


47-47: ActivityLogService injected into the constructor

Injecting ActivityLogService into the constructor ensures that activity logging methods are available throughout the TaskService.

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: 1

🧹 Outside diff range and nitpick comments (2)
packages/core/src/tasks/views/view.service.ts (1)

47-58: LGTM: Improved activity logging implementation.

The use of ActivityLogService.logActivity is a good improvement. It provides a more direct and type-safe approach to logging activities.

Consider extracting the activity log parameters into a separate object for better readability:

this.activityLogService.logActivity({
  entityType: BaseEntityEnum.TaskView,
  entityName: view.name,
  actorType: ActorTypeEnum.User,
  organizationId,
  tenantId,
  action: ActionTypeEnum.Created,
  data: view
});
packages/core/src/activity-log/activity-log.service.ts (1)

117-169: LGTM: New logActivity method enhances logging capabilities.

The new logActivity method is a well-structured and flexible approach to handling activity logging for various entity types and actions. The use of EventBus for publishing ActivityLogEvent aligns well with event-driven architecture principles.

Minor suggestion for improvement:
Consider adding a return type annotation to the method for better code clarity. If the method doesn't return anything, you can explicitly set it to void.

logActivity<T>(
  // ... parameters ...
): void {
  // ... method body ...
}

This change would enhance the method's type safety and readability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 045a18a and e05b37f.

📒 Files selected for processing (2)
  • packages/core/src/activity-log/activity-log.service.ts (4 hunks)
  • packages/core/src/tasks/views/view.service.ts (5 hunks)
🧰 Additional context used
🔇 Additional comments (7)
packages/core/src/tasks/views/view.service.ts (3)

1-1: LGTM: Import and constructor changes are appropriate.

The changes in the import statements and constructor align well with the shift from EventBus to ActivityLogService for activity logging. The addition of NotFoundException import is also beneficial for improved error handling.

Also applies to: 15-15, 29-29


70-71: LGTM: Updated method comments.

The comments have been appropriately updated to reflect the use of NotFoundException for better error handling.


Line range hint 1-116: Overall improvements with one critical issue to address.

This PR introduces significant improvements to the TaskViewService:

  1. Enhanced activity logging using ActivityLogService.
  2. Improved error handling with the use of NotFoundException.
  3. More consistent and type-safe approach to logging activities.

However, there's a critical issue in the update method that needs to be addressed:

  • The method is using super.create instead of super.update, which may lead to unexpected behavior.

Please address the issues raised in the individual comments, particularly the update logic in the update method. Once these are resolved, the changes will significantly enhance the robustness and maintainability of the TaskViewService.

packages/core/src/activity-log/activity-log.service.ts (4)

3-11: LGTM: New imports added for enhanced functionality.

The new imports for enums (ActionTypeEnum, ActorTypeEnum, BaseEntityEnum) and EventBus from @nestjs/cqrs are appropriate for the new event-driven logging functionality implemented in this service.

Also applies to: 18-20


26-27: LGTM: Constructor updated to include EventBus.

The addition of the _eventBus parameter in the constructor is appropriate for implementing the new event-driven logging functionality.


82-82: LGTM: Improved skip value calculation for pagination.

The adjustment to the skip value calculation ensures that it's a positive integer starting from 1, which is a good practice for pagination. This change improves the robustness of the findActivityLogs method.


Line range hint 106-114: Method renamed for clarity, but error handling concerns remain.

The renaming of logActivity to create improves the clarity of the method's purpose. However, the previously raised concerns about error handling are still valid:

  1. Consider using console.error instead of console.log for error logging.
  2. Consider throwing a more appropriate exception, such as InternalServerErrorException, instead of BadRequestException for server-side errors.

Please address these concerns to improve the robustness of the error handling in this method.

Comment on lines 79 to 102
// Retrieve existing view.
const existingView = await this.findOneByIdString(id);

if (!existingView) {
throw new NotFoundException('View not found');
}

const updatedTaskView = await super.create({
...input,
tenantId,
id
});

// Generate the activity log description.
const description = generateActivityLogDescription(
ActionTypeEnum.Updated,
// Generate the activity log
const { organizationId } = updatedTaskView;
this.activityLogService.logActivity(
BaseEntityEnum.TaskView,
updatedTaskView.name
);

// Compare values before and after update then add updates to fields
const { updatedFields, previousValues, updatedValues } = activityLogUpdatedFieldsAndValues(
updatedTaskView.name,
ActorTypeEnum.User,
organizationId,
tenantId,
ActionTypeEnum.Updated,
updatedTaskView,
existingView,
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

Improved error handling and logging, but update logic needs revision.

The addition of the existence check and use of NotFoundException is a good improvement in error handling. The activity logging changes are also consistent with the create method.

However, there's a critical issue in the update logic:

The method is using super.create instead of super.update. This may lead to unexpected behavior, potentially creating a new record instead of updating the existing one. Please modify the code as follows:

const updatedTaskView = await super.update(id, {
  ...input,
  tenantId
});

Consider extracting the activity log parameters into a separate object for better readability, similar to the suggestion for the create method.

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: 0

🧹 Outside diff range and nitpick comments (3)
packages/core/src/tasks/task.service.ts (3)

102-115: LGTM: Improved activity logging in update method

The refactoring of the update method to use the centralized ActivityLogService is a good improvement. It simplifies the code and promotes consistency in activity logging across the application.

However, I have a minor suggestion:

Consider extracting the activity logging call into a separate private method within the TaskService class. This would further improve readability and make it easier to reuse the logging logic if needed in other methods. For example:

private logTaskActivity(task: Task, action: ActionTypeEnum, oldTask?: Task, input?: Partial<ITaskUpdateInput>) {
  const { organizationId, tenantId } = task;
  this.activityLogService.logActivity<Task>(
    BaseEntityEnum.Task,
    task.title,
    task.id,
    ActorTypeEnum.User,
    organizationId,
    tenantId,
    action,
    task,
    oldTask,
    input
  );
}

Then in the update method, you could simply call:

this.logTaskActivity(updatedTask, ActionTypeEnum.Updated, task, input);

This approach would make the update method even cleaner and more focused on its primary responsibility.


Line range hint 119-122: Enhance error handling in update method

The use of HttpException with detailed error information is good for debugging purposes. However, it's important to ensure that sensitive information is not exposed in production environments.

Consider implementing a custom error handling strategy that logs detailed errors for internal use but returns sanitized error messages to the client. For example:

} catch (error) {
  console.error(`Error while updating task: ${error.message}`, error);
  throw new HttpException(
    { message: 'An error occurred while updating the task' },
    HttpStatus.BAD_REQUEST
  );
}

This approach would log the full error details for debugging while providing a generic error message to the client, enhancing security and maintaining a consistent API response structure.


Line range hint 1-1023: Overall assessment of TaskService changes

The primary focus of this update was to improve the activity logging mechanism in the TaskService, particularly in the update method. The integration of ActivityLogService and the refactoring of the update method contribute to a more centralized and consistent approach to activity logging.

These changes are likely to improve the maintainability of the code and provide better insights into task-related activities. The rest of the TaskService remains largely unchanged, which helps maintain stability in other areas of the service.

As the application evolves, consider applying similar activity logging patterns to other methods in the TaskService where appropriate. This would ensure consistency across all task-related operations and provide a comprehensive activity trail for auditing and debugging purposes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e05b37f and 09f5e1d.

📒 Files selected for processing (9)
  • packages/core/src/activity-log/activity-log.service.ts (4 hunks)
  • packages/core/src/organization-project-module/organization-project-module.service.ts (4 hunks)
  • packages/core/src/organization-project/organization-project.service.ts (3 hunks)
  • packages/core/src/organization-sprint/organization-sprint.service.ts (5 hunks)
  • packages/core/src/resource-link/resource-link.service.ts (4 hunks)
  • packages/core/src/tasks/commands/handlers/automation-task.sync.handler.ts (4 hunks)
  • packages/core/src/tasks/commands/handlers/task-create.handler.ts (2 hunks)
  • packages/core/src/tasks/task.service.ts (3 hunks)
  • packages/core/src/tasks/views/view.service.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (7)
  • packages/core/src/activity-log/activity-log.service.ts
  • packages/core/src/organization-project-module/organization-project-module.service.ts
  • packages/core/src/organization-sprint/organization-sprint.service.ts
  • packages/core/src/resource-link/resource-link.service.ts
  • packages/core/src/tasks/commands/handlers/automation-task.sync.handler.ts
  • packages/core/src/tasks/commands/handlers/task-create.handler.ts
  • packages/core/src/tasks/views/view.service.ts
🧰 Additional context used
🔇 Additional comments (4)
packages/core/src/organization-project/organization-project.service.ts (3)

25-25: LGTM: Logging mechanism updated

The change from EventBus to ActivityLogService aligns with the PR objective of using a generic method for activity logging. This update should provide a more standardized approach to logging activities across the application.

Also applies to: 48-48


125-134: LGTM: Enhanced activity logging implemented

The new implementation of activity logging using ActivityLogService provides more detailed and structured information about the created project. This change enhances the traceability and context of project creation events, which should improve debugging and auditing capabilities.


25-25: Summary: Improved activity logging for project creation

The changes in this file successfully implement a more robust activity logging mechanism for project creation. By replacing EventBus with ActivityLogService, the code now provides more detailed and structured logging. This update aligns well with the PR objectives and should enhance the overall traceability and auditability of project-related activities in the system.

Also applies to: 48-48, 125-134

packages/core/src/tasks/task.service.ts (1)

24-25: LGTM: ActivityLogService integration

The addition of ActivityLogService and ActionTypeEnum imports, along with the constructor update, aligns well with the integration of activity logging functionality. This change enhances the service's ability to track and log task-related activities.

Also applies to: 32-32, 47-47

@rahul-rocket rahul-rocket merged commit af1c24c into develop Oct 17, 2024
11 of 20 checks passed
@rahul-rocket rahul-rocket deleted the feat/automation-task-sync-activity-log branch October 17, 2024 13:33
@coderabbitai coderabbitai bot mentioned this pull request Jan 24, 2025
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants