Skip to content

BUG 4334 #1599

Open
sumanvpacewisdom wants to merge 1 commit intodevelopfrom
SANITY_BUG_4334_LIST_COUNT_NOT_MATCHING
Open

BUG 4334 #1599
sumanvpacewisdom wants to merge 1 commit intodevelopfrom
SANITY_BUG_4334_LIST_COUNT_NOT_MATCHING

Conversation

@sumanvpacewisdom
Copy link
Collaborator

@sumanvpacewisdom sumanvpacewisdom commented Feb 27, 2026

Refactor query handling in mentorExtension.js and userExtension.js to improve filter logic and pagination defaults. Enhance mentees.js and mentors.js by streamlining connection details retrieval and ensuring consistent handling of connected entities. This update improves code clarity and maintains uniformity across services.

Release Notes

  • Query Refactoring: Updated filter handling in mentorExtension.js to support reassignment of filter clauses with proper AND prefixing
  • Pagination Improvements: Modified userExtension.js getAllUsers to implement smart pagination defaults—when IDs are provided, limit matches ID count; otherwise defaults to 5000; supports "select_all" flow for comprehensive queries
  • Mentees Service: Consolidated validation and data preparation logic to early execution, updated connected mentees path with select_all flag support, removed redundant defaults/validation block
  • Mentors Service: Enhanced connected mentors retrieval to use filteredQuery, improved empty state messaging, added tenantCode parameter to connection details calls, conditional count assignment from connectionDetails

Contributor Statistics

Author Lines Added Lines Removed Total
sumanvpacewisdom 43 40 83

… improve filter logic and pagination defaults. Enhance mentees.js and mentors.js by streamlining connection details retrieval and ensuring consistent handling of connected entities. This update improves code clarity and maintains uniformity across services.
@coderabbitai
Copy link

coderabbitai bot commented Feb 27, 2026

Walkthrough

Changes unify query validation and paging logic across mentee/mentor service layers, moving critical setup earlier in execution flow. Database queries updated for flexible pagination defaults. Variable reassignment enabled in mentorExtension. No public API signatures altered.

Changes

Cohort / File(s) Summary
Database Query Updates
src/database/queries/mentorExtension.js, src/database/queries/userExtension.js
mentorExtension: variable declaration changed from const to let to permit reassignment. userExtension: pagination defaults in getAllUsers modified—when no page/limit provided, offset defaults to 0 and limit becomes ids.length (if ids non-empty) or 5000 (fallback), enabling flexible all-select behavior.
Service Layer Refactoring
src/services/mentees.js, src/services/mentors.js
mentees.js: validation/data preparation moved earlier in function; connected mentees path refactored to use filteredQuery and nullify paging when select\_all flag true; duplicated validation block removed. mentors.js: connected mentors path updated to use filteredQuery instead of connectedQuery; paging nullified when connections exist; count tracking via connectedMentorsCount introduced; messaging adjusted for mentor-specific responses.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Suggested reviewers

  • nevil-mathew

Poem

🐰 Hop hop, the filters now align,
Validation early, queries refined,
No more duplication in the flow,
Mentees and mentors brightly glow!
With flexible paging, all set free—
Code hops onward gracefully! 🌟

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'BUG 4334' is vague and does not clearly describe the actual changes made in the pull request, which involve refactoring query handling and pagination logic across multiple services. Provide a more descriptive title that summarizes the main change, such as 'Refactor query filtering and pagination defaults in mentees and mentors services' or 'Fix list count inconsistency by improving query filter and pagination logic'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch SANITY_BUG_4334_LIST_COUNT_NOT_MATCHING

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/database/queries/userExtension.js`:
- Around line 574-577: When the no-pagination branch sets replacements.offset =
0 and replacements.limit = ids.length > 0 ? ids.length : 5000, the separate
count query can still return the full total and cause count/data length mismatch
for large datasets; modify the logic so the count reflects the applied limit by
either (a) passing the same replacements.limit into the count SQL and using
LEAST(total_count, :limit) in the COUNT query, or (b) after running the full
count, clamp the returned count to replacements.limit (e.g., count =
Math.min(count, replacements.limit)); update the code that builds/executes the
count query to consume this limit and reference the variables
replacements.limit, replacements.offset, ids and the select_all/no-pagination
branch to ensure both data and count use the same effective limit.

In `@src/services/mentees.js`:
- Around line 1529-1534: The error response for the defaults.tenantCode check
uses the wrong message key 'DEFAULT_ORG_CODE_NOT_SET'; update the
responses.failureResponse call inside the defaults.tenantCode guard to use the
tenant-specific message key (e.g., 'DEFAULT_TENANT_CODE_NOT_SET') so the API
returns the correct tenant-related error; ensure you only change the message
string in the block that checks defaults.tenantCode and run/update any related
tests or message lookups that expect the tenant key.

In `@src/services/mentors.js`:
- Around line 1410-1417: When you push userId into connectedMentorsIds you must
also ensure connectedMentorsCount (and ultimately extensionDetails.count) stays
consistent with the updated array: instead of blindly assigning
connectedMentorsCount = connectionDetails.count, compute the count from the
updated set (e.g., derive it from connectedMentorsIds.length or take the max of
connectionDetails.count and connectedMentorsIds.length) so count >= data.length;
update the assignment that sets connectedMentorsCount/extensionDetails.count
(references: connectedMentorsIds, connectedMentorsCount, connectionDetails,
extensionDetails.count, userId) accordingly.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 58b9d33 and 7773099.

📒 Files selected for processing (4)
  • src/database/queries/mentorExtension.js
  • src/database/queries/userExtension.js
  • src/services/mentees.js
  • src/services/mentors.js

Comment on lines +574 to 577
// No pagination: return all provided IDs (e.g. select_all=true flow)
replacements.offset = 0
replacements.limit = 5 // Default limit
replacements.limit = ids.length > 0 ? ids.length : 5000
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

No-pagination path can still return mismatched count vs data.length.

When pagination is omitted and ids is empty, Line 576 caps results at 5000, but the count query still returns the full total. This can reintroduce list/count mismatch for large datasets.

As per coding guidelines src/database/queries/**: review queries for correctness/performance.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/database/queries/userExtension.js` around lines 574 - 577, When the
no-pagination branch sets replacements.offset = 0 and replacements.limit =
ids.length > 0 ? ids.length : 5000, the separate count query can still return
the full total and cause count/data length mismatch for large datasets; modify
the logic so the count reflects the applied limit by either (a) passing the same
replacements.limit into the count SQL and using LEAST(total_count, :limit) in
the COUNT query, or (b) after running the full count, clamp the returned count
to replacements.limit (e.g., count = Math.min(count, replacements.limit));
update the code that builds/executes the count query to consume this limit and
reference the variables replacements.limit, replacements.offset, ids and the
select_all/no-pagination branch to ensure both data and count use the same
effective limit.

Comment on lines +1529 to +1534
if (!defaults.tenantCode)
return responses.failureResponse({
message: 'DEFAULT_ORG_CODE_NOT_SET',
statusCode: httpStatusCode.bad_request,
responseCode: 'CLIENT_ERROR',
})
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix tenant validation error message key.

Line 1531 returns DEFAULT_ORG_CODE_NOT_SET for a missing tenant default. This should use the tenant-specific message to avoid misleading API responses.

Proposed patch
 if (!defaults.tenantCode)
   return responses.failureResponse({
-    message: 'DEFAULT_ORG_CODE_NOT_SET',
+    message: 'DEFAULT_TENANT_CODE_NOT_SET',
     statusCode: httpStatusCode.bad_request,
     responseCode: 'CLIENT_ERROR',
   })

As per coding guidelines src/services/**: check core business logic for correctness and edge cases.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!defaults.tenantCode)
return responses.failureResponse({
message: 'DEFAULT_ORG_CODE_NOT_SET',
statusCode: httpStatusCode.bad_request,
responseCode: 'CLIENT_ERROR',
})
if (!defaults.tenantCode)
return responses.failureResponse({
message: 'DEFAULT_TENANT_CODE_NOT_SET',
statusCode: httpStatusCode.bad_request,
responseCode: 'CLIENT_ERROR',
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/services/mentees.js` around lines 1529 - 1534, The error response for the
defaults.tenantCode check uses the wrong message key 'DEFAULT_ORG_CODE_NOT_SET';
update the responses.failureResponse call inside the defaults.tenantCode guard
to use the tenant-specific message key (e.g., 'DEFAULT_TENANT_CODE_NOT_SET') so
the API returns the correct tenant-related error; ensure you only change the
message string in the block that checks defaults.tenantCode and run/update any
related tests or message lookups that expect the tenant key.

Comment on lines 1410 to +1417
if (!connectedMentorsIds.includes(userId)) {
connectedMentorsIds.push(userId)
}
}

// If there are no connected mentees, short-circuit and return empty
if (typeof connectionDetails?.count === 'number') {
connectedMentorsCount = connectionDetails.count
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Connected mentor count can become inconsistent after self-inclusion.

You add userId into connectedMentorsIds (when missing), but later Line 1578 sets extensionDetails.count from connectionDetails.count without adjusting for that added record. This can produce count < data.length.

Proposed patch
 				if (connectionDetails?.data?.length > 0) {
 					pageNo = null
 					pageSize = null
 					connectedMentorsIds = connectionDetails.data.map((item) => item.user_id)
+					if (typeof connectionDetails?.count === 'number') {
+						connectedMentorsCount = connectionDetails.count
+					}
 					if (!connectedMentorsIds.includes(userId)) {
 						connectedMentorsIds.push(userId)
+						if (typeof connectedMentorsCount === 'number') {
+							connectedMentorsCount += 1
+						}
 					}
 				}
-
-				if (typeof connectionDetails?.count === 'number') {
-					connectedMentorsCount = connectionDetails.count
-				}

As per coding guidelines src/services/**: check core business logic for correctness and edge cases.

Also applies to: 1577-1579

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/services/mentors.js` around lines 1410 - 1417, When you push userId into
connectedMentorsIds you must also ensure connectedMentorsCount (and ultimately
extensionDetails.count) stays consistent with the updated array: instead of
blindly assigning connectedMentorsCount = connectionDetails.count, compute the
count from the updated set (e.g., derive it from connectedMentorsIds.length or
take the max of connectionDetails.count and connectedMentorsIds.length) so count
>= data.length; update the assignment that sets
connectedMentorsCount/extensionDetails.count (references: connectedMentorsIds,
connectedMentorsCount, connectionDetails, extensionDetails.count, userId)
accordingly.

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