Skip to content

Refactor mentees.js for enhanced query processing and validation - BUG 4416#1597

Open
sumanvpacewisdom wants to merge 1 commit intodevelopfrom
SANITY_BUG_4416_PWA_COUNT_ISSUE
Open

Refactor mentees.js for enhanced query processing and validation - BUG 4416#1597
sumanvpacewisdom wants to merge 1 commit intodevelopfrom
SANITY_BUG_4416_PWA_COUNT_ISSUE

Conversation

@sumanvpacewisdom
Copy link
Collaborator

@sumanvpacewisdom sumanvpacewisdom commented Feb 27, 2026

Refactor mentees.js to enhance query processing by integrating validation and filtering logic. This update ensures proper handling of tenant codes and improves the clarity of connected mentee retrieval.

Release Notes

  • Added early validation for defaults.tenantCode in MenteesHelper.list() to ensure tenant codes are properly validated before query processing
  • Introduced integration of entityTypeCache for Mentee extension model validation with utils.validateAndBuildFilters for creating filtered queries
  • Replaced connectedQuery with validated filteredQuery when retrieving connected mentees via connectionQueries.getConnectionsDetails()
  • Removed manual userId injection into connected mentees array and eliminated redundant validation blocks to consolidate validation logic upfront
  • Refactored query processing flow to perform entity-type validation and filtering at the beginning, improving clarity of connected-mentee retrieval

Contributors

Author Additions Deletions
sumanvpacewisdom 21 28

…tion and filtering logic. This update ensures proper handling of tenant codes and improves the clarity of connected mentee retrieval.
@coderabbitai
Copy link

coderabbitai bot commented Feb 27, 2026

Walkthrough

The mentees service refactors validation logic in the MenteesHelper.list method by moving tenant code and entity-type validation earlier in the flow. It consolidates duplicate validation checks, builds a filtered query upfront using validated data, and removes manual userId manipulation, reducing code redundancy.

Changes

Cohort / File(s) Summary
Validation Consolidation
src/services/mentees.js
Early validation of defaults.tenantCode with CLIENT_ERROR failure handling; retrieval of entityTypeCache validation data; buildFilters used to construct filteredQuery for connected mentees; eliminated redundant validation block and manual userId pushing into results.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • nevil-mathew

Poem

🐰 The validation hops up front, no need to wait,
Filters are built with such elegant state,
Redundant checks removed, the flow runs so clean,
Consolidation magic, the best we have seen!
thump thump

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main refactoring work: improving query processing and validation in mentees.js, and references the bug fix (BUG 4416) that motivated the change.
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_4416_PWA_COUNT_ISSUE

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/services/mentees.js`:
- Around line 1529-1534: The check for defaults.tenantCode returns a misleading
error key 'DEFAULT_ORG_CODE_NOT_SET'; update the responses.failureResponse call
in the block that validates defaults.tenantCode (where responses.failureResponse
is invoked with message: 'DEFAULT_ORG_CODE_NOT_SET') to use the correct
tenant-specific message key (e.g., 'DEFAULT_TENANT_CODE_NOT_SET' or the existing
tenant error constant from your error messages) while keeping the same
statusCode and responseCode; ensure you reference the tenant error constant if
available instead of a hard-coded string.
- Around line 1536-1547: The result of
entityTypeCache.getEntityTypesAndEntitiesWithCache (assigned to validationData)
can be an Error; before calling utils.validateAndBuildFilters you must guard
that validationData is not an Error. Add an explicit check after the
getEntityTypesAndEntitiesWithCache call (e.g., if (validationData instanceof
Error) { ... }) and handle it the same way other sections in this file do
(returning/propagating the error or logging and exiting) so that
utils.validateAndBuildFilters is only called with valid validation data.
- Around line 1528-1534: The list handler in src/services/mentees.js currently
calls getDefaults() and returns a hard failure if defaults.tenantCode is missing
even though defaults isn't used later; remove the unnecessary failure path by
either deleting the getDefaults() call entirely from the list flow or by making
the lookup non-blocking (e.g., catch errors and ignore missing tenantCode) so
the list function proceeds normally; update the code around getDefaults, the
conditional checking defaults.tenantCode, and any related
responses.failureResponse usage to ensure list continues without returning
DEFAULT_ORG_CODE_NOT_SET.

ℹ️ 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 d81e4d1.

📒 Files selected for processing (1)
  • src/services/mentees.js

Comment on lines +1528 to +1534
const defaults = await getDefaults()
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 | 🟠 Major

Avoid a hard failure on an unused defaults lookup

defaults is fetched and validated, but not used afterwards in list. This adds an unrelated failure path for Line 1504 endpoint behavior and can block mentee listing unnecessarily.

Proposed fix
-const defaults = await getDefaults()
-if (!defaults.tenantCode)
-	return responses.failureResponse({
-		message: 'DEFAULT_ORG_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 1528 - 1534, The list handler in
src/services/mentees.js currently calls getDefaults() and returns a hard failure
if defaults.tenantCode is missing even though defaults isn't used later; remove
the unnecessary failure path by either deleting the getDefaults() call entirely
from the list flow or by making the lookup non-blocking (e.g., catch errors and
ignore missing tenantCode) so the list function proceeds normally; update the
code around getDefaults, the conditional checking defaults.tenantCode, and any
related responses.failureResponse usage to ensure list continues without
returning DEFAULT_ORG_CODE_NOT_SET.

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

Use the correct tenant error message key

Line 1529 validates defaults.tenantCode, but Lines 1531-1534 return DEFAULT_ORG_CODE_NOT_SET. This returns a misleading client error for tenant misconfiguration.

Proposed fix
 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',
 	})
📝 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 check for
defaults.tenantCode returns a misleading error key 'DEFAULT_ORG_CODE_NOT_SET';
update the responses.failureResponse call in the block that validates
defaults.tenantCode (where responses.failureResponse is invoked with message:
'DEFAULT_ORG_CODE_NOT_SET') to use the correct tenant-specific message key
(e.g., 'DEFAULT_TENANT_CODE_NOT_SET' or the existing tenant error constant from
your error messages) while keeping the same statusCode and responseCode; ensure
you reference the tenant error constant if available instead of a hard-coded
string.

Comment on lines +1536 to +1547
let validationData = await entityTypeCache.getEntityTypesAndEntitiesWithCache(
{
status: common.ACTIVE_STATUS,
model_names: { [Op.overlap]: [userExtensionModelName] },
},
tenantCode,
organizationCode,
userExtensionModelName
)

let filteredQuery = utils.validateAndBuildFilters(query, validationData)

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

Guard entity-type cache failures before building filters

Line 1536 can return an Error object (pattern already handled elsewhere in this file), but Line 1546 immediately passes the result into validateAndBuildFilters. Add an explicit guard to prevent invalid filter construction.

Proposed fix
 let validationData = await entityTypeCache.getEntityTypesAndEntitiesWithCache(
 	{
 		status: common.ACTIVE_STATUS,
 		model_names: { [Op.overlap]: [userExtensionModelName] },
 	},
 	tenantCode,
 	organizationCode,
 	userExtensionModelName
 )
+if (validationData instanceof Error) {
+	throw validationData
+}

 let filteredQuery = utils.validateAndBuildFilters(query, validationData)
📝 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
let validationData = await entityTypeCache.getEntityTypesAndEntitiesWithCache(
{
status: common.ACTIVE_STATUS,
model_names: { [Op.overlap]: [userExtensionModelName] },
},
tenantCode,
organizationCode,
userExtensionModelName
)
let filteredQuery = utils.validateAndBuildFilters(query, validationData)
let validationData = await entityTypeCache.getEntityTypesAndEntitiesWithCache(
{
status: common.ACTIVE_STATUS,
model_names: { [Op.overlap]: [userExtensionModelName] },
},
tenantCode,
organizationCode,
userExtensionModelName
)
if (validationData instanceof Error) {
throw validationData
}
let filteredQuery = utils.validateAndBuildFilters(query, validationData)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/services/mentees.js` around lines 1536 - 1547, The result of
entityTypeCache.getEntityTypesAndEntitiesWithCache (assigned to validationData)
can be an Error; before calling utils.validateAndBuildFilters you must guard
that validationData is not an Error. Add an explicit check after the
getEntityTypesAndEntitiesWithCache call (e.g., if (validationData instanceof
Error) { ... }) and handle it the same way other sections in this file do
(returning/propagating the error or logging and exiting) so that
utils.validateAndBuildFilters is only called with valid validation data.

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