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

Hcmpre 866 #1547

Merged
merged 5 commits into from
Oct 17, 2024
Merged

Hcmpre 866 #1547

merged 5 commits into from
Oct 17, 2024

Conversation

Bhavya-egov
Copy link
Contributor

@Bhavya-egov Bhavya-egov commented Oct 17, 2024

Summary by CodeRabbit

  • New Features

    • Introduced new utility functions for data processing in campaign management.
    • Enhanced data handling and validation processes in the Setup Campaign component.
    • Added optional chaining for safer property access in various components.
  • Bug Fixes

    • Improved error handling and state management across multiple components to prevent potential runtime issues.
  • Refactor

    • Restructured multiple components for better data handling and UI responsiveness.
    • Removed deprecated functions and simplified logic in several areas for improved performance.

Copy link
Contributor

coderabbitai bot commented Oct 17, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces several changes across multiple components in the campaign management module. Key modifications include the addition of null checks, restructuring of data handling, introduction of new utility functions, and enhancements in state management. Notably, the CampaignSummary.js and SetupCampaign.js components have undergone significant rewrites to improve data processing and validation. Other components have also been refined for better error handling and property access, contributing to the overall robustness of the application.

Changes

File Path Change Summary
.../BoundarySummary.js Added null check for boundaryData in boundaryDataGrp function.
.../CampaignSummary.js Restructured data handling; added utility functions: mapProductVariants, parseConditionAndCreateRules, mapDeliveries; refined useEffect hooks.
.../CampaignUpdateSummary.js Updated handleRedirect function; modified redirection logic; removed commented-out useEffect for error handling.
.../DeliveryDetailsSummary.js Introduced getDeliveryConfig function; restructured reverseDeliveryRemap; refined error processing logic.
.../SetupCampaign.js Added functions for data processing and validation; refactored restructureData function; removed deprecated functions.
.../deliveryRule/AddDeliverycontext.js Enhanced delivery rules handling; used optional chaining for property access; refined attribute handling logic.
.../deliveryRule/index.js Updated delivery rules handling; added optional chaining; modified generateTabsData and campaignDataReducer.
.../utils/getDeliveryConfig.js Rewrote generateMRDNConfig; adjusted deliveryConfig logic; updated convertToConfig function.

Possibly related PRs

Suggested reviewers

  • nipunarora-eGov
  • jagankumar-egov

Poem

In the garden of code, we hop and play,
With checks and functions, we brighten the day.
From summaries to deliveries, all in a row,
Our changes bring joy, as we watch them grow! 🐇✨


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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

Caution

Inline review comments failed to post

Actionable comments posted: 25

🧹 Outside diff range comments (1)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/index.js (1)

Line range hint 532-537: LGTM! Improved reactivity for campaign data generation.

The updated useEffect hook now correctly depends on cycleData, ensuring that campaign data is regenerated whenever the cycle configuration changes. This improves the component's reactivity and data consistency.

Consider memoizing the cycleData.cycleConfgureDate object to optimize performance, especially if it's derived from props or complex calculations:

const memoizedCycleConfigureDate = useMemo(() => cycleData?.cycleConfgureDate, [cycleData]);

useEffect(() => {
  if (memoizedCycleConfigureDate) {
    dispatchCampaignData({
      type: "GENERATE_CAMPAIGN_DATA",
      cycle: memoizedCycleConfigureDate.cycle,
      deliveries: memoizedCycleConfigureDate.deliveries,
    });
  }
}, [memoizedCycleConfigureDate, dispatchCampaignData]);

This approach can help prevent unnecessary re-renders if cycleData changes frequently but cycleConfgureDate remains the same.

🛑 Comments failed to post (25)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignUpdateSummary.js (2)

217-217: 🧹 Nitpick (assertive)

LGTM! Consider adding keyboard accessibility.

The changes to the handleRedirect function and the addition of updateUrlParams improve URL handling and code maintainability. Great job!

To enhance accessibility, consider adding keyboard event handlers (onKeyUp, onKeyDown, or onKeyPress) alongside the onClick events for the edit buttons. This ensures that keyboard-only users can also interact with these elements. For example:

<div 
  className="campaign-preview-edit-container" 
  onClick={() => handleRedirect(4)}
  onKeyDown={(e) => e.key === 'Enter' && handleRedirect(4)}
  tabIndex={0}
  role="button"
>
  <span>{t(`CAMPAIGN_EDIT`)}</span>
  <EditIcon />
</div>

Apply this pattern to all similar div elements acting as buttons.

Also applies to: 237-237, 257-257

🧰 Tools
🪛 Biome

[error] 217-217: Enforce to have the onClick mouse event with the onKeyUp, the onKeyDown, or the onKeyPress keyboard event.

Actions triggered using mouse events should have corresponding keyboard events to account for keyboard-only navigation.

(lint/a11y/useKeyWithClickEvents)


217-217: 💡 Codebase verification

Error handling for summaryErrors is incomplete after removal of the useEffect block.

The CampaignUpdateSummary.js component initializes summaryErrors but does not actively manage or update them due to the commented-out setSummaryErrors calls. Please ensure that error handling for summaryErrors is implemented appropriately, either within this component or elsewhere in the codebase.

🔗 Analysis chain

Verify error handling after removal of commented-out code.

The removal of the commented-out useEffect block improves code cleanliness. However, please ensure that the error handling functionality previously managed by this code is now handled elsewhere or is no longer needed.

To confirm that error handling is still properly managed, please run the following script:

Also applies to: 237-237, 257-257

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for error handling related to summaryErrors

echo "Searching for summaryErrors usage in the codebase..."
rg --type js 'summaryErrors'

echo "Searching for error state management in the CampaignUpdateSummary component..."
rg --type js '(setDeliveryErrors|setTargetErrors|setFacilityErrors|setUserErrors|setCycleDatesError|setSummaryErrors)' health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignUpdateSummary.js

echo "Please review the output to ensure that error handling related to summaryErrors is still properly managed in the codebase."

Length of output: 12693

🧰 Tools
🪛 Biome

[error] 217-217: Enforce to have the onClick mouse event with the onKeyUp, the onKeyDown, or the onKeyPress keyboard event.

Actions triggered using mouse events should have corresponding keyboard events to account for keyboard-only navigation.

(lint/a11y/useKeyWithClickEvents)

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/index.js (1)

304-310: 🧹 Nitpick (assertive)

LGTM! Improved null checks for better robustness.

The addition of optional chaining operators (?.) enhances the code's resilience against potential runtime errors when accessing properties of potentially undefined objects. This is a good practice, especially when dealing with data that might not always be present.

Consider using nullish coalescing operator (??) for providing default values, which can make the code even more concise. For example:

if ((cycle?.deliveries?.length ?? 0) > subTabs) {
  cycle?.deliveries?.splice(subTabs);
}

if (subTabs > (cycle?.deliveries?.length ?? 0)) {
  // ... rest of the code
}

This approach handles both undefined and null cases elegantly.

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (4)

105-105: ⚠️ Potential issue

Potential confusion with nested deliveries property.

In line 105, conditionConfig is created by mapping over delivery.deliveries. This could be confusing since you are iterating over deliveries, and each delivery has a deliveries property. Verify that delivery.deliveries is the correct property and consider renaming variables or restructuring the data to improve readability.


124-128: 🧹 Nitpick (assertive)

Remove commented-out code for cleaner codebase.

The code in lines 124-128 is commented out. If this code is no longer needed, consider removing it to maintain code cleanliness and prevent confusion.


147-147: ⚠️ Potential issue

Incorrect function call to generateMRDNConfig.

The generateMRDNConfig function has been updated to accept only one parameter (deliveries), but at line 147, it is called with two arguments: data?.cycles and projectType. This mismatch will lead to a runtime error.

Apply this diff to fix the function call:

- return generateMRDNConfig(data?.cycles, projectType);
+ return generateMRDNConfig(data?.cycles);
📝 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.

        return generateMRDNConfig(data?.cycles);

101-142: ⚠️ Potential issue

Ensure proper handling of fromValue and toValue in attributeConfig.

In the generateMRDNConfig function, within the attributeConfig, fromValue and toValue are assigned using value.minValue and value.maxValue without considering the operatorValue. If operatorValue is not "IN_BETWEEN", value may not have minValue and maxValue, leading to undefined values.

Consider adding logic to handle different operatorValue cases, similar to what's done in the generateBednetConfig function.

Apply this diff to address the issue:

+             let fromValue = null;
+             let toValue = null;
+             if (operatorValue === "IN_BETWEEN") {
+               fromValue = Number(value.minValue);
+               toValue = Number(value.maxValue);
+             } else {
+               fromValue = Number(value.comparisonValue);
+               toValue = null;
+             }

              return {
                key: `${conditionIndex + 1}-${attrIndex + 1}`, 
                label: "Custom",
                attrType: criteria.attrType || "dropdown",
                attrValue: value.variable, 
                operatorValue,
-               fromValue: Number(value.minValue),
-               toValue: Number(value.maxValue) - 1
+               fromValue,
+               toValue
              };
📝 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.

  const generateMRDNConfig = (deliveries) => {
    const deliveryConfig = deliveries.map((delivery, deliveryIndex) => {
      return {
        delivery: delivery.id, 
        conditionConfig: delivery.deliveries.map((deliveryItem, conditionIndex) => {
          return {
            disableDeliveryType: deliveryItem.deliveryStrategy === "DIRECT",
            deliveryType: deliveryItem.deliveryStrategy,
            attributeConfig: deliveryItem.doseCriteria.map((criteria, attrIndex) => {
              const { operatorValue, value } = parseCondition(criteria.condition);
  
              let fromValue = null;
              let toValue = null;
              if (operatorValue === "IN_BETWEEN") {
                fromValue = Number(value.minValue);
                toValue = Number(value.maxValue);
              } else {
                fromValue = Number(value.comparisonValue);
                toValue = null;
              }

              return {
                key: `${conditionIndex + 1}-${attrIndex + 1}`, 
                label: "Custom",
                attrType: criteria.attrType || "dropdown",
                attrValue: value.variable, 
                operatorValue,
                fromValue,
                toValue
              };
            }),
            productConfig: deliveryItem.doseCriteria.flatMap((criteria, prodIndex) => {
              return criteria.ProductVariants.map((variant, varIndex) => {
                // if(variant?.productVariantId){
                //   productName = useProductVariantSearch({ variantId: variant.productVariantId, tenantId: "mz" });
                // }
                // const productName = useProductVariantSearch({ variantId: variant.productVariantId, tenantId: "mz" });
  
                return {
                  key: `${conditionIndex + 1}-${varIndex + 1}`,
                  count: variant.quantity,
                  value: variant.productVariantId,
                  name: variant.name
                };
              });
            })
          };
        })
      };
    });
    return deliveryConfig;
  };
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DeliveryDetailsSummary.js (3)

111-111: ⚠️ Potential issue

Use const instead of let for variables that are not reassigned.

Variables rules (line 111) and attributes (line 115) are declared with let but are never reassigned after their initial assignment. Using const for such variables enhances code readability and prevents accidental reassignment.

Apply this diff to fix the issue:

  // Line 111
- let rules = [];
+ const rules = [];

  // Line 115
- let attributes = [];
+ const attributes = [];

Also applies to: 115-115

🧰 Tools
🪛 Biome

[error] 111-111: This let declares a variable that is only assigned once.

'rules' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


89-97: ⚠️ Potential issue

Quote the key 'IN_BETWEEN' in operatorMapping to prevent referencing an undefined variable.

In the operatorMapping object, the key IN_BETWEEN is not enclosed in quotes. This could lead to an undefined variable error since unquoted keys are treated as variables. Object keys intended as strings should be enclosed in quotes.

Apply this diff to fix the issue:

  const operatorMapping = {
    "<=": "LESS_THAN_EQUAL_TO",
    ">=": "GREATER_THAN_EQUAL_TO",
    "<": "LESS_THAN",
    ">": "GREATER_THAN",
    "==": "EQUAL_TO",
    "!=": "NOT_EQUAL_TO",
-   IN_BETWEEN: "IN_BETWEEN",
+   "IN_BETWEEN": "IN_BETWEEN",
  };
📝 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.

  const operatorMapping = {
    "<=": "LESS_THAN_EQUAL_TO",
    ">=": "GREATER_THAN_EQUAL_TO",
    "<": "LESS_THAN",
    ">": "GREATER_THAN",
    "==": "EQUAL_TO",
    "!=": "NOT_EQUAL_TO",
    "IN_BETWEEN": "IN_BETWEEN",
  };

410-412: 🛠️ Refactor suggestion

Ensure consistent code formatting for better readability.

The else block is misaligned, which can lead to confusion. It's recommended to use braces consistently for all conditional branches to improve code clarity and maintainability.

Apply this diff to improve code formatting:

  const onStepClick = (currentStep) => {
    if (currentStep === 0) {
      setKey(7);
    } else if (currentStep === 2) {
      setKey(9);
    } else {
      setKey(8);
    }
  };
📝 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.

    if (currentStep === 0) {
      setKey(7);
    } else if (currentStep === 2) {
      setKey(9);
    } else {
      setKey(8);
    }
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignSummary.js (6)

95-95: ⚠️ Potential issue

Enclose 'IN_BETWEEN' in quotes

In the operatorMapping object, the key IN_BETWEEN is not enclosed in quotes, which could lead to unexpected behavior if IN_BETWEEN is not a defined variable. To ensure it's treated as a string key, enclose it in quotes.

Apply this diff to fix the issue:

-    IN_BETWEEN: "IN_BETWEEN",
+    "IN_BETWEEN": "IN_BETWEEN",
📝 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.

    "IN_BETWEEN": "IN_BETWEEN",

692-692: 🧹 Nitpick (assertive)

Simplify condition with optional chaining

Use optional chaining to streamline the condition when accessing nested properties.

Apply this diff:

-            if (section.props && section.props.data) {
+            if (section.props?.data) {
📝 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.

            if (section.props?.data) {
🧰 Tools
🪛 Biome

[error] 692-692: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


686-686: 🧹 Nitpick (assertive)

Simplify condition with optional chaining

You can simplify the condition by using optional chaining to check if card.name exists before calling startsWith.

Apply this diff:

-        if (card.name && card.name.startsWith("CYCLE_")) {
+        if (card.name?.startsWith("CYCLE_")) {
📝 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.

      if (card.name?.startsWith("CYCLE_")) {
🧰 Tools
🪛 Biome

[error] 686-686: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


426-426: 🧹 Nitpick (assertive)

Simplify string concatenation using template literals

You're concatenating strings inside a template literal using the + operator. You can simplify this by utilizing template literals entirely.

Apply this diff to improve the code:

-    cardHeader: { value: `${t((hierarchyType + "_" + item?.type).toUpperCase())}`, inlineStyles: { color: "#0B4B66" } },
+    cardHeader: { value: `${t(`${hierarchyType}_${item?.type}`.toUpperCase())}`, inlineStyles: { color: "#0B4B66" } },
📝 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.

                    cardHeader: { value: `${t(`${hierarchyType}_${item?.type}`.toUpperCase())}`, inlineStyles: { color: "#0B4B66" } },
🧰 Tools
🪛 Biome

[error] 426-426: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


114-114: 🧹 Nitpick (assertive)

Use 'const' instead of 'let' for 'attributes'

The variable attributes is declared with let but is never reassigned. Consider using const to make the intent clearer.

Apply this diff to fix the issue:

-    let attributes = [];
+    const attributes = [];
📝 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.

      const attributes = [];
🧰 Tools
🪛 Biome

[error] 114-114: This let declares a variable that is only assigned once.

'attributes' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


110-110: 🧹 Nitpick (assertive)

Use 'const' instead of 'let' for 'rules'

The variable rules is declared with let but is never reassigned. Using const is preferred for variables that are not reassigned to enhance code readability and prevent accidental reassignments.

Apply this diff to fix the issue:

-  let rules = [];
+  const rules = [];
📝 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.

    const rules = [];
🧰 Tools
🪛 Biome

[error] 110-110: This let declares a variable that is only assigned once.

'rules' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddDeliverycontext.js (2)

618-619: 🛠️ Refactor suggestion

Consider refactoring duplicated code for 'selectedStructureCodes'.

The declaration of selectedStructureCodes at lines 618-619 is duplicated at lines 922-923. Extracting this logic into a shared utility function can improve maintainability and reduce redundancy.


922-923: ⚠️ Potential issue

Missing optional chaining operator may cause runtime errors.

At line 923, the optional chaining operator ?. is missing before map on attributes. If rule?.attributes is null or undefined, calling map will result in a runtime error. Please add the optional chaining operator to prevent potential errors.

Apply this diff to fix the issue:

-        cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes.map((attribute) => attribute?.value)))
+        cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes?.map((attribute) => attribute?.value)))
📝 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.

  const selectedStructureCodes = campaignData?.flatMap((cycle) =>
    cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes?.map((attribute) => attribute?.value)))
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (7)

649-649: ⚠️ Potential issue

Ensure projectType is provided when calling restructureData

The restructureData function expects a projectType parameter. Omitting it may lead to unexpected behavior or errors, especially since it's used to find the appropriate delivery configuration.

Please update the function calls to include projectType:

// Example at line 649
- const temp = restructureData(..., DeliveryConfig);
+ const temp = restructureData(..., DeliveryConfig, totalFormData?.HCM_CAMPAIGN_TYPE?.projectType?.code);

Also applies to: 721-721, 786-786, 850-850


722-722: ⚠️ Potential issue

Maintain consistent assignment to payloadData.deliveryRules

payloadData.deliveryRules is assigned differently in various places—once as an array containing temp[0] and once directly as temp[0]. This inconsistency can cause issues if other parts of the code expect deliveryRules to be of a specific type.

Please standardize the assignment:

  • If deliveryRules should be an array:

    // At line 787
    - payloadData.deliveryRules = temp?.[0];
    + payloadData.deliveryRules = [temp?.[0]];
  • Or if it should be an object:

    // At lines 650 and 851
    - payloadData.deliveryRules = [temp?.[0]];
    + payloadData.deliveryRules = temp?.[0];

Also applies to: 787-787


186-186: 🧹 Nitpick (assertive)

Remove debugging statement

The console.log statement is likely used for debugging purposes and should be removed to clean up the console output in production.

Suggested change:

-  console.log("t" , data);
📝 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.



277-277: 🧹 Nitpick (assertive)

Remove debugging statement

The console.log statement can clutter console output and reveal internal data structures. It's advisable to remove it before deploying.

Suggested change:

-  console.log("tttttttttt" , transformedCycles);
📝 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.



86-149: 🧹 Nitpick (assertive)

Remove large blocks of commented-out code

Having large sections of commented-out code can reduce code readability and increase maintenance overhead. It's better to remove unused code and rely on version control systems to retrieve previous versions if needed.

Suggested change:

- // function restructureData(data, cycleData, DeliveryConfig, projectType) {
- //   const tt = DeliveryConfig?.find((e) => e.code === String(projectType));
- //   ...
- //   return [tt];
- // }
📝 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.



514-514: 🧹 Nitpick (assertive)

Remove debugging statement

Removing unnecessary console.log statements improves performance and reduces potential exposure of sensitive information.

Suggested change:

-        console.log("delivery" , delivery);
📝 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.



155-156: ⚠️ Potential issue

Avoid using the delete operator; consider setting properties to undefined or null instead

Using the delete operator can negatively impact JavaScript engine optimizations and overall performance. It's recommended to set the properties to undefined or null to indicate they are no longer needed.

Suggested change:

-    delete deliveryConfig.cycles;   
-    delete deliveryConfig.resources;  
+    deliveryConfig.cycles = undefined;   
+    deliveryConfig.resources = undefined;  
📝 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.

    deliveryConfig.cycles = undefined;   
    deliveryConfig.resources = undefined;  
🧰 Tools
🪛 Biome

[error] 155-155: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 156-156: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

@jagankumar-egov jagankumar-egov merged commit f774087 into console Oct 17, 2024
3 checks passed
@jagankumar-egov jagankumar-egov deleted the HCMPRE-866 branch October 17, 2024 12:07
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: 5

🧹 Outside diff range comments (2)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (2)

Line range hint 155-160: Verify the Correctness of Cycle Dates Assignment.

In the restructureData function, the startDate and endDate for each cycle are being set using cycleData.cycleData[0], which means all cycles will have the same dates:

const cycleStartDate = Digit.Utils.pt.convertDateToEpoch(cycleData?.cycleData?.[0]?.fromDate);
const cycleEndDate = Digit.Utils.pt.convertDateToEpoch(cycleData?.cycleData?.[0]?.toDate);

Please verify if this is intended. If each cycle should have its own start and end dates, consider updating the code to use the corresponding index:

const cycles = data.map((cycle, index) => {
-   const cycleStartDate = Digit.Utils.pt.convertDateToEpoch(cycleData?.cycleData?.[0]?.fromDate);
-   const cycleEndDate = Digit.Utils.pt.convertDateToEpoch(cycleData?.cycleData?.[0]?.toDate);
+   const cycleStartDate = Digit.Utils.pt.convertDateToEpoch(cycleData?.cycleData?.[index]?.fromDate);
+   const cycleEndDate = Digit.Utils.pt.convertDateToEpoch(cycleData?.cycleData?.[index]?.toDate);
    // rest of the code...
});

Line range hint 316-320: Enhance Age Extraction Logic in extractAgesFromConditions.

The extractAgesFromConditions function uses a regular expression that matches any number in the condition string:

const agePattern = /\b(\d+)\b/g;

Consider refining the regex to specifically match age-related numbers to avoid capturing unintended numbers that are not related to age.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between eddd07c and 076aad5.

📒 Files selected for processing (4)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/BoundarySummary.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddDeliverycontext.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/BoundarySummary.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddDeliverycontext.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (1)

Pattern **/*.js: check

🔇 Additional comments (2)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/BoundarySummary.js (1)

Line range hint 1-38: Overall, the change improves robustness without altering core functionality.

The addition of the null check in the boundaryDataGrp function enhances the component's resilience to unexpected data structures. This change:

  1. Prevents potential runtime errors when processing boundary data.
  2. Maintains the existing data flow and component functionality.
  3. Slightly improves code maintainability.

To ensure this change doesn't mask any underlying issues, please verify that boundaryData is expected to be potentially undefined in some valid scenarios. Run the following script to check for other usages of boundaryData:

✅ Verification successful

Change Verified: The null check added to the boundaryDataGrp function aligns with existing code practices where boundaryData may be undefined. This enhancement ensures greater resilience without affecting the component's core functionality.

  • boundaryData is appropriately handled across various components, indicating that it can be undefined in valid scenarios.
  • The added null check prevents potential runtime errors during data processing.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other usages of boundaryData to ensure consistency
rg --type js 'boundaryData' health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src

Length of output: 12050

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (1)

133-134: Verify that variant.name is reliably defined

The updated code assigns variant.name directly to the name property:

name: variant.name

Previously, there was a commented-out implementation using the useProductVariantSearch hook to retrieve the product name. This suggests that variant.name may not always have the necessary data. Please verify that variant.name is consistently defined and contains the correct product name for all variants. If there are cases where variant.name might be undefined or incorrect, consider handling these cases or reverting to using the useProductVariantSearch hook.

@@ -13,7 +13,7 @@ function boundaryDataGrp(boundaryData) {
const groupedData = {};

// Iterate through each boundary item in the data
boundaryData.forEach((item) => {
boundaryData?.forEach((item) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Approve the null check, but consider adding a fallback.

The addition of the optional chaining operator ?. is a good defensive programming practice. It prevents potential runtime errors when boundaryData is null or undefined.

Consider adding a fallback to make the behavior more explicit:

-  boundaryData?.forEach((item) => {
+  (boundaryData || []).forEach((item) => {

This change ensures that an empty array is used if boundaryData is falsy, making the intention clearer and maintaining consistent behavior.

📝 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
boundaryData?.forEach((item) => {
(boundaryData || []).forEach((item) => {

Comment on lines +618 to +619

const selectedStructureCodes = campaignData?.flatMap((cycle) =>
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor duplicated logic for selectedStructureCodes into a helper function

The computation of selectedStructureCodes at lines 618-619 is duplicated elsewhere in the code (lines 923-924). To improve maintainability and reduce code duplication, consider extracting this logic into a reusable helper function.

Here's how you can refactor the code:

+ const getSelectedStructureCodes = (campaignData) =>
+   campaignData?.flatMap((cycle) =>
+     cycle?.deliveries?.flatMap((delivery) =>
+       delivery?.deliveryRules?.flatMap((rule) =>
+         rule?.attributes?.map((attribute) => attribute?.value)
+       )
+     )
+   );

...

- const selectedStructureCodes = campaignData?.flatMap((cycle) =>
-   cycle?.deliveries?.flatMap((delivery) =>
-     delivery?.deliveryRules?.flatMap((rule) =>
-       rule?.attributes?.map((attribute) => attribute?.value)
-     )
-   )
- );

+ const selectedStructureCodes = getSelectedStructureCodes(campaignData);

Then, replace other occurrences of this computation with getSelectedStructureCodes(campaignData).

📝 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 selectedStructureCodes = campaignData?.flatMap((cycle) =>
const getSelectedStructureCodes = (campaignData) =>
campaignData?.flatMap((cycle) =>
cycle?.deliveries?.flatMap((delivery) =>
delivery?.deliveryRules?.flatMap((rule) =>
rule?.attributes?.map((attribute) => attribute?.value)
)
)
);
const selectedStructureCodes = getSelectedStructureCodes(campaignData);

Comment on lines +923 to +924
const selectedStructureCodes = campaignData?.flatMap((cycle) =>
cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes.map((attribute) => attribute?.value)))
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add missing optional chaining to prevent potential runtime errors

At lines 923-924, the optional chaining operator ?. is missing before attributes. If attributes is undefined, this could cause a runtime error when attempting to call .map() on undefined. Please add optional chaining for safer property access.

Apply this diff to fix the issue:

-     cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule.attributes.map((attribute) => attribute?.value)))
+     cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes?.map((attribute) => attribute?.value)))
📝 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 selectedStructureCodes = campaignData?.flatMap((cycle) =>
cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes.map((attribute) => attribute?.value)))
const selectedStructureCodes = campaignData?.flatMap((cycle) =>
cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes?.map((attribute) => attribute?.value)))

Comment on lines +238 to +240
attributes.push({
key: attributes.length + 1,
value,
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix Order of fromValue and toValue in IN_BETWEEN Condition Construction.

In the processDoseCriteria function, when handling the IN_BETWEEN operator, the condition string appears to have fromValue and toValue swapped:

return `${attr.toValue} <= ${attr.attribute.code} < ${attr.fromValue}`;

This might be incorrect, as usually fromValue should be less than toValue. The correct condition should be:

- return `${attr.toValue} <= ${attr.attribute.code} < ${attr.fromValue}`;
+ return `${attr.fromValue} <= ${attr.attribute.code} < ${attr.toValue}`;

Comment on lines +223 to +230
const fromValue = parts[4];
attributes.push({
key: 1,
operator: { code: operatorMapping["IN_BETWEEN"] },
attribute: { code: parts[2] },
fromValue,
toValue,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct fromValue and toValue Assignment in reverseDeliveryRemap.

In the parseConditionAndCreateRules function within reverseDeliveryRemap, the fromValue and toValue may be incorrectly assigned when parsing IN_BETWEEN conditions:

const toValue = parts[0];
const fromValue = parts[4];

This assignment seems reversed. The correct assignment should be:

- const toValue = parts[0];
- const fromValue = parts[4];
+ const fromValue = parts[0];
+ const toValue = parts[4];

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