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 "Dashboard" Entity Based On Employee #8790

Merged
merged 3 commits into from
Feb 19, 2025

Conversation

rahul-rocket
Copy link
Collaborator

@rahul-rocket rahul-rocket commented Feb 19, 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

    • Introduced employee-specific dashboard creation generating both default and random dashboard data.
    • Enhanced API endpoints with clearer routes and improved operation summaries.
    • Streamlined notification seeding with configurable batch sizes.
  • Refactor

    • Updated dashboard structure to include employee details and renamed user attribution fields.
    • Improved error handling and logging during dashboard creation and updates.
    • Revised type definitions for consistency across employee and user data.
  • Chores

    • Applied database schema migrations to support the updated dashboard structure.

Copy link
Contributor

coderabbitai bot commented Feb 19, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request implements extensive updates across multiple modules. It restructures dashboard-related interfaces and type definitions, adds new utility types, renames and repositions user-related properties, and enhances error handling in command handlers. Additional seeding functions for default and random employee dashboards are introduced along with adjustments to API endpoint paths, DTOs, and database migrations for dashboard entities. Minor changes in notification seeding further streamline the data insertion process.

Changes

File(s) Change Summary
packages/contracts/src/lib/dashboard.model.ts, packages/contracts/src/lib/employee.model.ts, packages/contracts/src/lib/user.model.ts Updated type definitions and interface structures; renamed types and interfaces (e.g., from ExcludeCreatorFields to ExcludeUserCreatorFields, IHasCreator to IHasUserCreator), and added a new utility type (ExcludeEmployeeAuthorFields).
packages/core/src/lib/core/seeds/seed-data.service.ts, packages/core/src/lib/dashboard/dashboard.seed.ts Added methods for seeding default and random employee dashboards; introduced helper function insertDashboards for batch insertion.
packages/core/src/lib/dashboard/commands/handlers/dashboard.create.handler.ts, packages/core/src/lib/dashboard/commands/handlers/dashboard.update.handler.ts Enhanced error handling with try-catch blocks and logging; added a logger instance to capture errors and throw HttpException on failures.
packages/core/src/lib/dashboard/dashboard.controller.ts, packages/core/src/lib/dashboard/dto/create-dashboard.dto.ts Updated API route definitions (added leading /), enhanced API documentation, and modified DTO inheritance to reflect new naming conventions.
packages/core/src/lib/dashboard/dashboard.entity.ts Modified the Dashboard entity: made isDefault optional, added optional employee-related fields, and renamed creator fields to createdByUser and createdByUserId.
packages/core/src/lib/dashboard/dashboard.service.ts Renamed private member (activityLogService to _activityLogService) and refined create/update logic with improved error handling and variable naming.
packages/core/src/lib/dashboard/dashboard.subscriber.ts Removed redundant error logging while maintaining JSON serialization handling for SQLite.
packages/core/src/lib/database/migrations/1739950092274-AlterDashboardEntityTable.ts Added a new migration to update the dashboard table structure across PostgreSQL, MySQL, and SQLite; replaced creatorId with employeeId and createdByUserId, and added corresponding constraints and indexes.
packages/core/src/lib/employee-notification/employee-notification.seed.ts Updated function signatures: changed the default notification function to accept a single organization and added an optional batchSize parameter for configurable batch insertion.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant DC as DashboardController
    participant DCH as DashboardCreateHandler
    participant DS as DashboardService
    participant DB as Database

    U->>DC: POST /dashboard
    DC->>DCH: execute(dashboardData)
    DCH->>DS: create(dashboardData)
    DS->>DB: Save dashboard
    alt Dashboard creation success
       DB-->>DS: Dashboard saved
       DS-->>DCH: Return dashboard
       DCH-->>DC: Return success response
    else Dashboard creation failure
       DS-->>DCH: Error occurred
       DCH->>DCH: Log error details
       DCH-->>DC: Throw HttpException (BAD_REQUEST)
    end
Loading
sequenceDiagram
    participant SDS as SeedDataService
    participant DD as DashboardSeed
    participant DB as Database

    SDS->>DD: createDefaultEmployeeDashboards(dataSource, tenant, org, employees)
    DD->>DB: insertDashboards(dashboardList)
    DB-->>DD: Insertion result
    DD-->>SDS: Return default dashboards

    SDS->>DD: createRandomEmployeeDashboards(dataSource, tenants, orgEmpMap)
    DD->>DB: insertDashboards(dashboardList)
    DB-->>DD: Insertion result
    DD-->>SDS: Return random dashboards
Loading

Possibly related PRs

  • Feat/dashboard widget api #8624: The changes in the main PR are related to the modifications of the IDashboard and IDashboardCreateInput interfaces, which are directly impacted by the changes in the IDashboardWidgetUpdateInput interface in the retrieved PR.
  • [Feat] update relationship between module and member #8558: The changes in the main PR, which involve modifications to the IDashboard and IDashboardCreateInput interfaces, are related to the changes in the retrieved PR that updates the IOrganizationProjectModule interface and introduces the IOrganizationProjectModuleEmployee interface.
  • [Feat] #8386 Global Logging For API Request (DB Structure) #8390: The changes in the main PR are related to the modifications of the IDashboard and IDashboardCreateInput interfaces, which involve the use of the ExcludeUserCreatorFields type that was renamed and updated in the retrieved PR.

Poem

Hopping through lines of code so bright,
I tweak the interfaces with all my might.
Error logs now whisper their tale,
And dashboards bloom without fail.
With every seed and migration in sight,
This rabbit celebrates a code delight! 🐇💻


📜 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 8a01523 and 986558b.

📒 Files selected for processing (1)
  • packages/core/src/lib/dashboard/dashboard.entity.ts (3 hunks)

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.

@rahul-rocket rahul-rocket merged commit 0b7e27b into develop Feb 19, 2025
13 of 15 checks passed
@rahul-rocket rahul-rocket deleted the fix/alter-dashboard-entity branch February 19, 2025 10:14
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 (8)
packages/core/src/lib/database/migrations/1739950092274-AlterDashboardEntityTable.ts (2)

1-3: Consider avoiding console-based logging in migrations.

Using chalk and console.log in a production setting may clutter logs. Consider removing these calls, or use a dedicated logging mechanism in your migration scripts for consistent and traceable logs.


675-704: Incorporate a log or validation step for MySQL user-employee mapping.

Based on your prior learnings for MySQL migrations, consider adding a validation or logging routine for edge cases where dashboards lack corresponding employee records. A side logging table or migration summary can help track problematic rows.

packages/core/src/lib/dashboard/commands/handlers/dashboard.create.handler.ts (1)

24-25: Enhance error handling for better security and clarity.

Consider these improvements to the error handling:

  1. Avoid logging the full stack trace as it might expose sensitive information
  2. Provide more specific error messages for different failure scenarios
-			this.logger.error('Failed to create dashboard', error.stack);
-			throw new HttpException(`Error while creating dashboard: ${error.message}`, HttpStatus.BAD_REQUEST);
+			this.logger.error('Failed to create dashboard', error.message);
+			throw new HttpException(
+				'Failed to create dashboard. Please check the input data and try again.',
+				HttpStatus.BAD_REQUEST
+			);
packages/core/src/lib/dashboard/commands/handlers/dashboard.update.handler.ts (1)

24-25: Apply consistent error handling improvements.

Similar to the create handler, enhance the error handling:

  1. Avoid logging the full stack trace
  2. Provide more specific error messages
-			this.logger.error('Failed to update dashboard', error.stack);
-			throw new HttpException(`Error while updating dashboard: ${error.message}`, HttpStatus.BAD_REQUEST);
+			this.logger.error('Failed to update dashboard', error.message);
+			throw new HttpException(
+				'Failed to update dashboard. Please check the input data and try again.',
+				HttpStatus.BAD_REQUEST
+			);
packages/core/src/lib/dashboard/dashboard.entity.ts (2)

124-124: Fix typo in comment.

Correct the spelling of "Dashbaord" to "Dashboard".

-	 * Dashbaord Widgets
+	 * Dashboard Widgets
🧰 Tools
🪛 GitHub Check: Cspell

[warning] 124-124:
Unknown word (Dashbaord)

🪛 GitHub Actions: Check Spelling and Typos with cspell

[warning] 124-124: Unknown word (Dashbaord)


90-97: Consider adding database index for employeeId.

Since employeeId will likely be used in queries to fetch dashboards for specific employees, consider adding a database index to improve query performance.

 	@ApiPropertyOptional({ type: () => String })
 	@IsOptional()
 	@IsUUID()
 	@IsEmployeeBelongsToOrganization()
 	@RelationId((dashboard: Dashboard) => dashboard.employee)
-	@ColumnIndex()
+	@Index()
 	@MultiORMColumn({ relationId: true })
 	employeeId?: ID;
packages/core/src/lib/dashboard/dashboard.seed.ts (2)

101-102: Fix incorrect comment reference.

The comment references "EmployeeNotification" instead of "Dashboard".

-		// Get the repository for EmployeeNotification
+		// Get the repository for Dashboard

95-98: Enhance warning message with more context.

The warning message could be more helpful by including the count of dashboards.

 	if (!dashboards.length) {
-		console.warn('No dashboards to insert. Please check the input data and try again.');
+		console.warn('No dashboards to insert. Received an empty array of dashboards. Please check the input data and try again.');
 		return [];
 	}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 487adbc and 8a01523.

📒 Files selected for processing (14)
  • packages/contracts/src/lib/dashboard.model.ts (2 hunks)
  • packages/contracts/src/lib/employee.model.ts (1 hunks)
  • packages/contracts/src/lib/user.model.ts (1 hunks)
  • packages/core/src/lib/core/seeds/seed-data.service.ts (4 hunks)
  • packages/core/src/lib/dashboard/commands/handlers/dashboard.create.handler.ts (1 hunks)
  • packages/core/src/lib/dashboard/commands/handlers/dashboard.update.handler.ts (2 hunks)
  • packages/core/src/lib/dashboard/dashboard.controller.ts (2 hunks)
  • packages/core/src/lib/dashboard/dashboard.entity.ts (3 hunks)
  • packages/core/src/lib/dashboard/dashboard.seed.ts (1 hunks)
  • packages/core/src/lib/dashboard/dashboard.service.ts (3 hunks)
  • packages/core/src/lib/dashboard/dashboard.subscriber.ts (0 hunks)
  • packages/core/src/lib/dashboard/dto/create-dashboard.dto.ts (1 hunks)
  • packages/core/src/lib/database/migrations/1739950092274-AlterDashboardEntityTable.ts (1 hunks)
  • packages/core/src/lib/employee-notification/employee-notification.seed.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • packages/core/src/lib/dashboard/dashboard.subscriber.ts
🧰 Additional context used
🧠 Learnings (1)
packages/core/src/lib/database/migrations/1739950092274-AlterDashboardEntityTable.ts (2)
Learnt from: rahul-rocket
PR: ever-co/ever-gauzy#8771
File: packages/core/src/lib/database/migrations/1739602849367-AlterActivityLogEntityTable.ts:600-642
Timestamp: 2025-02-17T07:36:46.838Z
Learning: MySQL migrations involving user-employee mappings should include logging and error handling for cases where employee records don't exist or multiple records exist for a user. Use a logging table to track problematic records and generate migration summaries.
Learnt from: rahul-rocket
PR: ever-co/ever-gauzy#8769
File: packages/core/src/lib/database/migrations/1739364133493-AlterCommentEntityTable.ts:658-659
Timestamp: 2025-02-13T16:48:54.177Z
Learning: TypeORM-generated migrations may use different data types for UUID fields (uuid in PostgreSQL, varchar(255) in MySQL) as this is handled by TypeORM's migration generator and is the standard practice across the packages.
🪛 GitHub Check: Cspell
packages/core/src/lib/dashboard/dashboard.entity.ts

[warning] 124-124:
Unknown word (Dashbaord)

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

[warning] 124-124: Unknown word (Dashbaord)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: build
  • GitHub Check: test
🔇 Additional comments (23)
packages/core/src/lib/database/migrations/1739950092274-AlterDashboardEntityTable.ts (4)

13-30: Verify data migration from the dropped “creatorId” field.

Dropping the existing creatorId column without transferring its values to the newly introduced columns may cause data loss. If you need to retain or re-map the old data, please implement a transformation step before removing creatorId.


106-391: Verify data continuity in the SQLite 'Up' process.

The multi-step SQLite migration pattern re-creates the table multiple times. Ensure that all intermediate steps preserve data integrity (especially when dropping columns like creatorId and adding employeeId, createdByUserId). Test with actual data to confirm no unintentional data loss occurs.


392-673: Review rollback steps for SQLite migrations.

The down migration reverts certain columns but does not re-populate them with data previously stored in employeeId or createdByUserId. Verify if this partial rollback is acceptable or if additional data handling is required.


706-727: Confirm correct reversal of MySQL changes.

When dropping employeeId and createdByUserId during rollback, data introduced by the up migration is lost. Confirm if this behavior is expected or if additional logic is needed to restore or preserve data in the old creatorId column.

packages/core/src/lib/dashboard/dto/create-dashboard.dto.ts (1)

10-13: Confirm omission of the user-related fields in creation.

The properties createdByUser, createdByUserId are now excluded from the DTO, so they won't be set when creating dashboards. Verify that you don't need to assign or capture the creating user at creation time.

packages/contracts/src/lib/dashboard.model.ts (2)

1-4: Imports and new references look consistent.

You’ve introduced imports for IEmployeeEntityInput and updated user-creator fields. This aligns well with the new entity structure. No issues spotted on these lines.


9-23: Validate extension of `IEmployeeEntityInput` and `IHasUserCreator`.

Dashboards now require an associated employee and user creator. If there are dashboards owned by users who are not employees, ensure they can still gracefully map these fields or safely handle missing references.

packages/core/src/lib/dashboard/dashboard.seed.ts (2)

14-36: LGTM! Well-structured default dashboard creation.

The implementation is clean and includes all necessary fields for creating default dashboards.


47-81: LGTM! Efficient implementation of random dashboard creation.

The nested iteration through tenants, organizations, and employees is well-structured and maintains proper relationships.

packages/core/src/lib/dashboard/dashboard.service.ts (4)

10-12: LGTM! Import paths are now more specific.

The import paths have been updated to be more specific, improving code maintainability.


22-22: LGTM! Variable naming follows conventions.

The private variable has been renamed from activityLogService to _activityLogService to follow the naming convention for private members.


65-68: Enhanced error handling with logging.

Error handling has been improved by adding console logging before throwing the HTTP exception. This will help with debugging issues in production.


92-95: Improved error handling for non-existent dashboard.

The error handling for a non-existent dashboard now includes logging, which will help track down issues in production.

packages/core/src/lib/dashboard/dashboard.controller.ts (2)

30-30: LGTM! API endpoint paths follow REST best practices.

The API endpoint paths have been updated to include leading slashes, following REST API best practices:

  • @Controller('/dashboard')
  • @Get('/')
  • @Get('/:id')
  • @Post('/')
  • @Put('/:id')
  • @Delete('/:id')

Also applies to: 54-54, 77-77, 102-102, 131-131, 153-153


43-43: LGTM! Enhanced API documentation.

The API operation summaries have been improved with more descriptive text, making the API more user-friendly:

  • "Retrieve a list of dashboards with pagination"
  • "Retrieve a dashboard by its ID"
  • "Create a new dashboard"
  • "Update an existing dashboard"
  • "Delete a dashboard by ID"

Also applies to: 66-66, 92-92, 115-115, 143-143

packages/core/src/lib/employee-notification/employee-notification.seed.ts (2)

25-25: LGTM! Simplified organization handling.

Changed from array to single organization parameter, improving code clarity and reducing complexity.


140-141: LGTM! Added configurable batch size for performance tuning.

Added optional batchSize parameter with a default value of 100, allowing for performance optimization of bulk inserts.

packages/contracts/src/lib/user.model.ts (2)

33-33: LGTM! Improved type naming and field exclusion.

The utility type has been renamed from ExcludeCreatorFields to ExcludeUserCreatorFields and now excludes createdByUser and createdByUserId fields, making it more specific and clearer in its purpose.


38-41: LGTM! Enhanced creator interface naming and fields.

The interface has been renamed from IHasCreator to IHasUserCreator with updated field names, improving clarity and consistency in the codebase.

packages/contracts/src/lib/employee.model.ts (1)

31-34: LGTM! Well-documented utility type.

The ExcludeEmployeeAuthorFields type is a well-designed utility that provides a flexible way to exclude employee-related fields from types. The implementation is clean and follows TypeScript best practices.

packages/core/src/lib/core/seeds/seed-data.service.ts (3)

32-32: LGTM! Clean import statement.

The import statement follows the existing pattern and imports the necessary functions for dashboard seeding.


724-732: LGTM! Well-structured default dashboard seeding.

The implementation follows the established seeding pattern and correctly passes the required parameters for creating default employee dashboards.


1424-1432: LGTM! Well-structured random dashboard seeding.

The implementation follows the established seeding pattern and correctly passes the required parameters for creating random employee dashboards.

Comment on lines +59 to +81
public async postgresUpQueryRunner(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`ALTER TABLE "dashboard" DROP CONSTRAINT "FK_d343751cf98e2bfd85754a35a12"`);
await queryRunner.query(`DROP INDEX "public"."IDX_d343751cf98e2bfd85754a35a1"`);
await queryRunner.query(`ALTER TABLE "dashboard" DROP COLUMN "creatorId"`);
await queryRunner.query(`ALTER TABLE "dashboard" ADD "employeeId" uuid NOT NULL`);
await queryRunner.query(`ALTER TABLE "dashboard" ADD "createdByUserId" uuid NOT NULL`);
await queryRunner.query(`CREATE INDEX "IDX_b34e5ae765e0f8d674e0604621" ON "dashboard" ("employeeId") `);
await queryRunner.query(`CREATE INDEX "IDX_30613c8cd1a1df1b176dfb696b" ON "dashboard" ("createdByUserId") `);
await queryRunner.query(
`ALTER TABLE "dashboard"
ADD CONSTRAINT "FK_b34e5ae765e0f8d674e06046210"
FOREIGN KEY ("employeeId") REFERENCES "employee"("id")
ON DELETE CASCADE
ON UPDATE NO ACTION`
);
await queryRunner.query(
`ALTER TABLE "dashboard"
ADD CONSTRAINT "FK_30613c8cd1a1df1b176dfb696ba"
FOREIGN KEY ("createdByUserId") REFERENCES "user"("id")
ON DELETE CASCADE
ON UPDATE NO ACTION`
);
}
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 handling for missing employee records.

This migration enforces a NOT NULL foreign key relationship with the employee table but doesn’t handle scenarios where an existing dashboard might not have a matching employee. In similar past PRs, you mentioned logging missing user-employee mappings. Consider applying that solution here to avoid referential integrity breaks.

Copy link

nx-cloud bot commented Feb 19, 2025

View your CI Pipeline Execution ↗ for commit 986558b.

Command Status Duration Result
nx build desktop-ui-lib --configuration=production ✅ Succeeded 30s View ↗
nx build plugin-integration-wakatime ✅ Succeeded <1s View ↗
nx build desktop-lib ✅ Succeeded <1s View ↗
nx build desktop-window ✅ Succeeded <1s View ↗
nx build desktop-core ✅ Succeeded <1s View ↗
nx build plugin-videos ✅ Succeeded <1s View ↗
nx build plugin-integration-upwork ✅ Succeeded <1s View ↗
nx build plugin-integration-hubstaff ✅ Succeeded <1s View ↗
Additional runs (52) ✅ Succeeded ... View ↗

☁️ Nx Cloud last updated this comment at 2025-02-19 10:58:35 UTC

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.

1 participant