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] Alter Activity Log Entity Based On Employee #8771

Merged
merged 9 commits into from
Feb 17, 2025

Conversation

GloireMutaliko21
Copy link
Contributor

@GloireMutaliko21 GloireMutaliko21 commented Feb 11, 2025

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
    • Activity log entries now reference employee details rather than generic user information, providing enhanced tracking and accountability.
  • Refactor
    • Updated activity tracking processes to integrate employee-specific data seamlessly.
  • Chores
    • Performed underlying database updates to ensure consistency and reliability with the new employee-oriented logging system.

Copy link
Contributor

coderabbitai bot commented Feb 11, 2025

Walkthrough

The changes refactor activity log functionality to shift from a user-centric model to an employee-centric one. In the contracts package, interface definitions are updated to extend employee-related types and remove user-specific properties. In the core package, both the entity and service classes replace "creator" and "creatorId" with "employee" and "employeeId," including updates to validation and comment descriptions. A new migration updates the database table accordingly, modifying constraints, indexes, and column mappings across PostgreSQL, SQLite, and MySQL.

Changes

File(s) Change Summary
packages/contracts/src/lib/.../activity-log.model.ts Updated IActivityLog to extend employee-related interfaces; removed creator/creatorId and updated IActivityLogInput to use OmitFields, excluding employeeId and employee.
packages/core/src/lib/.../activity-log.entity.ts
packages/core/src/lib/.../activity-log.service.ts
Replaced the User model with the Employee model; updated property names from creator/creatorId to employee/employeeId, adjusted comments, imports, and validation (e.g., added @IsUUID). In the service, the method now retrieves employeeId using currentEmployeeId().
packages/core/src/lib/.../1739602849367-AlterActivityLogEntityTable.ts Introduced a new migration class to modify the activity_log table: dropping and re-adding foreign key constraints, indexes, and columns to replace creatorId with employeeId, with specific routines for PostgreSQL, SQLite, and MySQL.

Possibly related PRs

Suggested labels

hold

Suggested reviewers

  • GloireMutaliko21

Poem

I'm hopping through the code, quick and neat,
Changing "users" to "employees" in every beat.
The logs now sing a brand new tune,
With employee vibes, bright as the moon.
Keep on coding—let's leap to success soon!
🐇💻


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4307c12 and 5c35909.

📒 Files selected for processing (1)
  • packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: test

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 1

🧹 Nitpick comments (7)
packages/core/src/lib/database/migrations/1739268372038-AlterActivityLogTableUsingEmployeeId.ts (4)

1-7: Consider using a standardized logging approach in migrations.
While using console.log and chalk for feedback is acceptable during development, you might consider leveraging the built-in queryRunner.logger or a consistent application logger for production environments.


13-30: Wrap the up migration in a transaction if supported.
For safer schema updates, consider wrapping the up actions in a transaction (if the underlying database supports it). This ensures that either all schema changes apply successfully or none do, preventing partial updates in case of errors.


32-52: Consider transactional rollback for the down migration.
Similar reasoning applies here: using transactions (where supported) can protect against partial rollbacks if an error occurs during the down steps.


90-168: Be aware of potential data migration overhead on large tables in SQLite.
The strategy of creating a temporary table, copying data, and dropping the original table is common for SQLite, but can be slow for large datasets. If performance is a concern for large activity_log tables, consider scheduling downtime or batched copies.

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

33-39: Update method documentation to reflect employee-centric changes.

The documentation still refers to "current user" instead of "current employee".

 /**
- * Creates a new activity log entry with the provided input, while associating it with the current user and tenant.
+ * Creates a new activity log entry with the provided input, while associating it with the current employee and tenant.
  *
  * @param input - The data required to create an activity log entry.
  * @returns The created activity log entry.
  * @throws BadRequestException when the log creation fails.
  */

42-42: Update comment to reflect employee context.

The comment still refers to "user's ID".

-			// Retrieve the current user's ID from the request context
+			// Retrieve the current employee's ID from the request context

1-176: Consider architectural implications of employee-centric logging.

The shift from user-centric to employee-centric logging is a significant architectural change. Please consider:

  1. What happens when non-employee users perform actions?
  2. How does this affect system-generated logs?
  3. Are there any reporting or auditing requirements that might need both user and employee context?

Let's check for system-generated logs and non-employee actions:

❌ Verification inconclusive

🏁 Script executed:

#!/bin/bash
# Search for system-generated logs and non-employee actions
rg "ActorTypeEnum.SYSTEM" --type ts
rg "logActivity.*ActorTypeEnum" -A 5 --type ts

Length of output: 84


Architectural Implication: Verify Handling of Non‐Employee and System Actions
Our current implementation in ActivityLogService consistently uses the employee ID obtained via RequestContext.currentEmployeeId(), and a repository search did not reveal any usage of ActorTypeEnum.SYSTEM or any alternative handling for non‐employee user actions. This means that system-generated events or actions performed by users who aren’t employees might not be logged as expected.

  • The log creation in the create() method relies solely on currentEmployeeId().
  • No evidence was found that non-employee or system-originated actions are handled differently (e.g., via ActorTypeEnum.SYSTEM or an alternative context check).
  • This might impact auditing or reporting requirements if both employee and non-employee contexts are needed.

Please manually verify if system events or actions by non-employees are expected to be logged with different semantics or if additional logic is needed to address these cases.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bce9192 and 6e934c5.

📒 Files selected for processing (4)
  • packages/contracts/src/lib/activity-log.model.ts (2 hunks)
  • packages/core/src/lib/activity-log/activity-log.entity.ts (2 hunks)
  • packages/core/src/lib/activity-log/activity-log.service.ts (1 hunks)
  • packages/core/src/lib/database/migrations/1739268372038-AlterActivityLogTableUsingEmployeeId.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: test
🔇 Additional comments (7)
packages/core/src/lib/database/migrations/1739268372038-AlterActivityLogTableUsingEmployeeId.ts (3)

59-67: Postgres foreign key constraint rename looks correct.
The new constraint referencing the employee table with cascade behavior aligns with the rest of the employee-centric changes. This appears correct.


261-269: MySQL column rename and foreign key update look good.
Changing creatorId to employeeId aligns with the rest of the updates and references the correct table.


277-284: Reverse logic for MySQL is consistent.
Dropping the new constraint and reintroducing the old one reverts the schema correctly.

packages/contracts/src/lib/activity-log.model.ts (2)

12-15: Employee-based extension in IActivityLog is coherent.
Replacing user references with IEmployeeEntityInput matches the new employee-centric approach across the codebase.


40-43: Updated omission for IActivityLogInput is aligned.
Switching from omitting 'creatorId' | 'creator' to 'employeeId' | 'employee' keeps the interface consistent with the new model. Verify that all code referencing old props is updated.

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

7-8: Imports switched from User to Employee.
The removal of the User import and addition of the Employee import fits the shift to an employee-based logging mechanism.


94-109: References changed to employee and employeeId.
The property rename from creator to employee aligns with the updated database schema and model interfaces. The new RelationId usage and on-delete cascade policy appear consistent with the application’s intended logic.

Copy link

nx-cloud bot commented Feb 11, 2025

View your CI Pipeline Execution ↗ for commit 5c35909.

Command Status Duration Result
nx build desktop --base-href ./ ✅ Succeeded 1m 49s View ↗
nx build desktop-api --output-path=dist/apps/de... ✅ Succeeded 28s View ↗
nx run api:desktop-api ✅ Succeeded 1m 16s View ↗
nx build gauzy -c=production --prod --verbose ✅ Succeeded 3m 54s View ↗
nx run gauzy:desktop-ui --base-href ./ ✅ Succeeded 3m 38s View ↗
nx build api -c=production --prod ✅ Succeeded 1m 7s View ↗
nx build desktop-ui-lib --configuration=production ✅ Succeeded 28s View ↗
nx build desktop-ui-lib --configuration=develop... ✅ Succeeded 29s View ↗
Additional runs (56) ✅ Succeeded ... View ↗

☁️ Nx Cloud last updated this comment at 2025-02-17 07:47:02 UTC

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

🧹 Nitpick comments (1)
packages/core/src/lib/activity-log/activity-log.entity.ts (1)

91-100: Fix typo in documentation.

There's a typo in the documentation comment: "Actvity" should be "Activity".

Apply this diff to fix the typo:

-	 * Actvity Log Author ID
+	 * Activity Log Author ID
🧰 Tools
🪛 GitHub Check: Cspell

[warning] 92-92:
Unknown word (Actvity)

🪛 GitHub Actions: Check Spelling and Typos with cspell

[warning] 92-92: Unknown word (Actvity)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 79cfb86 and 55c1c65.

📒 Files selected for processing (2)
  • packages/contracts/src/lib/activity-log.model.ts (2 hunks)
  • packages/core/src/lib/activity-log/activity-log.entity.ts (2 hunks)
🧰 Additional context used
🪛 GitHub Check: Cspell
packages/core/src/lib/activity-log/activity-log.entity.ts

[warning] 92-92:
Unknown word (Actvity)

🪛 GitHub Actions: Check Spelling and Typos with cspell
packages/core/src/lib/activity-log/activity-log.entity.ts

[warning] 92-92: Unknown word (Actvity)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: test
🔇 Additional comments (4)
packages/contracts/src/lib/activity-log.model.ts (2)

7-17: LGTM! Well-structured employee-centric activity log interface.

The interface successfully transitions from user-centric to employee-centric logging while maintaining comprehensive documentation and type safety.


32-35: LGTM! Consistent input interface definition.

The interface correctly uses OmitFields to exclude employee-related fields, maintaining consistency with the employee-centric model.

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

5-8: LGTM! Proper imports and validation.

The imports are correctly updated to support employee-centric logging and include proper validation decorators.


79-89: LGTM! Well-defined employee relation.

The ManyToOne relation is properly configured with appropriate cascade and nullable settings.

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 (2)
packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts (2)

59-101: Consider chunk-based or batched updates when reassigning IDs.
For large tables, using a single UPDATE statement that references another table can potentially lock or slow down the database. If the activity_log table contains a high volume of data, chunk-based updates may improve performance and reduce lock contention.


108-150: Replicate the batching strategy for the down migration.
The down() migration uses a single UPDATE to revert employeeId back to creatorId. As with the up() process, consider chunk-based approaches for large data sets to avoid performance bottlenecks.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 55c1c65 and 3d4e210.

📒 Files selected for processing (4)
  • packages/contracts/src/lib/activity-log.model.ts (2 hunks)
  • packages/core/src/lib/activity-log/activity-log.entity.ts (2 hunks)
  • packages/core/src/lib/activity-log/activity-log.service.ts (1 hunks)
  • packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/core/src/lib/activity-log/activity-log.service.ts
  • packages/core/src/lib/activity-log/activity-log.entity.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: test
  • GitHub Check: build
🔇 Additional comments (4)
packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts (1)

72-84:

❓ Verification inconclusive

Verify presence of corresponding employee records.
When transferring creatorId to employeeId using a sub-query on the employee table, any missing captures (e.g., if creatorId doesn't map to an existing employee.userId) will result in null employeeId values.

Below is a script to identify whether orphaned creatorId entries exist in the activity_log table:

You could then decide how to handle these orphaned rows gracefully.


🏁 Script executed:

#!/bin/bash
# This script checks for any activity_log rows whose creatorId cannot be mapped to an employee's userId

echo "Detecting orphaned creatorId entries..."
cat <<EOF | psql
SELECT COUNT(*) AS orphan_count
FROM "activity_log" al
WHERE al."creatorId" IS NOT NULL
  AND NOT EXISTS (
    SELECT 1
    FROM "employee" e
    WHERE e."userId" = al."creatorId"
  );
EOF

Length of output: 197


Action Required: Manual Verification of Orphaned Creator IDs

The intended query to detect orphaned creatorId entries could not be executed due to a missing PostgreSQL (psql) command in the current environment. Please verify manually or through an appropriate environment that supports psql to ensure no activity_log records contain unmapped creatorId values.

  • Issue: The provided script errored with psql: command not found, so its output is inconclusive.
  • Next Steps:
    • Re-run the query in an environment with PostgreSQL installed or via an alternative method to check for orphaned creatorId entries.
    • Confirm that every non-null creatorId in activity_log maps to an existing employee.userId.
packages/contracts/src/lib/activity-log.model.ts (3)

1-2: Good addition of IEmployeeEntityInput import.
The import statements at the top cleanly integrate employee-related types. This aligns the IActivityLog interface with the new employee-based model.


7-7: Shifting to employee-based interfaces seems consistent.
Replacing the prior user linkage with IEmployeeEntityInput in IActivityLog properly reflects the new reliance on the employee model. Verify all references across the codebase are similarly updated (e.g., any lingering creatorId usage).


35-35: Use of OmitFields in IActivityLogInput appears valid.
Utilizing OmitFields<IActivityLog> is a cleaner approach than manually specifying omitted fields. Ensure that the omitted fields match your intended omissions (i.e., no accidental override of required properties).

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

♻️ Duplicate comments (2)
packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts (2)

157-164: 🛠️ Refactor suggestion

SQLite migration placeholders remain unimplemented
These methods are empty and will result in inconsistent database states across SQLite deployments.

Consider implementing the migration steps or throwing an error to handle SQLite properly.


16-30: 🛠️ Refactor suggestion

Implement or explicitly disallow SQLite/better-sqlite3 migrations
Currently, the sqliteUpQueryRunner and sqliteDownQueryRunner methods are called for SQLite, but they are empty. This creates incomplete schema evolution for SQLite-based deployments.

You could either implement the SQLite-specific migration steps or throw a clear error indicating that these engines are not supported:

case DatabaseTypeEnum.sqlite:
case DatabaseTypeEnum.betterSqlite3:
-    await this.sqliteUpQueryRunner(queryRunner);
+    throw new Error('SQLite is not fully supported by this migration yet.');
break;
🧹 Nitpick comments (1)
packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts (1)

14-14: Consider using migration logging abstractions instead of console.log
While printing to the console in a migration is acceptable for quick feedback, leveraging TypeORM or a dedicated logging library can produce more consistent logs across various environments.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3d4e210 and 3c11c05.

📒 Files selected for processing (1)
  • packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: test
  • GitHub Check: build
🔇 Additional comments (2)
packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts (2)

60-85: Verify behavior for users with no matching employee record
When copying creatorId to employeeId, a mapping query sets employeeId to the last created employee for a matching user. If a user has multiple employees or none at all, the result may be unexpected (null or mismatched references).

Ensure that all employees can be mapped consistently or that a fallback mechanism handles users without employees.


185-196: Handle multiple possible employees for a single user
In MySQL, the query uses ORDER BY e.\createdAt` DESC LIMIT 1`, which may unpredictably map to the most recently created employee. Verify that the data model supports this assumption or confirm that each user has only one employee entry.

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

🧹 Nitpick comments (3)
packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts (3)

16-29: Consider separate migration files per DB vendor for maintainability.

While using a switch statement in a single migration class is convenient, splitting each database type’s logic into its own migration file can make maintenance and troubleshooting more straightforward, especially when differences in SQL syntax or constraints arise in future changes.


157-470: Reduce complexity of repeated dropping and recreating indexes.

Within the SQLite Up migration, multiple indexes are dropped and re-created several times in the same flow. While valid, this operation can inflate migration execution time on large datasets. Consider consolidating index operations to minimize overhead.


852-894: Consider transactional safety or compensating steps in MySQL Down.

Dropping and adding columns alongside foreign keys in multiple steps might expose intermediate states if the migration is partially applied and fails. Evaluate using a transaction (if supported) or providing a robust retry mechanism to guarantee a complete rollback.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3c11c05 and 4307c12.

📒 Files selected for processing (1)
  • packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: test
🔇 Additional comments (2)
packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts (2)

60-85: Validate the employee-user mapping before updating.

The PostgresUpQueryRunner relies on the assumption that each creatorId maps to a valid employee row (via userId). If no matching record exists, employeeId will be set to NULL. Consider adding logs or gracefully handling missing employee entries to avoid silently losing references in this step.


477-796: Ensure thorough testing for the multi-step SQLite rollback.

The SQLite Down migration merges multiple rename, copy, and re-creation cycles. This approach may be fragile if an error occurs mid-migration. Ensure thorough testing on real or staging datasets to confirm complete data integrity and correct rollback in all scenarios (e.g., partial data, existing constraints).

@evereq
Copy link
Member

evereq commented Feb 16, 2025

@rahul-rocket / @GloireMutaliko21 see suggestions by Coderabbit. Also can we get this merged?

@rahul-rocket rahul-rocket changed the title [Fix] Activity Log entity employee based [Fix] Alter Activity Log Entity Based On Employee Feb 17, 2025
@rahul-rocket rahul-rocket merged commit d80c8f5 into develop Feb 17, 2025
16 checks passed
@rahul-rocket rahul-rocket deleted the fix/activity-log-entity-employee-based branch February 17, 2025 07:49
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.

3 participants