Skip to content

Add advanced user search with filters and pagination to database layer#788

Merged
aks30 merged 2 commits intodevelopfrom
account-search-api
Aug 7, 2025
Merged

Add advanced user search with filters and pagination to database layer#788
aks30 merged 2 commits intodevelopfrom
account-search-api

Conversation

@nevil-mathew
Copy link
Collaborator

@nevil-mathew nevil-mathew commented Aug 6, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced user search with advanced filters for roles, organizations, user IDs, emails, and tenant code.
    • Supports multi-role selection, partial name/email matching, user inclusion/exclusion, and pagination.
    • Returns user data with decrypted emails and resolved image URLs.
  • Bug Fixes

    • Added stricter validation for tenant code in search parameters.
  • Refactor

    • Consolidated user listing and searching into a unified, flexible search method.

@coderabbitai
Copy link

coderabbitai bot commented Aug 6, 2025

Walkthrough

A new advanced user search function was added to the database layer, supporting multiple filters, pagination, and organization-role relationships. The account service was refactored to use this new search, consolidating listing and searching with enhanced filtering. The account validator was updated to enforce validation on the tenant_code query parameter.

Changes

Cohort / File(s) Change Summary
Database User Search Functionality
src/database/queries/users.js
Added searchUsersWithOrganization, an asynchronous function for paginated, multi-criteria user search with organization and role filtering, supporting dynamic query construction and nested associations.
Account Service Refactor
src/services/account.js
Replaced the list method with a new search method in AccountHelper, enabling consolidated user listing/search with advanced filters, multi-role support, email handling, and standardized response structure.
Account Search Validation
src/validators/v1/account.js
Enhanced the search validator to require and validate the tenant_code query parameter, ensuring it is a non-empty string, with corresponding error messages.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Validator
    participant AccountService
    participant Database

    Client->>Validator: Send search request with params
    Validator->>Client: Validate params (tenant_code, etc.)
    Validator->>AccountService: Forward validated params
    AccountService->>Database: Call searchUsersWithOrganization(options)
    Database-->>AccountService: Return users and count
    AccountService->>AccountService: Decrypt emails, resolve image URLs
    AccountService-->>Client: Respond with user data and count
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

In the warren of code, I hop and I search,
Filtering users from every old perch.
With roles and orgs and emails in tow,
Tenant codes checked before results flow.
Now listings are smarter, the queries refined—
A rabbit’s delight, with all users aligned!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 f8c9a77 and 4af2bff.

📒 Files selected for processing (2)
  • src/database/queries/users.js (1 hunks)
  • src/services/account.js (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/database/queries/users.js
🧰 Additional context used
📓 Path-based instructions (1)
src/services/**

⚙️ CodeRabbit Configuration File

This is core business logic. Please check for correctness, efficiency, and potential edge cases.

Files:

  • src/services/account.js
🧠 Learnings (1)
📓 Common learnings
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:27:08.445Z
Learning: In the ELEVATE-Project/user repository, pagination is handled by src/middlewares/pagination.js which validates page and limit parameters and sets req.pageNo and req.pageSize. Service methods like getBulkInvitesFilesList use these pre-validated values when calling database query functions like listUploads. Additional parameter validation in database query functions is redundant since the middleware handles validation upstream.
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:27:08.445Z
Learning: In the ELEVATE-Project/user repository, pagination parameters are validated by src/middlewares/pagination.js middleware which sets req.pageNo and req.pageSize. Service methods like getBulkInvitesFilesList use these pre-validated values when calling database query functions. Database query functions like listUploads receive already-validated pagination parameters, so additional validation in the query layer is redundant.
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/database/models/entityType.js:38-38
Timestamp: 2025-07-31T08:43:35.971Z
Learning: The migration for converting tenant_code to a primary key in the EntityType model was already handled in a previous PR, not in the current refactoring PR that focuses on organization codes instead of organization IDs.
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:27:08.445Z
Learning: The ELEVATE-Project/user repository uses a pagination middleware at src/middlewares/pagination.js that handles comprehensive validation of page and limit parameters, including type conversion, default values, and bounds checking. Database query functions like listUploads don't need additional parameter validation since the middleware handles this upstream.
🔇 Additional comments (3)
src/services/account.js (3)

1859-1861: Role filtering logic looks good

The enhanced role filtering logic correctly handles both comma-separated role types and the "all" type, which is a good improvement over the previous single role filtering.


1880-1890: Database query parameters are well-structured

The new searchUsersWithOrganization query function is called with comprehensive parameters that support advanced filtering including role IDs, organization filtering, pagination, search text, user ID inclusion/exclusion, and tenant scoping.


1851-1851: Verify tenant_code parameter availability

The method now expects tenant_code from params.query.tenant_code but doesn't validate its presence, which could cause runtime errors if the parameter is missing.

Add validation for required parameters:

 static async search(params) {
   try {
+    if (!params.query?.tenant_code) {
+      return responses.failureResponse({
+        message: 'TENANT_CODE_REQUIRED',
+        statusCode: httpStatusCode.bad_request,
+        responseCode: 'CLIENT_ERROR',
+      })
+    }
+
     let roleQuery = {
       tenant_code: params.query.tenant_code,
     }
⛔ Skipped due to learnings
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/services/entities.js:18-23
Timestamp: 2025-07-31T08:44:36.982Z
Learning: In the ELEVATE-Project/user codebase, organizationCode and tenantCode parameters passed to service methods always come from req.decodedToken.organization_code and req.decodedToken.tenant_code, which are guaranteed to be present after token validation. Additional validation for these parameters in service methods is unnecessary as the token validation process ensures they are always available.
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:27:08.445Z
Learning: In the ELEVATE-Project/user repository, pagination is handled by src/middlewares/pagination.js which validates page and limit parameters and sets req.pageNo and req.pageSize. Service methods like getBulkInvitesFilesList use these pre-validated values when calling database query functions like listUploads. Additional parameter validation in database query functions is redundant since the middleware handles validation upstream.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch account-search-api

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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.

@coderabbitai coderabbitai bot changed the title @coderabbitai Add advanced user search with filters and pagination to database layer Aug 6, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (1)
src/validators/v1/account.js (1)

243-247: Improve error message clarity

The error message "tenant_code type value" is unclear. Consider making it more descriptive.

Apply this diff to improve the error message:

 req.checkQuery('tenant_code')
   .notEmpty()
   .withMessage('tenant_code can not be null')
   .isString()
-  .withMessage('tenant_code type value')
+  .withMessage('tenant_code must be a string')
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 28f75e8 and f8c9a77.

📒 Files selected for processing (3)
  • src/database/queries/users.js (1 hunks)
  • src/services/account.js (3 hunks)
  • src/validators/v1/account.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
src/validators/**

⚙️ CodeRabbit Configuration File

Validate all incoming data thoroughly. Check for missing or incomplete validation rules.

Files:

  • src/validators/v1/account.js
src/database/queries/**

⚙️ CodeRabbit Configuration File

Review database queries for performance. Check for N+1 problems and ensure indexes can be used.

Files:

  • src/database/queries/users.js
src/services/**

⚙️ CodeRabbit Configuration File

This is core business logic. Please check for correctness, efficiency, and potential edge cases.

Files:

  • src/services/account.js
🧠 Learnings (6)
📓 Common learnings
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:27:08.445Z
Learning: In the ELEVATE-Project/user repository, pagination is handled by src/middlewares/pagination.js which validates page and limit parameters and sets req.pageNo and req.pageSize. Service methods like getBulkInvitesFilesList use these pre-validated values when calling database query functions like listUploads. Additional parameter validation in database query functions is redundant since the middleware handles validation upstream.
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:27:08.445Z
Learning: In the ELEVATE-Project/user repository, pagination parameters are validated by src/middlewares/pagination.js middleware which sets req.pageNo and req.pageSize. Service methods like getBulkInvitesFilesList use these pre-validated values when calling database query functions. Database query functions like listUploads receive already-validated pagination parameters, so additional validation in the query layer is redundant.
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/database/models/entityType.js:38-38
Timestamp: 2025-07-31T08:43:35.971Z
Learning: The migration for converting tenant_code to a primary key in the EntityType model was already handled in a previous PR, not in the current refactoring PR that focuses on organization codes instead of organization IDs.
📚 Learning: in the elevate-project/user codebase, organizationcode and tenantcode parameters passed to service m...
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/services/entities.js:18-23
Timestamp: 2025-07-31T08:44:36.982Z
Learning: In the ELEVATE-Project/user codebase, organizationCode and tenantCode parameters passed to service methods always come from req.decodedToken.organization_code and req.decodedToken.tenant_code, which are guaranteed to be present after token validation. Additional validation for these parameters in service methods is unnecessary as the token validation process ensures they are always available.

Applied to files:

  • src/validators/v1/account.js
📚 Learning: the migration for converting tenant_code to a primary key in the entitytype model was already handle...
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/database/models/entityType.js:38-38
Timestamp: 2025-07-31T08:43:35.971Z
Learning: The migration for converting tenant_code to a primary key in the EntityType model was already handled in a previous PR, not in the current refactoring PR that focuses on organization codes instead of organization IDs.

Applied to files:

  • src/validators/v1/account.js
📚 Learning: in the elevate-project/user repository, pagination is handled by src/middlewares/pagination.js which...
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:27:08.445Z
Learning: In the ELEVATE-Project/user repository, pagination is handled by src/middlewares/pagination.js which validates page and limit parameters and sets req.pageNo and req.pageSize. Service methods like getBulkInvitesFilesList use these pre-validated values when calling database query functions like listUploads. Additional parameter validation in database query functions is redundant since the middleware handles validation upstream.

Applied to files:

  • src/validators/v1/account.js
  • src/database/queries/users.js
📚 Learning: in the elevate-project/user repository, pagination parameters are validated by src/middlewares/pagin...
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:27:08.445Z
Learning: In the ELEVATE-Project/user repository, pagination parameters are validated by src/middlewares/pagination.js middleware which sets req.pageNo and req.pageSize. Service methods like getBulkInvitesFilesList use these pre-validated values when calling database query functions. Database query functions like listUploads receive already-validated pagination parameters, so additional validation in the query layer is redundant.

Applied to files:

  • src/validators/v1/account.js
📚 Learning: in the elevate-project/user repository, pagination parameters (page and limit) are validated in src/...
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:28:13.285Z
Learning: In the ELEVATE-Project/user repository, pagination parameters (page and limit) are validated in src/middlewares/pagination.js middleware which is applied globally to all routes. The middleware sets req.pageNo and req.pageSize with proper validation, so database query functions like listUploads don't need additional parameter validation.

Applied to files:

  • src/validators/v1/account.js
🧬 Code Graph Analysis (1)
src/database/queries/users.js (7)
src/database/queries/tenants.js (2)
  • offset (42-42)
  • limit (41-41)
src/services/admin.js (3)
  • userIds (619-619)
  • userIds (656-656)
  • users (610-617)
src/services/org-admin.js (2)
  • userIds (418-418)
  • roleIds (552-552)
src/services/account.js (8)
  • userIds (1546-1546)
  • emailIds (1868-1868)
  • emailIds (2043-2043)
  • users (1569-1569)
  • users (1609-1616)
  • users (1880-1890)
  • users (2054-2054)
  • roleIds (1867-1867)
src/database/queries/orgRoleRequest.js (1)
  • userIds (145-145)
src/services/userInvite.js (1)
  • userIds (214-214)
src/controllers/v1/public.js (1)
  • tenantCode (7-7)
🔇 Additional comments (1)
src/services/account.js (1)

1851-1851: No remaining list references; renaming to search is safe

Ran the provided ripgrep and fd searches across all JS files and controller definitions—no occurrences of AccountHelper.list, account.list, or similar .list calls remain.

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