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 "ScreeningTask" Entity Table #8801

Merged
merged 4 commits into from
Feb 24, 2025

Conversation

rahul-rocket
Copy link
Collaborator

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

    • Improved error handling during screening task creation and updates, providing clearer feedback.
    • Standardized screening task API routes for a more consistent integration experience.
    • Automatic association of new screening tasks with the correct user, streamlining task management.
  • Chores

    • Applied database schema enhancements to ensure improved data integrity for screening tasks.

Copy link
Contributor

coderabbitai bot commented Feb 24, 2025

Warning

Rate limit exceeded

@rahul-rocket has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 28 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 06d6556 and 16727bf.

📒 Files selected for processing (2)
  • packages/core/src/lib/tasks/screening-tasks/commands/handlers/screening-task.update.handler.ts (1 hunks)
  • packages/core/src/lib/tasks/screening-tasks/screening-task.entity.ts (3 hunks)

Walkthrough

The pull request refactors the screening task interfaces and related DTOs and entities to improve modularity and clarity. Changes include splitting an interface into two parts, adjusting type omission logic, and renaming properties. Additionally, it adds robust error handling to task creation and update handlers, updates subscriber registration and routing definitions, introduces a new database migration for screening task table alterations, and updates service constructor parameter ordering and task creation logic.

Changes

File(s) Summary
packages/contracts/src/lib/screening-task.model.ts Split IScreeningTask into IScreeningTaskBase and IScreeningTaskAssociations; updated create/update input interfaces to use OmitFields and extend IScreeningTaskBase.
packages/core/src/lib/tasks/screening-tasks/dto/create-screening-task.dto.ts
packages/core/src/lib/tasks/screening-tasks/screening-task.entity.ts
Simplified DTO inheritance via a flat IntersectionType; updated entity properties: added onHoldUntil, renamed creator/creatorId to createdByUser/createdByUserId, and improved property documentation.
packages/core/src/lib/core/entities/internal.ts
packages/core/src/lib/core/entities/subscribers/index.ts
packages/core/src/lib/tasks/screening-tasks/screening-task.subscriber.ts
Added a new ScreeningTaskSubscriber for handling pre-insert events; updated exports and subscriber aggregation to include this new entity.
packages/core/src/lib/database/migrations/1740385271257-AlterScreeningTaskEntityTable.ts Introduced a new migration file that alters the screening_task table for SQLite, PostgreSQL, and MySQL including column renaming and foreign key adjustments.
packages/core/src/lib/tasks/screening-tasks/commands/handlers/screening-task.create.handler.ts
packages/core/src/lib/tasks/screening-tasks/commands/handlers/screening-task.update.handler.ts
Enhanced the execute methods in both create and update handlers with try-catch error handling and added detailed JSDoc comments.
packages/core/src/lib/tasks/screening-tasks/screening-tasks.controller.ts Updated route definitions to include leading slashes and refined JSDoc comments and API response descriptions.
packages/core/src/lib/tasks/screening-tasks/screening-tasks.module.ts
packages/core/src/lib/tasks/screening-tasks/screening-tasks.service.ts
Adjusted module metadata by moving a module from exports to imports (resulting in empty exports) and updated service constructor order and task creation logic (using ?? and spread operators).

Sequence Diagram(s)

sequenceDiagram
  participant Client as User/Client
  participant Controller as ScreeningTasksController
  participant Handler as ScreeningTaskCreateHandler
  participant Service as ScreeningTasksService
  participant EventBus as EventBus
  participant Subscriber as ScreeningTaskSubscriber
  participant DB as Database

  Client->>Controller: POST /screening-tasks (create command)
  Controller->>Handler: execute(create command)
  Handler->>Service: create(data)
  Service->>EventBus: publish(CreateSubscriptionEvent)
  EventBus->>Subscriber: beforeEntityCreate(entity)
  Subscriber->>Service: Set createdByUserId on entity
  Service->>DB: Insert ScreeningTask
  DB-->>Service: Return confirmation
  Service-->>Handler: Return new ScreeningTask
  Handler-->>Controller: Return new ScreeningTask
  Controller-->>Client: HTTP response with new task
Loading

Possibly related PRs

  • [Fix] Comment entity employee based #8769: Addresses modifications in input interfaces to incorporate employee identifiers, similar to the adjustments seen in the IScreeningTaskCreateInput interface changes.

Poem

I'm a rabbit with hops so keen,
Skipping through code in places unseen.
Interfaces split, new paths unfurled,
Database migrations reshape our world.
With joyful hops and ASCII cheer,
I celebrate these changes far and near!
🐇💻


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

🔭 Outside diff range comments (2)
packages/core/src/lib/tasks/screening-tasks/screening-tasks.service.ts (2)

48-153: 🛠️ Refactor suggestion

Refactor create method to improve maintainability.

The create method is handling too many responsibilities. Consider extracting some operations into separate private methods.

+ private async createAssociatedTask(data: any, tenantId: string, organizationId: string, project: any): Promise<Task> {
+   const prefix = project?.name?.substring(0, 3) ?? null;
+   const maxNumber = await this.taskService.getMaxTaskNumberByProject({
+     tenantId,
+     organizationId,
+     projectId: project?.id ?? null
+   });
+   return this.taskService.create({
+     ...data.task,
+     prefix,
+     number: maxNumber + 1,
+     isScreeningTask: true,
+     tenantId,
+     organizationId
+   });
+ }

+ private async handleMentionsAndSubscriptions(
+   task: Task,
+   mentionEmployeeIds: ID[],
+   createdByUserId: string,
+   organizationId: string,
+   tenantId: string
+ ): Promise<void> {
+   const mentionPromises = mentionEmployeeIds.map((mentionedUserId: ID) =>
+     this.mentionService.publishMention({
+       entity: BaseEntityEnum.Task,
+       entityId: task.id,
+       entityName: task.title,
+       mentionedUserId,
+       mentionById: createdByUserId
+     })
+   );
+
+   this.eventBus.publish(
+     new CreateSubscriptionEvent({
+       entity: BaseEntityEnum.Task,
+       entityId: task.id,
+       userId: createdByUserId,
+       type: SubscriptionTypeEnum.CREATED_ENTITY,
+       organizationId,
+       tenantId
+     })
+   );
+
+   await Promise.all(mentionPromises);
+ }

  async create(input: IScreeningTaskCreateInput): Promise<IScreeningTask> {
    try {
      const createdByUserId = RequestContext.currentUserId();
      const tenantId = RequestContext.currentTenantId() ?? input.tenantId;
      const { organizationId, mentionEmployeeIds = [], ...data } = input;

      const project = data.task.projectId
        ? await this.organizationProjectService.findOneByIdString(data.task.projectId)
        : data.task.project || null;

      if (!project) {
        console.warn('No projectId or project provided. Proceeding without project information');
      }

      const task = await this.createAssociatedTask(data, tenantId, organizationId, project);

      const screeningTask = await super.create({
        ...data,
        status: ScreeningTaskStatusEnum.PENDING,
        taskId: task.id,
        organizationId,
        tenantId
      });

      await Promise.all([
        this.handleMentionsAndSubscriptions(
          task,
          mentionEmployeeIds,
          createdByUserId,
          organizationId,
          tenantId
        ),
        this.activityLogService.logActivity<Task>(/* ... */),
        this.activityLogService.logActivity<ScreeningTask>(/* ... */)
      ]);

      return screeningTask;
    } catch (error) {
-     throw new HttpException('Screening task creation failed', HttpStatus.BAD_REQUEST);
+     throw new HttpException(
+       `Screening task creation failed: ${error.message}`,
+       error instanceof HttpException ? error.getStatus() : HttpStatus.BAD_REQUEST
+     );
    }
  }

163-210: 🛠️ Refactor suggestion

Improve error handling in update method.

Similar to the create method, the error handling could be more specific.

		} catch (error) {
-			throw new HttpException(`Failed to update screening task with ID ${id}`, HttpStatus.BAD_REQUEST);
+			throw new HttpException(
+				`Failed to update screening task with ID ${id}: ${error.message}`,
+				error instanceof HttpException ? error.getStatus() : HttpStatus.BAD_REQUEST
+			);
		}
🧹 Nitpick comments (5)
packages/core/src/lib/tasks/screening-tasks/screening-task.subscriber.ts (1)

25-27: Remove redundant null check.

The null check on entity is unnecessary as TypeORM will never call the hook with a null entity.

-			if (entity) {
				entity.createdByUserId = RequestContext.currentUserId();
-			}
packages/core/src/lib/tasks/screening-tasks/screening-tasks.service.ts (1)

29-39: Consider reordering constructor parameters by dependency importance.

The eventBus parameter has been moved to the end, but it might be better to group related dependencies together.

	constructor(
		readonly typeOrmScreeningTaskRepository: TypeOrmScreeningTaskRepository,
		readonly mikroOrmScreeningTaskRepository: MikroOrmScreeningTaskRepository,
-		private readonly eventBus: EventBus,
		private readonly taskService: TaskService,
		private readonly organizationProjectService: OrganizationProjectService,
		private readonly mentionService: MentionService,
-		private readonly activityLogService: ActivityLogService
+		private readonly activityLogService: ActivityLogService,
+		private readonly eventBus: EventBus
	)
packages/contracts/src/lib/screening-task.model.ts (1)

26-26: Consider adding JSDoc comments for input interfaces.

While the base interfaces are well-documented, the input interfaces could benefit from similar documentation.

Add JSDoc comments:

+/**
+ * Interface for creating a new screening task, excluding the status field.
+ */
 export interface IScreeningTaskCreateInput extends OmitFields<IScreeningTask, 'status'>, IMentionEmployeeIds {}

+/**
+ * Interface for updating an existing screening task.
+ */
 export interface IScreeningTaskUpdateInput extends IScreeningTaskBase {}

Also applies to: 28-28

packages/core/src/lib/database/migrations/1740385271257-AlterScreeningTaskEntityTable.ts (2)

1-4: Consider making chalk logging optional.

Using chalk to colorize console output in a production migration is fine if your environment expects it, but it can clutter logs in certain deployments. Consider making the log call optional or only logging in development mode.


86-168: SQLite up migration approach is standard but long.

The temporary table approach is typical, due to SQLite's limited ALTER TABLE capabilities. For large datasets, notice that table re-creations and full data copies can be performance-heavy.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8d7d4f1 and 06d6556.

📒 Files selected for processing (12)
  • packages/contracts/src/lib/screening-task.model.ts (2 hunks)
  • packages/core/src/lib/core/entities/internal.ts (1 hunks)
  • packages/core/src/lib/core/entities/subscribers/index.ts (2 hunks)
  • packages/core/src/lib/database/migrations/1740385271257-AlterScreeningTaskEntityTable.ts (1 hunks)
  • packages/core/src/lib/tasks/screening-tasks/commands/handlers/screening-task.create.handler.ts (2 hunks)
  • packages/core/src/lib/tasks/screening-tasks/commands/handlers/screening-task.update.handler.ts (1 hunks)
  • packages/core/src/lib/tasks/screening-tasks/dto/create-screening-task.dto.ts (1 hunks)
  • packages/core/src/lib/tasks/screening-tasks/screening-task.entity.ts (3 hunks)
  • packages/core/src/lib/tasks/screening-tasks/screening-task.subscriber.ts (1 hunks)
  • packages/core/src/lib/tasks/screening-tasks/screening-tasks.controller.ts (5 hunks)
  • packages/core/src/lib/tasks/screening-tasks/screening-tasks.module.ts (1 hunks)
  • packages/core/src/lib/tasks/screening-tasks/screening-tasks.service.ts (4 hunks)
🧰 Additional context used
🧠 Learnings (3)
packages/core/src/lib/tasks/screening-tasks/screening-task.entity.ts (1)
Learnt from: rahul-rocket
PR: ever-co/ever-gauzy#8800
File: packages/core/src/lib/tasks/screening-tasks/screening-tasks.service.ts:81-81
Timestamp: 2025-02-24T05:25:58.665Z
Learning: The `creatorId` column in the `screening-task` entity will be renamed to `createdByUserId` in a future PR to maintain consistency with the task entity.
packages/core/src/lib/tasks/screening-tasks/screening-tasks.service.ts (1)
Learnt from: rahul-rocket
PR: ever-co/ever-gauzy#8800
File: packages/core/src/lib/tasks/screening-tasks/screening-tasks.service.ts:81-81
Timestamp: 2025-02-24T05:25:58.665Z
Learning: The `creatorId` column in the `screening-task` entity will be renamed to `createdByUserId` in a future PR to maintain consistency with the task entity.
packages/core/src/lib/database/migrations/1740385271257-AlterScreeningTaskEntityTable.ts (1)
Learnt from: rahul-rocket
PR: ever-co/ever-gauzy#8800
File: packages/core/src/lib/database/migrations/1740146592586-AlterOrganizationProjectModuleEntityTable.ts:0-0
Timestamp: 2025-02-24T05:26:43.208Z
Learning: SQLite and MySQL migration implementations for the Task entity table alterations will be added in subsequent commits. This is an intentional decision to implement the changes incrementally.
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: test
  • GitHub Check: build
🔇 Additional comments (18)
packages/core/src/lib/core/entities/internal.ts (1)

203-203: LGTM! The subscriber export is well-placed.

The new export for screening-task.subscriber is correctly placed among other task-related subscribers, maintaining consistent organization.

packages/core/src/lib/core/entities/subscribers/index.ts (1)

38-38: LGTM! The subscriber is properly integrated.

The ScreeningTaskSubscriber is correctly added to both the imports and coreSubscribers array, maintaining alphabetical ordering.

Also applies to: 96-96

packages/core/src/lib/tasks/screening-tasks/dto/create-screening-task.dto.ts (1)

10-12: LGTM! The DTO inheritance structure is simplified.

The flattened IntersectionType makes the code more maintainable while preserving the same functionality.

packages/core/src/lib/tasks/screening-tasks/screening-tasks.controller.ts (2)

30-30: LGTM! Route paths are now consistently formatted.

The route paths have been standardized to include leading slashes, which improves consistency across the API.

Also applies to: 55-55, 78-78, 102-102, 129-129, 154-154


39-44: LGTM! Comprehensive JSDoc comments added.

The addition of detailed JSDoc comments for all controller methods improves code documentation and maintainability.

Also applies to: 61-67, 86-91, 108-114, 138-143

packages/contracts/src/lib/screening-task.model.ts (2)

14-17: LGTM! Well-documented base interface.

The IScreeningTaskBase interface clearly defines core properties with descriptive comments.


19-22: LGTM! Good separation of concerns.

The IScreeningTaskAssociations interface effectively isolates relationship properties.

packages/core/src/lib/tasks/screening-tasks/screening-task.entity.ts (3)

21-29: LGTM! Well-documented status property.

The status property now has clear documentation explaining its purpose.


31-38: LGTM! New onHoldUntil property with validation.

The new property is well-documented and includes appropriate validation decorators.


48-52: LGTM! Clear cascade configuration documentation.

The cascade configuration is now well-documented with explanatory comments.

packages/core/src/lib/database/migrations/1740385271257-AlterScreeningTaskEntityTable.ts (8)

5-13: Migration class and naming convention look appropriate.

The class name and property name match the typical TypeORM migration pattern, and the doc comments provide clarity on the migration purpose.


14-30: Solid multi-database handling in the up method.

This switch-case pattern is a clear way to handle different database backends. Ensure that all new changes for each database dialect remain consistent as new features evolve.


32-52: Down method consistency check.

The down method mirrors the up method across the supported databases. This consistency helps maintain reliable rollback if needed.


54-70: Postgres up migration is well-structured.

The steps cleanly drop the old constraint, rename the column, and recreate the foreign key. Make sure these constraints match your intended referential actions (e.g., NO ACTION) for your business logic.


71-84: Postgres down migration matches the up migration.

Reverting the column renaming and constraints is straightforward. This symmetry ensures consistent rollbacks.


170-250: SQLite down migration retains full rollback.

This contains a similar temporary table rebuild to revert the changes. The logic looks consistent.


252-269: MySQL up migration: column rename and index re-creation.

The rename from creatorId to createdByUserId aligns with other DB logic. Confirm that the default NO ACTION on foreign key constraints meets your delete/update semantics.


271-289: MySQL down migration completes the cycle.

Rolls back the column rename and constraints properly. No issues spotted here.

rahul-rocket and others added 2 commits February 24, 2025 15:13
…ity.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
…screening-task.update.handler.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@rahul-rocket rahul-rocket merged commit a09f259 into develop Feb 24, 2025
16 checks passed
@rahul-rocket rahul-rocket deleted the fix/alter-screening-task-entity branch February 24, 2025 10:01
Copy link

nx-cloud bot commented Feb 24, 2025

View your CI Pipeline Execution ↗ for commit 16727bf.

Command Status Duration Result
nx build desktop --base-href ./ ✅ Succeeded 1m 48s View ↗
nx build desktop-api --output-path=dist/apps/de... ✅ Succeeded 28s View ↗
nx run api:desktop-api ✅ Succeeded 1m 15s View ↗
nx build gauzy -c=production --prod --verbose ✅ Succeeded 4m 1s View ↗
nx run gauzy:desktop-ui --base-href ./ ✅ Succeeded 3m 31s View ↗
nx build api -c=production --prod ✅ Succeeded 1m 10s View ↗
nx build desktop-ui-lib --configuration=develop... ✅ Succeeded 30s View ↗
nx build desktop-ui-lib --configuration=production ✅ Succeeded 28s View ↗
Additional runs (56) ✅ Succeeded ... View ↗

☁️ Nx Cloud last updated this comment at 2025-02-24 10:34:12 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