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

feat(j-s): User National Id #17976

Merged
merged 7 commits into from
Feb 21, 2025
Merged

feat(j-s): User National Id #17976

merged 7 commits into from
Feb 21, 2025

Conversation

gudjong
Copy link
Member

@gudjong gudjong commented Feb 15, 2025

User National Id

Taka unique constraint af kennitölu og skila lista af notendum úr bakenda

What

  • Removes the unique constraint from user national ids.
  • Returns a list of users from the backend rather than a single user.
  • Uses the first returned user from the backend everywhere.

Remaining work

  • Sync with LÖKE on how to select the correct prosecutors office when creating new cases from LÖKE.
  • Modify event logs so we know the event's user institution.
  • Support multiple users in client login.
  • Stop allowing user institution changes.

Why

  • This is the first in a series of PRs to support multiple users per national id.

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features

    • User lookups now return multiple results, enabling the system to handle scenarios where several matches exist for a national identifier.
    • Updated user identification supports shared national identifiers across institutions with a composite uniqueness rule.
  • Refactor

    • Enhanced error handling and flow clarity in authentication and case management, ensuring more robust operations when processing user-related requests.

@gudjong gudjong requested a review from a team as a code owner February 15, 2025 13:05
Copy link

nx-cloud bot commented Feb 15, 2025

View your CI Pipeline Execution ↗ for commit f042d2f.

Command Status Duration Result
nx run-many --projects judicial-system-backend ... ✅ Succeeded 8m 32s View ↗
nx run-many --target=build --projects=judicial-... ✅ Succeeded 22s View ↗
nx run-many --target=build --projects=judicial-... ✅ Succeeded 16s View ↗
nx run-many --projects judicial-system-api --ta... ✅ Succeeded 6s View ↗
nx run-many --target=lint --projects=judicial-s... ✅ Succeeded 8s View ↗
nx run-many --target=codegen/frontend-client --... ✅ Succeeded 13s View ↗
nx run-many --target=codegen/backend-schema --a... ✅ Succeeded 35s View ↗

☁️ Nx Cloud last updated this comment at 2025-02-21 08:47:37 UTC

Copy link
Contributor

coderabbitai bot commented Feb 15, 2025

Walkthrough

This pull request updates multiple modules to support handling user queries that return arrays rather than a single user object. In the authentication, case, and user modules, methods and tests have been refactored to retrieve and process user data as arrays. Additionally, the database migration adjusts the unique constraint on national IDs by including the institution ID. These changes improve the clarity of error handling and data processing without altering the core business logic.

Changes

File(s) Change Summary
apps/judicial-system/api/src/app/modules/auth/auth.service.ts Updated findUser to assign the JSON result to a users array and return its first element; refined error handling in findDefender using an explicit block.
apps/judicial-system/backend/migrations/20250214111730-update-user.js Modified migration: in up, removed the unique constraint on national_id and added a composite unique constraint (national_id + institution_id); down method reverts these changes.
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts In the create method, replaced the single creator assignment with retrieving an array of users and selecting the first user to support multiple results.
apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/create.spec.ts
apps/judicial-system/backend/src/app/modules/user/test/getByNationalId.spec.ts
Updated test mocks to return arrays (instead of single user objects) and adjusted assertions for methods that now return arrays rather than individual user objects.
apps/judicial-system/backend/src/app/modules/user/user.controller.ts
apps/judicial-system/backend/src/app/modules/user/user.model.ts
apps/judicial-system/backend/src/app/modules/user/user.service.ts
Changed getByNationalId in the controller to return an array of users; removed the unique constraint from the nationalId property in the user model; refactored findByNationalId in the service to return an array and use findAll for database queries.

Sequence Diagram(s)

sequenceDiagram
    participant Auth as AuthService
    participant API as External API
    Auth->>API: Call for user data (findUser)
    API-->>Auth: Return JSON array of users
    Auth->>Auth: Select first user from array
    Auth-->>Caller: Return selected user
Loading
sequenceDiagram
    participant C as UserController
    participant S as UserService
    participant DB as Database
    C->>S: getByNationalId(nationalId)
    S->>DB: findAll({nationalId})
    DB-->>S: Return array of users
    S-->>C: Return user array
Loading

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • oddsson
  • thorhildurt

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 71dc9e4 and f042d2f.

📒 Files selected for processing (1)
  • apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/create.spec.ts (10 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/create.spec.ts

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.

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

🔭 Outside diff range comments (2)
apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/create.spec.ts (1)

161-175: 🛠️ Refactor suggestion

Add test case for empty array scenario.

The "user not found" test currently checks for undefined, but with the new array-based implementation, we should also verify the behavior when an empty array is returned.

Apply this diff to add the test case:

 describe('creating user not found', () => {
+  describe('when undefined is returned', () => {
     let then: Then
 
     beforeEach(async () => {
       const mockFindByNationalId = mockUserService.findByNationalId as jest.Mock
       mockFindByNationalId.mockResolvedValueOnce(undefined)
 
       then = await givenWhenThen(caseToCreate)
     })
 
     it('should throw BadRequestException', () => {
       expect(then.error).toBeInstanceOf(BadRequestException)
       expect(then.error.message).toBe('Creating user not found')
     })
+  })
+
+  describe('when empty array is returned', () => {
+    let then: Then
+
+    beforeEach(async () => {
+      const mockFindByNationalId = mockUserService.findByNationalId as jest.Mock
+      mockFindByNationalId.mockResolvedValueOnce([])
+
+      then = await givenWhenThen(caseToCreate)
+    })
+
+    it('should throw BadRequestException', () => {
+      expect(then.error).toBeInstanceOf(BadRequestException)
+      expect(then.error.message).toBe('Creating user not found')
+    })
+  })
 })
apps/judicial-system/backend/src/app/modules/user/test/getByNationalId.spec.ts (1)

14-17: 🛠️ Refactor suggestion

Update interface to reflect array return type.

The Then interface should be updated to expect an array of users.

 interface Then {
-  result: User
+  result: User[]
   error: Error
 }
🧹 Nitpick comments (9)
apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/create.spec.ts (3)

116-116: Consider adding test coverage for multiple users.

While the mock now correctly returns an array of users, the test only verifies the behavior with a single user in the array. Given that the system now supports multiple users with the same national ID, consider adding test cases that verify the behavior when multiple users are returned.


177-202: Update test description for clarity.

The test description "creating user not from prosecution office" could be more specific about which user from the array is being validated.

Apply this diff to improve the test description:

-describe('creating user not from prosecution office', () => {
+describe('first user not from prosecution office', () => {

288-291: Consider consolidating error test cases.

The error test cases (case creation, defendant creation, and case lookup failures) follow the same pattern of mocking the user service to return an array. Consider using a shared setup to reduce code duplication.

Apply this diff to consolidate the setup:

+const createUserMock = (user: User) => {
+  const mockFindByNationalId = mockUserService.findByNationalId as jest.Mock
+  mockFindByNationalId.mockResolvedValueOnce([user])
+  return mockFindByNationalId
+}

 describe('case creation fails', () => {
   // ... user definition ...
   let then: Then

   beforeEach(async () => {
-    const mockFindByNationalId = mockUserService.findByNationalId as jest.Mock
-    mockFindByNationalId.mockResolvedValueOnce([user])
+    createUserMock(user)
     then = await givenWhenThen(caseToCreate)
   })
   // ... rest of the test ...
 })

Also applies to: 341-344, 367-372, 395-403

apps/judicial-system/backend/migrations/20250214111730-update-user.js (1)

1-1: Remove redundant 'use strict' directive.

JavaScript modules are automatically in strict mode, making this directive unnecessary.

-'use strict'
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

apps/judicial-system/backend/src/app/modules/user/user.model.ts (1)

41-42: Update API documentation to reflect array return type.

The @ApiProperty decorator should be updated to indicate that multiple users can share the same national ID.

-  @ApiProperty({ type: String })
+  @ApiProperty({ type: String, description: 'National ID (can be shared by multiple users)' })
apps/judicial-system/backend/src/app/modules/user/user.controller.ts (1)

95-98: Update API documentation for array return type.

The API documentation needs to be updated to reflect that the endpoint now returns an array of users.

   @ApiOkResponse({
     type: User,
+    isArray: true,
-    description: 'Gets an existing user by national id',
+    description: 'Gets all users with the specified national id',
   })
apps/judicial-system/backend/src/app/modules/user/test/getByNationalId.spec.ts (1)

72-91: Add test cases for edge scenarios.

Consider adding test cases for:

  • Empty array when no users found
  • Array with more than two users
  • Error handling for invalid national IDs
apps/judicial-system/backend/src/app/modules/user/user.service.ts (1)

57-95: LGTM! Method signature change aligns with PR objectives.

The changes correctly implement the return of multiple users while maintaining backward compatibility by wrapping single users in arrays.

Consider improving error handling and admin user logic.

The error message could be more specific about handling multiple users, and the admin user logic could be more explicit about returning a single-element array.

Apply this diff to improve clarity:

  async findByNationalId(nationalId: string): Promise<User[]> {
    // First check if the user is an admin
    try {
      const admin = this.config.adminUsers.find(
        (user: { nationalId: string }) => user.nationalId === nationalId,
      )

      if (admin) {
+       // Return a single-element array for admin users
+       // This maintains consistency with the multiple users support
        return [
          {
            created: nowFactory(),
            modified: nowFactory(),
            mobileNumber: '',
            email: '',
            role: UserRole.ADMIN,
            active: true,
            canConfirmIndictment: false,
            ...admin,
          } as User,
        ]
      }
    } catch (error) {
      // Tolerate failure, but log error
      this.logger.error('Failed to parse admin users', { error })
    }

    const users = await this.userModel.findAll({
      where: { nationalId, active: true },
      include: [{ model: Institution, as: 'institution' }],
    })

    if (!users || users.length === 0) {
-     throw new NotFoundException('User does not exist')
+     throw new NotFoundException('No active users found with the provided national ID')
    }

    return users
  }
apps/judicial-system/api/src/app/modules/auth/auth.service.ts (1)

54-107:

❓ Verification inconclusive

Consider aligning with multiple users approach.

Since the system is being updated to support multiple users per national ID, this method might need similar changes to handle multiple defenders.

Consider:

  1. Updating the method to handle an array of defenders.
  2. Adding selection criteria for defenders based on institution.
  3. Updating the return type to Promise<User[]>.

Let's verify if the defender endpoint has been updated to return multiple users:


🏁 Script executed:

#!/bin/bash
# Search for defender endpoint implementation
rg -A 10 "limitedAccess/defender.*nationalId" --type ts

Length of output: 1122


Action Required: Update findDefender to Support Multiple Defenders

The current implementation in apps/judicial-system/api/src/app/modules/auth/auth.service.ts still treats the defender as a single user. Since the system is evolving to support multiple users per national ID, please consider refactoring this method as follows:

  • Return Type: Change the return type to Promise<User[]> instead of a single User.
  • Response Handling: Process the JSON response as an array of defenders.
  • Selection Criteria: Implement appropriate selection or filtering (e.g., based on institution) to determine which defender(s) to use when multiple are available.

Our verification (via the search for the defender endpoint) indicates that the endpoint continues to return a single result. Further modifications may be necessary once the backend supports multiple defenders.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b274eca and 72d3f6a.

📒 Files selected for processing (9)
  • apps/judicial-system/api/src/app/modules/auth/auth.service.ts (2 hunks)
  • apps/judicial-system/backend/migrations/20250214111730-update-user.js (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/pdf.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/create.spec.ts (7 hunks)
  • apps/judicial-system/backend/src/app/modules/user/test/getByNationalId.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/user/user.controller.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/user/user.model.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/user/user.service.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`apps/**/*`: "Confirm that the code adheres to the following...

apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
  • apps/judicial-system/backend/migrations/20250214111730-update-user.js
  • apps/judicial-system/backend/src/app/modules/user/user.model.ts
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts
  • apps/judicial-system/backend/src/app/modules/user/user.controller.ts
  • apps/judicial-system/backend/src/app/modules/user/test/getByNationalId.spec.ts
  • apps/judicial-system/api/src/app/modules/auth/auth.service.ts
  • apps/judicial-system/backend/src/app/modules/user/user.service.ts
  • apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/create.spec.ts
  • apps/judicial-system/backend/src/app/modules/case/pdf.service.ts
🪛 Biome (1.9.4)
apps/judicial-system/backend/migrations/20250214111730-update-user.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

🔇 Additional comments (5)
apps/judicial-system/backend/src/app/modules/case/test/internalCaseController/create.spec.ts (1)

247-253: LGTM!

The test for prosecutor representative creating indictment case correctly handles the array-based user response and verifies the appropriate case creation.

apps/judicial-system/backend/migrations/20250214111730-update-user.js (1)

4-6: LGTM! Migration correctly removes the unique constraint.

The up method properly removes the unique constraint on the national_id column, aligning with the PR objective to support multiple users with the same national ID.

apps/judicial-system/backend/src/app/modules/user/user.model.ts (1)

40-42: LGTM! Model changes align with database migration.

The removal of the unique constraint from the nationalId column correctly implements the database schema change.

apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1)

334-344: LGTM! Well-structured handling of multiple users.

The changes correctly handle the array response with appropriate error checking and include a clear TODO about future improvements.

apps/judicial-system/api/src/app/modules/auth/auth.service.ts (1)

68-70: LGTM! Improved error handling structure.

The explicit else block enhances code readability and maintainability.

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 (1)
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1)

342-342: Track the TODO comment in the issue tracker.

The TODO comment indicates a dependency on synchronization with LÖKE for user selection.

Would you like me to create an issue to track this TODO and the implementation of the user selection strategy? The issue can include:

  • Requirement to sync with LÖKE
  • Implementation of user selection criteria
  • Testing scenarios for multiple users
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 72d3f6a and ef920c4.

📒 Files selected for processing (1)
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`apps/**/*`: "Confirm that the code adheres to the following...

apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: tests (judicial-system-backend)

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 (1)
apps/judicial-system/backend/migrations/20250214111730-update-user.js (1)

1-1: Remove redundant 'use strict' directive.

JavaScript modules are automatically in strict mode, making this directive unnecessary.

-'use strict'
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ef920c4 and a128e14.

📒 Files selected for processing (1)
  • apps/judicial-system/backend/migrations/20250214111730-update-user.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`apps/**/*`: "Confirm that the code adheres to the following...

apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
  • apps/judicial-system/backend/migrations/20250214111730-update-user.js
🪛 Biome (1.9.4)
apps/judicial-system/backend/migrations/20250214111730-update-user.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

🔇 Additional comments (1)
apps/judicial-system/backend/migrations/20250214111730-update-user.js (1)

4-13:

❓ Verification inconclusive

LGTM! Migration aligns with PR objectives.

The migration correctly implements the required changes to support multiple users with the same national ID while maintaining uniqueness per institution.

Let's verify the constraint changes:


🏁 Script executed:

#!/bin/bash
# Description: Verify constraint changes in the database schema

# Search for any remaining unique constraints on national_id
rg -A 5 "national_id.*unique" apps/judicial-system/backend/src/

Length of output: 65


LGTM! Migration aligns with PR objectives.

The migration correctly removes the existing unique constraint on "national_id" and adds a composite unique constraint ("unique_national_id_per_institution") to ensure uniqueness per institution. Although the earlier grep in the apps/judicial-system/backend/src/ directory showed no trace of a unique constraint on "national_id", this check did not cover the entire codebase. Please manually verify that:

  • The legacy constraint "user_national_id_key" does not appear anywhere else in the repository.
  • The new composite constraint "unique_national_id_per_institution" is properly applied without conflict.

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)
apps/judicial-system/backend/migrations/20250214111730-update-user.js (1)

15-27: ⚠️ Potential issue

Fix redundant constraints in down migration.

The down migration has redundant constraints:

  1. It attempts to add a unique constraint on 'national_id' while also having a composite unique constraint
  2. Having both constraints is redundant and potentially conflicting

Apply this diff:

  down(queryInterface, Sequelize) {
    return Promise.all([
      queryInterface.changeColumn('user', 'national_id', {
        type: Sequelize.STRING,
        unique: true,
        allowNull: false,
      }),
-     queryInterface.removeConstraint(
-       'user',
-       'unique_national_id_per_institution',
-     ),
    ])
  },
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1)

338-339: 🛠️ Refactor suggestion

Consider implementing a more robust user selection strategy.

The current implementation arbitrarily selects the first prosecution user without specific criteria. This could lead to incorrect prosecutor selection when multiple users are associated with the same national ID.

Consider implementing a selection strategy based on specific criteria, such as:

  • User's institution/office
  • User's role or seniority
  • Active status
  • Case load
-    // TODO: Sync with LÖKE so we can select the correct user
-    const creator = users?.find((user) => isProsecutionUser(user))
+    const creator = await this.selectAppropriateUser(users, caseToCreate)

Add a new method to handle user selection:

private async selectAppropriateUser(users: User[], caseToCreate: InternalCreateCaseDto): Promise<User> {
  // Implement selection logic based on business requirements
  // Example: Select user by institution
  const appropriateUser = users.find(user => 
    user.institution?.id === caseToCreate.prosecutorsOfficeId
  );
  return appropriateUser ?? users[0]; // Fallback to first user if no match
}
🧹 Nitpick comments (1)
apps/judicial-system/backend/migrations/20250214111730-update-user.js (1)

1-2: Remove redundant 'use strict' directive.

The 'use strict' directive is redundant as JavaScript modules are automatically in strict mode.

Apply this diff:

-'use strict'
-
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a128e14 and 71dc9e4.

📒 Files selected for processing (3)
  • apps/judicial-system/api/src/app/modules/auth/auth.service.ts (2 hunks)
  • apps/judicial-system/backend/migrations/20250214111730-update-user.js (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/api/src/app/modules/auth/auth.service.ts
🧰 Additional context used
📓 Path-based instructions (1)
`apps/**/*`: "Confirm that the code adheres to the following...

apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
  • apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts
  • apps/judicial-system/backend/migrations/20250214111730-update-user.js
🪛 Biome (1.9.4)
apps/judicial-system/backend/migrations/20250214111730-update-user.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: tests (judicial-system-backend)
🔇 Additional comments (3)
apps/judicial-system/backend/migrations/20250214111730-update-user.js (1)

4-13: LGTM! The up migration correctly implements the national ID constraint changes.

The migration properly removes the unique constraint on 'national_id' and adds a composite unique constraint on 'national_id' and 'institution_id', which aligns with the PR objective to support multiple users with the same national ID.

apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts (2)

334-336: LGTM! User retrieval now supports multiple users.

The code correctly handles the new array return type from findByNationalId, aligning with the PR objective to support multiple users with the same national ID.


341-345: LGTM! Error handling is clear and accurate.

The error message accurately reflects the validation requirements for creating a case, checking both user existence and prosecution role.

@gudjong gudjong enabled auto-merge February 20, 2025 14:35
@gudjong gudjong added this pull request to the merge queue Feb 21, 2025
Merged via the queue into main with commit b769b1c Feb 21, 2025
31 checks passed
@gudjong gudjong deleted the j-s/user-noational-id-not-unique branch February 21, 2025 08:57
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