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

Microplancheck2 #2

Open
wants to merge 4 commits into
base: console
Choose a base branch
from
Open

Microplancheck2 #2

wants to merge 4 commits into from

Conversation

ashish-egov
Copy link
Owner

@ashish-egov ashish-egov commented Dec 4, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced asynchronous checks for microplan campaign IDs across various functions, enhancing data validation and processing.
    • Added new utility functions for improved handling of microplan-related requests.
  • Bug Fixes

    • Refined validation logic for campaign-related requests to ensure accuracy and specificity, particularly for microplan campaigns.
  • Documentation

    • Updated comments and documentation to reflect new functionalities and asynchronous behaviors.

These changes improve the overall robustness and responsiveness of the campaign management system.

Copy link

coderabbitai bot commented Dec 4, 2024

Walkthrough

The changes in this pull request focus on enhancing the asynchronous functionality and validation logic within the campaign-related files. Key modifications include the introduction of new utility functions, such as isMicropplanCampaignId and isMicroplanRequest, which facilitate checks for microplan campaign IDs. Several existing functions have been updated to be asynchronous, allowing them to await results from these new checks. Additionally, validation functions have been refined to improve accuracy and specificity in handling microplan-related requests. Overall, the changes promote a more modular and maintainable code structure.

Changes

File Path Change Summary
health-services/project-factory/src/server/api/campaignApis.ts Added isMicropplanCampaignId function; updated multiple functions to be asynchronous.
health-services/project-factory/src/server/utils/campaignUtils.ts Updated deterMineLastColumnAndEnrichUserDetails and processErrorData to be asynchronous; added isMicroplanRequest function.
health-services/project-factory/src/server/utils/genericUtils.ts Updated imports; replaced checkIfSourceIsMicroplan with isMicropplanCampaignId in createFacilitySheet.
health-services/project-factory/src/server/utils/microplanUtils.ts Removed checkIfSourceIsMicroplan; added isMicropplanCampaignId; refactored isMicroplanRequest.
health-services/project-factory/src/server/utils/targetUtils.ts Replaced checkIfSourceIsMicroplan with isMicroplanRequest in generateDynamicTargetHeaders.
health-services/project-factory/src/server/validators/campaignValidators.ts Added imports for isMicroplanRequest and isMicropplanCampaignId; updated validation functions for microplan checks.
health-services/project-factory/src/server/validators/microplanValidators.ts Updated validateFacilityBoundaryForLowestLevel to be asynchronous; integrated isMicropplanCampaignId check.

Poem

In the fields where campaigns grow,
A new check for microplans, we sow.
Asynchronous hops, oh what a delight,
Validations now shine, oh so bright!
With functions refined, we dance and play,
In the code's embrace, we find our way! 🐇✨


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 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.

@ashish-egov
Copy link
Owner Author

@coderabbitai review

Copy link

coderabbitai bot commented Dec 4, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Outside diff range comments (12)
health-services/project-factory/src/server/utils/targetUtils.ts (5)

Line range hint 9-19: Document the purpose of removing the first element in microplan path

The logic for handling microplan vs non-microplan requests is clear, but the purpose of headerColumnsAfterHierarchy.shift() isn't immediately obvious.

Consider adding a comment explaining why the first element is removed in the microplan path:

    else {
        headerColumnsAfterHierarchy = await getConfigurableColumnHeadersBasedOnCampaignType(request);
+       // Remove the first column as it's not needed for microplan requests
        headerColumnsAfterHierarchy.shift();
    }

Line range hint 23-55: Enhance type safety and naming conventions

The function has several areas that could be improved:

  1. The parameter name dataa appears to be a typo
  2. Type safety could be enhanced with proper interfaces
  3. Complex condition combining logic could be extracted

Consider applying these improvements:

+ interface DeliveryCondition {
+   attribute: { code: string };
+   operator: { code: string };
+   value?: number;
+   fromValue?: number;
+   toValue?: number;
+ }

- function modifyDeliveryConditions(dataa: any[]): any {
+ function modifyDeliveryConditions(deliveryRules: Array<{ conditions: DeliveryCondition[] }>): Set<string> {

Line range hint 58-69: Extract magic number to configuration

The hard limit of 18 columns should be moved to configuration for better maintainability.

Consider extracting the magic number:

+ const MAX_TARGET_COLUMNS = config.maxTargetColumns || 18;
  
  if (targetColumnsBasedOnDeliveryConditions.length > 18) {
-     targetColumnsBasedOnDeliveryConditions.splice(18);
+     targetColumnsBasedOnDeliveryConditions.splice(MAX_TARGET_COLUMNS);
      targetColumnsBasedOnDeliveryConditions.push(getLocalizedName("OTHER_TARGETS", localizationMap));
  }

Line range hint 87-109: Add error handling and improve readability

The function has several areas for improvement:

  1. Missing error handling for the external API call
  2. Deep nesting of conditions reduces readability

Consider this refactoring:

  async function updateTargetColumnsIfDeliveryConditionsDifferForSMC(request: any) {
+     try {
          const existingCampaignDetails = request?.body?.ExistingCampaignDetails;
-         if (existingCampaignDetails) {
-             if (isDynamicTargetTemplateForProjectType(request?.body?.CampaignDetails?.projectType) && 
-                 config?.isCallGenerateWhenDeliveryConditionsDiffer && 
-                 !_.isEqual(existingCampaignDetails?.deliveryRules, request?.body?.CampaignDetails?.deliveryRules)) {
+         if (!existingCampaignDetails) return;
+         
+         const shouldUpdateTargets = 
+             isDynamicTargetTemplateForProjectType(request?.body?.CampaignDetails?.projectType) && 
+             config?.isCallGenerateWhenDeliveryConditionsDiffer && 
+             !_.isEqual(existingCampaignDetails?.deliveryRules, request?.body?.CampaignDetails?.deliveryRules);
+         
+         if (shouldUpdateTargets) {
              // ... rest of the function
          }
+     } catch (error) {
+         console.error('Failed to update target columns:', error);
+         throw error;
+     }
  }

Line range hint 111-116: Add type safety for configuration value

The function could benefit from better type handling for the configuration value.

Consider this improvement:

+ type ProjectType = string;

- function isDynamicTargetTemplateForProjectType(projectType: string) {
+ function isDynamicTargetTemplateForProjectType(projectType: ProjectType): boolean {
-     const projectTypesFromConfig = config?.enableDynamicTemplateFor;
+     const projectTypesFromConfig: string = config?.enableDynamicTemplateFor ?? '';
      const projectTypesArray = projectTypesFromConfig ? projectTypesFromConfig.split(',') : [];
      return projectTypesArray.includes(projectType);
  }
health-services/project-factory/src/server/validators/microplanValidators.ts (1)

Line range hint 466-484: Handle Undefined campaignId in isMicropplanCampaignId Function

In isMicropplanCampaignId(campaignId: string), the campaignId parameter may be undefined if neither request.query.campaignId nor request.body.ResourceDetails.campaignId is defined. This could lead to unexpected behavior when executing the database query. Consider adding a null or undefined check for campaignId before proceeding.

Apply this diff to add a null check for campaignId:

 export async function isMicropplanCampaignId(campaignId: string) {
+    if (!campaignId) {
+        return false; // or handle the undefined campaignId appropriately
+    }
     if (campaignId == "microplan") return true;
     const query = `
         SELECT (additionaldetails->>'source' = 'microplan') AS is_microplan
         FROM ${config?.DB_CONFIG.DB_CAMPAIGN_DETAILS_TABLE_NAME}
         WHERE id = $1;
     `;
     try {
         const { rowCount, rows } = await executeQuery(query, [campaignId]);
         return rowCount > 0 ? rows[0].is_microplan : false;
     } catch (error: any) {
         logger.error(`Error checking if campaign ${campaignId} is a microplan request: ${error.message}`);
         throw error;
     }
 }
health-services/project-factory/src/server/utils/microplanUtils.ts (2)

Line range hint 538-540: Simplify Boolean Assignment

The boolean assignment using the ternary operator is unnecessary. You can directly assign the result of the await expression to isLockSheetNeeded.

Apply this diff to simplify the code:

 const isLockSheetNeeded =
-    await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)
-      ? true
-      : false;
+    await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId);

Line range hint 598-600: Simplify Boolean Assignment

The boolean assignment using the ternary operator is unnecessary. You can directly assign the result of the await expression to isLockSheetNeeded.

Apply this diff to simplify the code:

 const isLockSheetNeeded =
-    await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)
-      ? true
-      : false;
+    await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId);
health-services/project-factory/src/server/utils/genericUtils.ts (2)

Line range hint 1235-1244: Consider enhancing error handling for microplan data retrieval

While the conditional logic for microplan handling is well-implemented, consider adding explicit error handling for cases where the microplan check fails.

 const isSourceMicroplan = await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId);
+try {
   const type = request?.body?.ResourceDetails?.type;
   if (isSourceMicroplan) {
     if (type == 'user') {
       return await getUserDataFromMicroplanSheet(request, fileStoreId, tenantId, createAndSearchConfig, localizationMap);
     }
     else {
       return await getDataFromSheetFromNormalCampaign(type, fileStoreId, tenantId, createAndSearchConfig, optionalSheetName, localizationMap);
     }
   }
+} catch (error) {
+  logger.error(`Error retrieving microplan data: ${error.message}`);
+  throw error;
+}

Line range hint 1434-1439: LGTM: Clear microplan source handling with good logging

The microplan source handling is well-implemented. Consider enhancing the logging to include more context.

 const isSourceMicroplan = await isMicroplanRequest(request);
-  if (isSourceMicroplan) {
-    logger.info(`Source is Microplan.`);
+  if (isSourceMicroplan) {
+    logger.info(`Source is Microplan for campaign: ${request?.query?.campaignId}`);
health-services/project-factory/src/server/api/campaignApis.ts (2)

Line range hint 243-252: Assign the result of 'isMicroplanCampaignId' to 'isSourceMicroplan' variable

In the function updateErrorsForUser, the result of await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId); is not assigned to any variable. To utilize this value, assign it to isSourceMicroplan.

Apply this diff to fix the issue:

-    await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId);
+    const isSourceMicroplan = await isMicroplanCampaignId(request?.body?.ResourceDetails?.campaignId);

Line range hint 2975-2983: Avoid using 'await' inside object literals directly

Using await directly inside an object literal is invalid syntax. You need to compute the value before constructing the object.

Refactor the code to compute the source value before the additionalDetails object:

+      const isMicroplan = await isMicroplanCampaignId(request?.body?.ResourceDetails?.campaignId);
       additionalDetails: {
         ...request?.body?.ResourceDetails?.additionalDetails,
         sheetErrors: request?.body?.additionalDetailsErrors,
-        source:
-          await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)
-            ? "microplan"
-            : null,
+        source: isMicroplan ? "microplan" : null,
         [name]: [fileStoreId],
       },
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 72061ac and 083df47.

📒 Files selected for processing (7)
  • health-services/project-factory/src/server/api/campaignApis.ts (16 hunks)
  • health-services/project-factory/src/server/utils/campaignUtils.ts (15 hunks)
  • health-services/project-factory/src/server/utils/genericUtils.ts (6 hunks)
  • health-services/project-factory/src/server/utils/microplanUtils.ts (3 hunks)
  • health-services/project-factory/src/server/utils/targetUtils.ts (1 hunks)
  • health-services/project-factory/src/server/validators/campaignValidators.ts (8 hunks)
  • health-services/project-factory/src/server/validators/microplanValidators.ts (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
health-services/project-factory/src/server/utils/campaignUtils.ts

[error] 538-540: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


[error] 598-600: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

health-services/project-factory/src/server/validators/campaignValidators.ts

[error] 484-484: Unsafe usage of optional chaining.

If it short-circuits with 'undefined' the evaluation will throw TypeError here:

(lint/correctness/noUnsafeOptionalChaining)

🔇 Additional comments (4)
health-services/project-factory/src/server/utils/targetUtils.ts (2)

Line range hint 71-85: LGTM! Well-structured localization handling

The function effectively uses template literals and properly handles localization for all string components.


2-2: Verify the microplan utility function refactoring

The migration from checkIfSourceIsMicroplan to isMicroplanRequest appears to be part of a broader refactoring effort to consolidate microplan-related functionality.

Also applies to: 6-6

✅ Verification successful

Based on the search results, I can now generate the final response:

Migration from checkIfSourceIsMicroplan to isMicroplanRequest is complete and consistent

The refactoring appears to be thorough and complete:

  • No traces of the old checkIfSourceIsMicroplan function found in the codebase
  • The new isMicroplanRequest function is properly implemented in microplanUtils.ts and consistently used across multiple files:
    • campaignValidators.ts
    • targetUtils.ts
    • genericUtils.ts
    • campaignUtils.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the complete removal of old function and consistent usage of new function
rg "checkIfSourceIsMicroplan" 
rg "isMicroplanRequest" -A 2

Length of output: 5244

health-services/project-factory/src/server/utils/genericUtils.ts (2)

21-21: LGTM: Import statement is well-structured

The import statement correctly imports necessary microplan-related utility functions.


547-548: LGTM: Proper async/await usage for microplan check

The modification correctly implements the microplan campaign ID check using async/await pattern.

Comment on lines +290 to +291
export async function validateFacilityBoundaryForLowestLevel(request: any, boundaries: any, rowData: any, errors: any = [], localizationMap?: { [key: string]: string }) {
if (request?.body?.ResourceDetails?.type == "facility" && await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)) {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add Null Check for campaignId Before Using

The function validateFacilityBoundaryForLowestLevel accesses request?.body?.ResourceDetails?.campaignId without verifying if campaignId is defined. If campaignId is undefined, passing it to isMicropplanCampaignId() might cause unexpected behavior or errors. Consider adding a check to ensure campaignId is defined before using it.

Apply this diff to add a null check for campaignId:

 export async function validateFacilityBoundaryForLowestLevel(request: any, boundaries: any, rowData: any, errors: any = [], localizationMap?: { [key: string]: string }) {
+    const campaignId = request?.body?.ResourceDetails?.campaignId;
+    if (request?.body?.ResourceDetails?.type == "facility" && campaignId && await isMicropplanCampaignId(campaignId)) {
-    if (request?.body?.ResourceDetails?.type == "facility" && await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)) {
         const hierarchy = request?.body?.hierarchyType?.boundaryHierarchy
         const lastLevel = hierarchy?.[hierarchy.length - 1]?.boundaryType
         for (const data of rowData?.boundaryCodes) {
             const boundaryFromBoundariesType = boundaries.find((boundary: any) => boundary.code == data)?.type
             if (boundaryFromBoundariesType != lastLevel) {
                 errors.push({ status: "INVALID", rowNumber: rowData?.rowNumber, errorDetails: `${data} is not a ${lastLevel} level boundary` })
             }
         }
     }
 }
📝 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
export async function validateFacilityBoundaryForLowestLevel(request: any, boundaries: any, rowData: any, errors: any = [], localizationMap?: { [key: string]: string }) {
if (request?.body?.ResourceDetails?.type == "facility" && await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)) {
export async function validateFacilityBoundaryForLowestLevel(request: any, boundaries: any, rowData: any, errors: any = [], localizationMap?: { [key: string]: string }) {
const campaignId = request?.body?.ResourceDetails?.campaignId;
if (request?.body?.ResourceDetails?.type == "facility" && campaignId && await isMicropplanCampaignId(campaignId)) {
const hierarchy = request?.body?.hierarchyType?.boundaryHierarchy
const lastLevel = hierarchy?.[hierarchy.length - 1]?.boundaryType
for (const data of rowData?.boundaryCodes) {
const boundaryFromBoundariesType = boundaries.find((boundary: any) => boundary.code == data)?.type
if (boundaryFromBoundariesType != lastLevel) {
errors.push({ status: "INVALID", rowNumber: rowData?.rowNumber, errorDetails: `${data} is not a ${lastLevel} level boundary` })
}
}
}
}

Comment on lines +1453 to 1455
const isSourceMicroplan = await isMicroplanRequest(request);
campaignType = (isSourceMicroplan) ? `${config?.prefixForMicroplanCampaigns}-${campaignType}` : campaignType;
const mdmsResponse = await callMdmsTypeSchema(request, request?.query?.tenantId || request?.body?.ResourceDetails?.tenantId, false, request?.query?.type || request?.body?.ResourceDetails?.type, campaignType)
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider moving microplan prefix to configuration

While the prefix handling for microplan campaigns is correct, consider moving the prefix to configuration for better maintainability.

 const isSourceMicroplan = await isMicroplanRequest(request);
-  campaignType = (isSourceMicroplan) ? `${config?.prefixForMicroplanCampaigns}-${campaignType}` : campaignType;
+  campaignType = (isSourceMicroplan) ? `${config?.microplan?.campaignTypePrefix || 'MP'}-${campaignType}` : campaignType;

Committable suggestion skipped: line range outside the PR's diff.

@@ -48,6 +47,7 @@ import { checkAndGiveIfParentCampaignAvailable } from "../utils/onGoingCampaignU
import { validateMicroplanFacility } from "../validators/microplanValidators";
import {
createPlanFacilityForMicroplan,
isMicropplanCampaignId,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct the typo in function name 'isMicropplanCampaignId'

The function name isMicropplanCampaignId is misspelled; it should be isMicroplanCampaignId with a single 'p' in 'microplan'. Please correct the import statement and ensure consistency throughout the codebase.

Apply this diff to fix the typo:

-import {
-  createPlanFacilityForMicroplan,
-  isMicropplanCampaignId,
-  updateFacilityDetailsForMicroplan,
-} from "../utils/microplanUtils";
+import {
+  createPlanFacilityForMicroplan,
+  isMicroplanCampaignId,
+  updateFacilityDetailsForMicroplan,
+} from "../utils/microplanUtils";

Committable suggestion skipped: line range outside the PR's diff.

@@ -24,7 +24,7 @@ import { generateTargetColumnsBasedOnDeliveryConditions, isDynamicTargetTemplate
import { getBoundariesFromCampaignSearchResponse, validateBoundariesIfParentPresent } from "../utils/onGoingCampaignUpdateUtils";
import { validateFacilityBoundaryForLowestLevel, validateLatLongForMicroplanCampaigns, validatePhoneNumberSheetWise, validateTargetsForMicroplanCampaigns, validateUniqueSheetWise, validateUserForMicroplan } from "./microplanValidators";
import { produceModifiedMessages } from "../kafka/Producer";
import { planConfigSearch, planFacilitySearch } from "../utils/microplanUtils";
import { isMicroplanRequest, isMicropplanCampaignId, planConfigSearch, planFacilitySearch } from "../utils/microplanUtils";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct the typo in function name 'isMicroplanCampaignId'

The function name isMicropplanCampaignId is misspelled; it should be isMicroplanCampaignId with a single 'p' in 'microplan'. Please correct the import statement and ensure consistency throughout the codebase.

Apply this diff to fix the typo:

-import { isMicroplanRequest, isMicropplanCampaignId, planConfigSearch, planFacilitySearch } from "../utils/microplanUtils";
+import { isMicroplanRequest, isMicroplanCampaignId, planConfigSearch, planFacilitySearch } from "../utils/microplanUtils";
📝 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
import { isMicroplanRequest, isMicropplanCampaignId, planConfigSearch, planFacilitySearch } from "../utils/microplanUtils";
import { isMicroplanRequest, isMicroplanCampaignId, planConfigSearch, planFacilitySearch } from "../utils/microplanUtils";

@@ -481,7 +481,7 @@ function validateStorageCapacity(obj: any, index: any) {


async function validateCampaignId(request: any) {
const { campaignId, tenantId, type, additionalDetails } = request?.body?.ResourceDetails;
const { campaignId, tenantId, type } = request?.body?.ResourceDetails;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix unsafe optional chaining when destructuring 'request.body.ResourceDetails'

Destructuring { campaignId, tenantId, type } from request?.body?.ResourceDetails is unsafe because if request.body.ResourceDetails is undefined, it will cause a TypeError. Optional chaining cannot be used in destructuring assignments.

Apply this diff to fix the issue:

-     const { campaignId, tenantId, type } = request?.body?.ResourceDetails;
+     if (!request.body || !request.body.ResourceDetails) {
+       throwError("COMMON", 400, "VALIDATION_ERROR", "ResourceDetails is missing");
+     }
+     const { campaignId, tenantId, type } = request.body.ResourceDetails;

Alternatively, provide a default value to prevent the error:

-     const { campaignId, tenantId, type } = request?.body?.ResourceDetails;
+     const { campaignId, tenantId, type } = request.body.ResourceDetails || {};

Ensure that request.body.ResourceDetails exists before destructuring.

📝 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
const { campaignId, tenantId, type } = request?.body?.ResourceDetails;
if (!request.body || !request.body.ResourceDetails) {
throwError("COMMON", 400, "VALIDATION_ERROR", "ResourceDetails is missing");
}
const { campaignId, tenantId, type } = request.body.ResourceDetails;
Suggested change
const { campaignId, tenantId, type } = request?.body?.ResourceDetails;
const { campaignId, tenantId, type } = request.body.ResourceDetails || {};
🧰 Tools
🪛 Biome (1.9.4)

[error] 484-484: Unsafe usage of optional chaining.

If it short-circuits with 'undefined' the evaluation will throw TypeError here:

(lint/correctness/noUnsafeOptionalChaining)

@@ -93,7 +93,7 @@ import {
modifyNewSheetData,
unhideColumnsOfProcessedFile,
} from "./onGoingCampaignUpdateUtils";
import { changeCreateDataForMicroplan, lockSheet } from "./microplanUtils";
import { changeCreateDataForMicroplan, isMicroplanRequest, isMicropplanCampaignId, lockSheet } from "./microplanUtils";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct the typo in function name 'isMicroplanCampaignId'

The function name isMicropplanCampaignId is misspelled; it should be isMicroplanCampaignId with a single 'p' in 'microplan'. Please correct the import statement and ensure consistency throughout the codebase.

Apply this diff to fix the typo:

-import { changeCreateDataForMicroplan, isMicroplanRequest, isMicropplanCampaignId, lockSheet } from "./microplanUtils";
+import { changeCreateDataForMicroplan, isMicroplanRequest, isMicroplanCampaignId, lockSheet } from "./microplanUtils";
📝 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
import { changeCreateDataForMicroplan, isMicroplanRequest, isMicropplanCampaignId, lockSheet } from "./microplanUtils";
import { changeCreateDataForMicroplan, isMicroplanRequest, isMicroplanCampaignId, lockSheet } from "./microplanUtils";

Comment on lines +538 to 540
await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)
? true
: false;
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Simplify boolean assignment without redundant ternary operator

The ternary operator is unnecessary here since await isMicroplanCampaignId(...) already returns a boolean. Assign the result directly to isLockSheetNeeded.

Apply this diff to simplify the code:

-     const isLockSheetNeeded =
-       await isMicroplanCampaignId(request?.body?.ResourceDetails?.campaignId)
-         ? true
-         : false;
+     const isLockSheetNeeded = await isMicroplanCampaignId(request?.body?.ResourceDetails?.campaignId);
📝 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
await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)
? true
: false;
const isLockSheetNeeded = await isMicroplanCampaignId(request?.body?.ResourceDetails?.campaignId);
🧰 Tools
🪛 Biome (1.9.4)

[error] 538-540: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

Comment on lines +2975 to +2983
{
...request?.body?.ResourceDetails?.additionalDetails,
sheetErrors: request?.body?.additionalDetailsErrors,
source:
await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)
? "microplan"
: null,
[name]: [fileStoreId],
} ,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid using 'await' inside object literals directly

Using await directly inside an object literal is invalid syntax. Compute the awaited value before constructing the object.

Refactor the code as follows:

+      const isMicroplan = await isMicroplanCampaignId(request?.body?.ResourceDetails?.campaignId);
       request.body.ResourceDetails = {
         ...request.body.ResourceDetails,
         processedFileStoreId: fileStoreId,
         status:
           request.body.ResourceDetails.status != resourceDataStatuses.invalid
             ? resourceDataStatuses.completed
             : resourceDataStatuses.invalid,
         auditDetails: {
           ...request.body.ResourceDetails.auditDetails,
           lastModifiedBy: request.body.RequestInfo.userInfo.uuid,
           lastModifiedTime: Date.now(),
         },
         additionalDetails: {
           ...request.body.ResourceDetails.additionalDetails,
           sheetErrors: request.body.additionalDetailsErrors,
-          source:
-            await isMicroplanCampaignId(request?.body?.ResourceDetails?.campaignId)
-              ? "microplan"
-              : null,
+          source: isMicroplan ? "microplan" : null,
           [name]: [fileStoreId],
         },
       };

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +598 to 600
await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)
? true
: false;
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Simplify boolean assignment without redundant ternary operator

Again, the ternary operator is unnecessary and can be removed.

Apply this diff to simplify the code:

-     const isLockSheetNeeded =
-       await isMicroplanCampaignId(request?.body?.ResourceDetails?.campaignId)
-         ? true
-         : false;
+     const isLockSheetNeeded = await isMicroplanCampaignId(request?.body?.ResourceDetails?.campaignId);

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Biome (1.9.4)

[error] 598-600: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

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