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-700, HCMPRE-701 and HCMPRE-741 #1471

Merged
merged 5 commits into from
Oct 8, 2024
Merged

HCMPRE-700, HCMPRE-701 and HCMPRE-741 #1471

merged 5 commits into from
Oct 8, 2024

Conversation

Bhavya-egov
Copy link
Contributor

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

Summary by CodeRabbit

  • New Features

    • Introduced a new asynchronous hook for product variant search.
    • Enhanced campaign configuration management with new delivery configuration logic.
  • Bug Fixes

    • Adjusted validation logic for product names and variants to improve user experience.
  • Documentation

    • Updated external stylesheet links to the latest versions for improved styling.
  • Refactor

    • Streamlined delivery rules handling in various components to reduce complexity.
    • Simplified data flow in the SetupCampaign component by removing complex restructuring logic.
  • Chores

    • Removed unused functions and commented-out code to clean up the codebase.

Copy link
Contributor

coderabbitai bot commented Oct 7, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request includes updates to several files within the campaign manager module and related components. Key changes involve updating external CSS stylesheet links in HTML files, refactoring functions in JavaScript components, and introducing a new hook for product variant search. Additionally, several functions have been commented out or removed, indicating a shift in how data is processed and managed within the application. The overall structure of the components remains largely intact, with a focus on enhancing data handling and user interactions.

Changes

File Change Summary
health/micro-ui/web/micro-ui-internals/example/public/index.html Updated stylesheet links for digit-ui-css and digit-ui-components-css to versions 1.8.2-beta.34 and 0.0.2-beta.36, respectively.
health/micro-ui/web/public/index.html Similar updates to the stylesheet links for digit-ui-css and digit-ui-components-css.
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js Added variable modulePrefix and updated useStore hook; modified componentsToRegister to map CreateQuestion to CreateQuestionContext.
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignSummary.js Restructured the cards array for the CampaignSummary component for improved clarity and navigation.
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DataUploadSummary.js Commented out several functions (loopAndReturn, reverseDeliveryRemap) and parts of useEffect, disabling their functionality.
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DeliveryDetailsSummary.js Refactored reverseDeliveryRemap and loopAndReturn functions; updated logic for processing delivery data using cycleIndex and deliveryIndex.
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DetailsTable.js Added import for operators from ajv; modified data computation logic to handle operator.code for "IN_BETWEEN".
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js Modified preProcess and additionalCustomizations methods for various campaign configurations to enhance functionality and data processing.
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useProductVariantSearch.js Introduced a new asynchronous hook for searching product variants based on variantId and tenantId.
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/AddProduct.js Adjusted validation logic for product names and variants; introduced a Set to track unique combinations during processing.
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.js Updated delivery configuration management, including new import for getDeliveryConfig and modified parameters for useCustomMDMS.
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js Removed reverseDeliveryRemap and restructureData functions; simplified handling of delivery rules.
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/index.js Updated to use getDeliveryConfig for fetching delivery configuration data; removed previous logic accessing deliveryConfig.
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js Introduced a new function to process delivery configurations based on project types, including helper functions for parsing conditions and generating configurations.

Possibly related PRs

Suggested reviewers

  • jagankumar-egov

Poem

In the garden where code does bloom,
Stylesheets updated, dispelling gloom.
Functions refactored, logic anew,
Campaigns now brighter, with a clearer view.
Hops of joy for changes made,
In the world of code, let’s dance and parade! 🐰✨


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.

Actionable comments posted: 22

🧹 Outside diff range comments (2)
health/micro-ui/web/micro-ui-internals/example/public/index.html (1)

Line range hint 12-30: Consider optimizing CSS imports and removing commented code

There are multiple CSS stylesheets being loaded, and some are commented out. This could potentially lead to styling conflicts or unexpected behavior. Additionally, keeping commented-out code in production files is generally not recommended.

Consider the following suggestions:

  1. Review and consolidate the CSS imports to ensure only the necessary stylesheets are loaded.
  2. Remove commented-out code if it's no longer needed, or add clear comments explaining why certain lines are kept for future reference.
  3. If different stylesheet versions are being tested, consider using a more systematic approach for managing these variations, such as feature flags or environment-specific configurations.

Would you like assistance in optimizing these imports or cleaning up the commented code?

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

Line range hint 41-46: Consider increasing the minimum length for product names.

The validation now allows product names as short as 1 character. This might lead to less meaningful or potentially confusing product names. Consider increasing the minimum length to ensure more descriptive product names.

-if (i?.name?.length >= 1 && i?.name?.length < 101) {
+if (i?.name?.length >= 3 && i?.name?.length < 101) {

This change would require product names to be at least 3 characters long, which is more likely to result in meaningful names while still allowing flexibility.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between f2cf379 and a44eb1e.

📒 Files selected for processing (13)
  • health/micro-ui/web/micro-ui-internals/example/public/index.html (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DataUploadSummary.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DeliveryDetailsSummary.js (4 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DetailsTable.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js (0 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useProductVariantSearch.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/AddProduct.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (7 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/index.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (1 hunks)
  • health/micro-ui/web/public/index.html (1 hunks)
💤 Files with no reviewable changes (1)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js
🧰 Additional context used
📓 Path-based instructions (10)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.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/index.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

🪛 Biome
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DeliveryDetailsSummary.js

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

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

(lint/correctness/noUnsafeOptionalChaining)


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

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

(lint/correctness/noUnsafeOptionalChaining)

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useProductVariantSearch.js

[error] 15-15: 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)

🔇 Additional comments (23)
health/micro-ui/web/micro-ui-internals/example/public/index.html (3)

Line range hint 32-32: Verify global configuration loading

The file loads a global configuration script using an environment variable (%REACT_APP_GLOBAL%).

While using environment variables for configuration is a good practice, please ensure that:

  1. The correct configuration is loaded in each environment (development, staging, production).
  2. Sensitive information is not exposed through this global configuration.

Consider running the following script to check the usage of this global configuration:

#!/bin/bash
# Description: Check usage of global configuration

# Test: Search for usage of globalConfigs or window.globalConfigs
rg --type javascript --type typescript -g '!node_modules' -i '(globalConfigs|window\.globalConfigs)'

# Test: Look for any TODO or FIXME comments related to configuration
rg --type javascript --type typescript -g '!node_modules' -i '(TODO|FIXME).*config'

21-21: Confirm the update of digit-ui-components-css version

The version of digit-ui-components-css has been updated from 0.0.2-beta.34 to 0.0.2-beta.36.

While this is a smaller version jump compared to the previous change, please ensure that this update is intentional and compatible with the rest of the application. Consider running the following script to check for any potential issues:

#!/bin/bash
# Description: Check for potential issues with digit-ui-components-css update

# Test: Search for custom component styles that might be affected by the update
rg --type css -g '!node_modules' -i 'digit-ui-components'

# Test: Look for any component-related TODO or FIXME comments
rg --type html --type javascript --type typescript -g '!node_modules' -i '(TODO|FIXME).*component'

17-17: Verify the intentional update of digit-ui-css version

The version of digit-ui-css has been updated from 1.8.2-beta.11 to 1.8.2-beta.34. This is a significant jump within the same minor version.

Please confirm that this update is intentional and that it doesn't introduce any breaking changes or unexpected behavior in the UI. Consider running the following script to check for any potential issues:

health/micro-ui/web/public/index.html (1)

11-12: 🧹 Nitpick (assertive)

CSS library versions updated - verify visual consistency

The changes update two CSS libraries to newer versions:

  1. @egovernments/digit-ui-css: 1.8.2-beta.11 → 1.8.2-beta.34
  2. @egovernments/digit-ui-components-css: 0.0.2-beta.34 → 0.0.2-beta.36

While these updates likely include improvements and bug fixes, please ensure that:

  1. The application's visual appearance and functionality remain consistent after these updates.
  2. You've reviewed the changelogs for these libraries to understand any breaking changes or new features.

To verify the impact of these changes, please run the following commands:

Consider the following improvements:

  1. Add integrity hashes to the link tags for enhanced security. For example:
    <link rel="stylesheet" href="https://unpkg.com/@egovernments/digit-ui-css@1.8.2-beta.34/dist/index.css" 
          integrity="sha384-[calculated-hash]" crossorigin="anonymous">
  2. Host these CSS files locally to reduce dependency on external CDNs and improve load reliability.
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/AddProduct.js (3)

Line range hint 51-56: Approved: Improved validation for product variants.

The change to require at least 2 characters for product variants is a good improvement. It ensures more meaningful variant names while maintaining the upper limit of 100 characters.


89-96: No additional comments needed.

This segment has been addressed in the previous comment about efficient handling of unique product-variant combinations.


90-96: No additional comments needed.

This segment has been addressed in the previous comments about efficient handling of unique product-variant combinations.

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

Line range hint 123-123: Verify usage of CreateQuestionContext

The mapping of CreateQuestion to CreateQuestionContext in the componentsToRegister object looks good. This change suggests a refactoring of the CreateQuestion component, possibly to use React's Context API.

To ensure this change doesn't introduce any issues, please verify that all usages of CreateQuestion in the application are compatible with the new CreateQuestionContext. Run the following script to check for any potential issues:

Review the results to ensure that all usages are consistent with this change.

✅ Verification successful

Verification Successful: CreateQuestionContext Mapping

The mapping of CreateQuestion to CreateQuestionContext has been successfully verified. All usages are consistent and compatible with the new context mapping.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usages of CreateQuestion and CreateQuestionContext

# Search for CreateQuestion usages
echo "Searching for CreateQuestion usages:"
rg --type js "CreateQuestion" -g '!Module.js'

# Search for CreateQuestionContext usages
echo "Searching for CreateQuestionContext usages:"
rg --type js "CreateQuestionContext" -g '!Module.js'

Length of output: 3863

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

77-77: ⚠️ Potential issue

Verify potential off-by-one error when decrementing toValue.

At line 77, you subtract 1 from toValue:

toValue: toValue ? toValue - 1 : null,

Subtracting 1 from toValue may introduce an off-by-one error, depending on the intended logical conditions. Ensure that this decrement aligns with the business logic and that it does not exclude the intended upper boundary value.

Suggested Action:

Double-check the requirement for the toValue. If the condition should include the maxValue, you might not need to subtract 1. If the subtraction is intentional, consider adding a comment to explain why.


135-144: ⚠️ Potential issue

Ensure consistent attribute configuration keys across functions.

In generateBednetConfig, the attribute configuration objects do not include fromValue and toValue keys, unlike the objects in generateMRDNConfig. This inconsistency may lead to issues when consuming these configurations elsewhere in your application.

Suggested Fix:

Include fromValue and toValue in the attribute configurations within generateBednetConfig, even if they are null or unused. This ensures a consistent data structure.

return {
  key: index + 1 + subIndex,
  label: "Custom",
  attrType: criteria.attrType,
  attrValue: value?.variable,
  operatorValue: operatorValue,
  value: value?.comparisonValue,
+ fromValue: fromValue,
+ toValue: toValue,
};

Likely invalid or redundant comment.


153-163: ⚠️ Potential issue

Handle asynchronous functions correctly in deliveryConfig.

If generateMRDNConfig and generateBednetConfig become asynchronous due to the use of await, the deliveryConfig function should also be marked as async. Additionally, ensure that all callers of deliveryConfig handle the returned Promise appropriately.

Suggested Fix:

Mark deliveryConfig as async:

- const deliveryConfig = ({ data, projectType }) => {
+ const deliveryConfig = async ({ data, projectType }) => {

Update the switch cases to await the asynchronous functions:

switch (projectType) {
  case "MR-DN":
-   return generateMRDNConfig(data?.cycles?.[0]?.deliveries, projectType);
+   return await generateMRDNConfig(data?.cycles?.[0]?.deliveries, projectType);
  case "LLIN-mz":
  case "IRS-mz":
-   return generateBednetConfig(data?.cycles?.[0]?.deliveries, projectType);
+   return await generateBednetConfig(data?.cycles?.[0]?.deliveries, projectType);
  default:
    return [];
}

Ensure that any function calling deliveryConfig handles it as a Promise.

Likely invalid or redundant comment.

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

6-6: Import statement for getDeliveryConfig is correct

The new import statement correctly brings in the getDeliveryConfig utility function.

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DeliveryDetailsSummary.js (2)

77-77: LGTM!

The return statement correctly spreads the object i and returns it. The code is clear and functions as intended.


88-125: Ensure commenting out reverseDeliveryRemap does not affect functionality

The entire logic of the reverseDeliveryRemap function has been commented out, and it now simply returns the input data. If other parts of the application rely on the processing done within this function, this change could lead to unexpected behavior or bugs.

Run the following script to identify all usages of reverseDeliveryRemap and assess the impact:

This will help you determine if the function can be safely altered or if the original logic needs to be preserved.

✅ Verification successful

Verified: reverseDeliveryRemap is not used in active code

After reviewing the codebase, all usages of reverseDeliveryRemap are currently commented out. This ensures that commenting out the function does not impact the application's functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all occurrences of 'reverseDeliveryRemap' in the codebase to verify its usage.

# Expected: List all places where 'reverseDeliveryRemap' is invoked.

rg --type js 'reverseDeliveryRemap' -A 5 -B 5

Length of output: 11858

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

5-5: Verify the import path for getDeliveryConfig

Please ensure that the getDeliveryConfig module exists at the specified path "../../../utils/getDeliveryConfig" and that it exports the required function correctly. This helps prevent import errors at runtime.


26-27: Confirm the MDMS module name and data structure

The module name "HCM-PROJECT-TYPES" is used in the useCustomMDMS hook. Please verify that this is the correct MDMS module name and that it contains the projectTypes data as expected.

Run the following script to check the available MDMS modules and their contents:

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

177-222: Remove obsolete commented-out functions

The restructureData function and its helper functions are commented out from lines 177 to 222. If these functions are no longer required, consider deleting them to maintain a clean codebase.


433-434: Ensure deliveryRule is in the expected format after removing reverseDeliveryRemap

By directly assigning deliveryRule: delivery on line 434, verify that the delivery object structure matches what is expected downstream. Previously, reverseDeliveryRemap might have transformed delivery into the required format. Confirm that all parts of the application using deliveryRule can handle the new structure without issues.


500-573: Clean up commented-out restructureData function

The restructureData function, along with its internal logic, is commented out from lines 500 to 573. If this code is no longer necessary, removing it will enhance code clarity.


614-616: Verify the structure of payloadData.deliveryRules after bypassing restructureData

On line 616, payloadData.deliveryRules is assigned directly from totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule. Ensure that this data now aligns with what the backend API expects, as restructureData was previously used to format it appropriately.


686-688: Confirm deliveryRules format is acceptable for the API

At line 688, check that the direct assignment of payloadData.deliveryRules without restructuring still conforms to the API's expected data schema. This is crucial to prevent potential data processing errors on the server side.


751-753: Ensure deliveryRules meet backend requirements after changes

By directly assigning payloadData.deliveryRules on line 753, confirm that the data meets all necessary backend requirements, especially since the transformation via restructureData is no longer applied.


815-817: Check deliveryRules consistency with expected data structure

On line 817, since restructureData is no longer used, verify that payloadData.deliveryRules has the correct structure and includes all required fields as per the backend's expectations.

@@ -61,6 +61,7 @@ const CampaignModule = ({ stateCode, userType, tenants }) => {
});

const hierarchyData = Digit.Hooks.campaign.useBoundaryRelationshipSearch({BOUNDARY_HIERARCHY_TYPE,tenantId});
// const modulePrefix = "hcm";
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)

Consider removing or explaining commented-out code

There are two instances of commented-out code related to modulePrefix:

  1. Line 64: // const modulePrefix = "hcm";
  2. Line 73: // modulePrefix,

Commented-out code can lead to confusion and make the codebase harder to maintain. If this code is no longer needed, consider removing it entirely. If it's kept for future use, add a TODO comment explaining why it's there and when it might be needed.

If you decide to keep the code, consider adding a comment like this:

// TODO: modulePrefix might be needed for future implementation of X feature. Keeping it commented out until then.
// const modulePrefix = "hcm";

Also applies to: 73-73

Comment on lines +14 to +33
const temp = rowsData.map((i) => {
if (i?.operator?.code === "IN_BETWEEN") {
return {
...i,
value: `${i?.toValue ? i?.toValue : "N/A"} to ${i?.fromValue ? i?.fromValue : "N/A"}`,
operator: t(i?.operator?.code) || t(i?.operator),
attribute: i?.attribute?.code || i?.attribute ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.code?.toUpperCase()}`) : "",
};
}
else{
return{
...i,
operator: t(i?.operator),
attribute: i?.attribute ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.toUpperCase()}`) : "",
}));
operator: t(i?.operator?.code) || t(i?.operator),
attribute: i?.attribute?.code
? t(`CAMPAIGN_ATTRIBUTE_${i.attribute.code.toUpperCase()}`)
: i?.attribute
? t(`CAMPAIGN_ATTRIBUTE_${i.attribute}`)
: "",
}
}});
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 mapping function to reduce duplication and improve readability

The current mapping function contains duplicated code and complex conditional logic. Refactoring can enhance readability and maintainability.

Consider the following refactored version:

const temp = rowsData.map((i) => {
  const attribute = i?.attribute?.code
    ? t(`CAMPAIGN_ATTRIBUTE_${i.attribute.code.toUpperCase()}`)
    : i?.attribute
    ? t(`CAMPAIGN_ATTRIBUTE_${i.attribute}`)
    : "";

  const operator = t(i?.operator?.code) || t(i?.operator);

  const value =
    i?.operator?.code === "IN_BETWEEN"
      ? `${i?.fromValue ? i?.fromValue : "N/A"} to ${i?.toValue ? i?.toValue : "N/A"}`
      : i?.value;

  return {
    ...i,
    attribute,
    operator,
    value,
  };
});

Comment on lines +27 to +31
attribute: i?.attribute?.code
? t(`CAMPAIGN_ATTRIBUTE_${i.attribute.code.toUpperCase()}`)
: i?.attribute
? t(`CAMPAIGN_ATTRIBUTE_${i.attribute}`)
: "",
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

Ensure safe optional chaining for 'attribute' properties

To prevent potential runtime errors when i.attribute or i.attribute.code is undefined, ensure that optional chaining is consistently used.

Suggested change:

          attribute: i?.attribute?.code 
-            ? t(`CAMPAIGN_ATTRIBUTE_${i.attribute.code.toUpperCase()}`) 
+            ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.code?.toUpperCase()}`) 
            : i?.attribute 
-            ? t(`CAMPAIGN_ATTRIBUTE_${i.attribute}`) 
+            ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute}`) 
            : "",
📝 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
attribute: i?.attribute?.code
? t(`CAMPAIGN_ATTRIBUTE_${i.attribute.code.toUpperCase()}`)
: i?.attribute
? t(`CAMPAIGN_ATTRIBUTE_${i.attribute}`)
: "",
attribute: i?.attribute?.code
? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.code?.toUpperCase()}`)
: i?.attribute
? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute}`)
: "",

if (i?.operator?.code === "IN_BETWEEN") {
return {
...i,
value: `${i?.toValue ? i?.toValue : "N/A"} to ${i?.fromValue ? i?.fromValue : "N/A"}`,
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

Reverse 'fromValue' and 'toValue' in the range display

In the value assignment, the 'toValue' and 'fromValue' appear to be reversed. Typically, a range is displayed as 'fromValue to toValue'. Consider swapping them for correct representation.

Suggested change:

-          value: `${i?.toValue ? i?.toValue : "N/A"}  to ${i?.fromValue ? i?.fromValue : "N/A"}`,
+          value: `${i?.fromValue ? i?.fromValue : "N/A"} to ${i?.toValue ? i?.toValue : "N/A"}`,
📝 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
value: `${i?.toValue ? i?.toValue : "N/A"} to ${i?.fromValue ? i?.fromValue : "N/A"}`,
value: `${i?.fromValue ? i?.fromValue : "N/A"} to ${i?.toValue ? i?.toValue : "N/A"}`,

...i,
value: `${i?.toValue ? i?.toValue : "N/A"} to ${i?.fromValue ? i?.fromValue : "N/A"}`,
operator: t(i?.operator?.code) || t(i?.operator),
attribute: i?.attribute?.code || i?.attribute ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.code?.toUpperCase()}`) : "",
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 logical error in 'attribute' field assignment

The current logic for the 'attribute' field may not work as intended due to operator precedence. The expression could always evaluate to t(...), even when i?.attribute?.code is undefined.

Suggested change:

-          attribute: i?.attribute?.code ||  i?.attribute ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.code?.toUpperCase()}`) : "",
+          attribute: i?.attribute?.code
+            ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.code?.toUpperCase()}`)
+            : i?.attribute
+            ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute}`)
+            : "",
📝 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
attribute: i?.attribute?.code || i?.attribute ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.code?.toUpperCase()}`) : "",
attribute: i?.attribute?.code
? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.code?.toUpperCase()}`)
: i?.attribute
? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute}`)
: "",

Comment on lines +41 to +80
// function loopAndReturn(dataa, t) {
// let newArray = [];
// const data = dataa?.map((i) => ({ ...i, operator: i?.operator, attribute: i?.attribute }));

data.forEach((item) => {
// Check if an object with the same attribute already exists in the newArray
const existingIndex = newArray.findIndex((element) => element.attribute === item.attribute);
if (existingIndex !== -1) {
// If an existing item is found, replace it with the new object
const existingItem = newArray[existingIndex];
newArray[existingIndex] = {
attribute: existingItem.attribute,
operator: "IN_BETWEEN",
toValue: existingItem.value && item.value ? Math.min(existingItem.value, item.value) : null,
fromValue: existingItem.value && item.value ? Math.max(existingItem.value, item.value) : null,
};
} else if (item?.operator === "EQUAL_TO") {
newArray.push({
...item,
value: item?.value ? t(item?.value) : null,
});
} else {
newArray.push(item);
}
});
// data.forEach((item) => {
// // Check if an object with the same attribute already exists in the newArray
// const existingIndex = newArray.findIndex((element) => element.attribute === item.attribute);
// if (existingIndex !== -1) {
// // If an existing item is found, replace it with the new object
// const existingItem = newArray[existingIndex];
// newArray[existingIndex] = {
// attribute: existingItem.attribute,
// operator: "IN_BETWEEN",
// toValue: existingItem.value && item.value ? Math.min(existingItem.value, item.value) : null,
// fromValue: existingItem.value && item.value ? Math.max(existingItem.value, item.value) : null,
// };
// } else if (item?.operator === "EQUAL_TO") {
// newArray.push({
// ...item,
// value: item?.value ? t(item?.value) : null,
// });
// } else {
// newArray.push(item);
// }
// });

const withKey = newArray.map((i, c) => ({ key: c + 1, ...i }));
const format = withKey.map((i) => {
if (i.operator === "IN_BETWEEN") {
return {
...i,
value: `${i?.toValue ? i?.toValue : "N/A"} to ${i?.fromValue ? i?.fromValue : "N/A"}`,
};
}
return {
...i,
};
});
return format;
}
// const withKey = newArray.map((i, c) => ({ key: c + 1, ...i }));
// const format = withKey.map((i) => {
// if (i.operator === "IN_BETWEEN") {
// return {
// ...i,
// value: `${i?.toValue ? i?.toValue : "N/A"} to ${i?.fromValue ? i?.fromValue : "N/A"}`,
// };
// }
// return {
// ...i,
// };
// });
// return format;
// }
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)

Consider removing the commented-out function loopAndReturn

The function loopAndReturn has been commented out. If this function is no longer needed, consider removing it to keep the codebase clean and maintainable.


💡 Codebase verification

References to loopAndReturn and reverseDeliveryRemap exist in multiple files, which may lead to runtime errors since these functions are commented out. Please review and remove or update these references accordingly:

  • src/pages/employee/SetupCampaign.js
  • src/components/DeliveryDetailsSummary.js
  • src/components/CampaignSummary.js
🔗 Analysis chain

Verify there are no remaining references to the commented-out functions

Since loopAndReturn and reverseDeliveryRemap have been commented out, ensure that there are no remaining references to these functions elsewhere in the codebase to prevent potential runtime errors.

Run the following script to check for any references:

Also applies to: 82-123

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for references to `loopAndReturn` and `reverseDeliveryRemap` in the codebase.

# Test: Find all occurrences of `loopAndReturn` and `reverseDeliveryRemap` excluding commented lines.
# Expect: No matches found.

rg '^[^/\n]*\b(loopAndReturn|reverseDeliveryRemap)\b' --type js --type jsx --type ts --type tsx --glob '!DataUploadSummary.js'

Length of output: 156


Script:

#!/bin/bash
# Description: Search for references to `loopAndReturn` and `reverseDeliveryRemap` in the codebase.

# Test: Find all occurrences of `loopAndReturn` and `reverseDeliveryRemap` excluding commented lines.
# Expect: No matches found.

rg '^[^/\n]*\b(loopAndReturn|reverseDeliveryRemap)\b' \
   -g '*.js' -g '*.jsx' -g '*.ts' -g '*.tsx' \
   --glob '!DataUploadSummary.js'

Length of output: 1362

Comment on lines +82 to +123
// function reverseDeliveryRemap(data, t) {
// if (!data) return null;
// const reversedData = [];
// let currentCycleIndex = null;
// let currentCycle = null;

data.forEach((item, index) => {
if (currentCycleIndex !== item.cycleNumber) {
currentCycleIndex = item.cycleNumber;
currentCycle = {
cycleIndex: currentCycleIndex.toString(),
startDate: item?.startDate ? Digit.Utils.date.convertEpochToDate(item?.startDate) : null,
endDate: item?.endDate ? Digit.Utils.date.convertEpochToDate(item?.endDate) : null,
active: index === 0, // Initialize active to false
deliveries: [],
};
reversedData.push(currentCycle);
}
// data.forEach((item, index) => {
// if (currentCycleIndex !== item.cycleNumber) {
// currentCycleIndex = item.cycleNumber;
// currentCycle = {
// cycleIndex: currentCycleIndex.toString(),
// startDate: item?.startDate ? Digit.Utils.date.convertEpochToDate(item?.startDate) : null,
// endDate: item?.endDate ? Digit.Utils.date.convertEpochToDate(item?.endDate) : null,
// active: index === 0, // Initialize active to false
// deliveries: [],
// };
// reversedData.push(currentCycle);
// }

const deliveryIndex = item.deliveryNumber.toString();
// const deliveryIndex = item.deliveryNumber.toString();

let delivery = currentCycle.deliveries.find((delivery) => delivery.deliveryIndex === deliveryIndex);
// let delivery = currentCycle.deliveries.find((delivery) => delivery.deliveryIndex === deliveryIndex);

if (!delivery) {
delivery = {
deliveryIndex: deliveryIndex,
active: item.deliveryNumber === 1, // Set active to true only for the first delivery
deliveryRules: [],
};
currentCycle.deliveries.push(delivery);
}
// if (!delivery) {
// delivery = {
// deliveryIndex: deliveryIndex,
// active: item.deliveryNumber === 1, // Set active to true only for the first delivery
// deliveryRules: [],
// };
// currentCycle.deliveries.push(delivery);
// }

delivery.deliveryRules.push({
ruleKey: item.deliveryRuleNumber,
delivery: {},
attributes: loopAndReturn(item.conditions, t),
products: [...item.products],
});
});
// delivery.deliveryRules.push({
// ruleKey: item.deliveryRuleNumber,
// delivery: {},
// attributes: loopAndReturn(item.conditions, t),
// products: [...item.products],
// });
// });

return reversedData;
}
// return reversedData;
// }
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)

Consider removing the commented-out function reverseDeliveryRemap

The function reverseDeliveryRemap has been commented out. If it's no longer required, removing it can improve code readability and reduce clutter.

Comment on lines +30 to +31
const temp= getDeliveryConfig({data: data?.["HCM-PROJECT-TYPES"], projectType:selectedProjectType});
return temp;
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 the data access path in getDeliveryConfig

The data being passed to getDeliveryConfig is accessed as data?.["HCM-PROJECT-TYPES"]. However, the MDMS response typically contains data under the MdmsRes key. To ensure the correct data is retrieved, please adjust the access path.

Apply this diff to fix the data access:

- const temp= getDeliveryConfig({data: data?.["HCM-PROJECT-TYPES"], projectType:selectedProjectType});
+ const temp= getDeliveryConfig({data: data?.MdmsRes?.["HCM-PROJECT-TYPES"], projectType: selectedProjectType});
📝 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 temp= getDeliveryConfig({data: data?.["HCM-PROJECT-TYPES"], projectType:selectedProjectType});
return temp;
const temp= getDeliveryConfig({data: data?.MdmsRes?.["HCM-PROJECT-TYPES"], projectType: selectedProjectType});
return temp;

Comment on lines 134 to 175
// function reverseDeliveryRemap(data) {
// if (!data) return null;
// const reversedData = [];
// let currentCycleIndex = null;
// let currentCycle = null;

const deliveryIndex = item.deliveryNumber.toString();
// data.forEach((item, index) => {
// if (currentCycleIndex !== item.cycleNumber) {
// currentCycleIndex = item.cycleNumber;
// currentCycle = {
// cycleIndex: currentCycleIndex.toString(),
// active: index === 0, // Initialize active to false
// deliveries: [],
// };
// reversedData.push(currentCycle);
// }

let delivery = currentCycle.deliveries.find((delivery) => delivery.deliveryIndex === deliveryIndex);
// const deliveryIndex = item.deliveryNumber.toString();

if (!delivery) {
delivery = {
deliveryIndex: deliveryIndex,
active: item.deliveryNumber === 1, // Set active to true only for the first delivery
deliveryRules: [],
};
currentCycle.deliveries.push(delivery);
}
// let delivery = currentCycle.deliveries.find((delivery) => delivery.deliveryIndex === deliveryIndex);

delivery.deliveryRules.push({
ruleKey: item.deliveryRuleNumber,
delivery: {},
deliveryType: item?.deliveryType,
attributes: loopAndReturn(item.conditions),
products: [...item.products],
});
});
// if (!delivery) {
// delivery = {
// deliveryIndex: deliveryIndex,
// active: item.deliveryNumber === 1, // Set active to true only for the first delivery
// deliveryRules: [],
// };
// currentCycle.deliveries.push(delivery);
// }

// delivery.deliveryRules.push({
// ruleKey: item.deliveryRuleNumber,
// delivery: {},
// deliveryType: item?.deliveryType,
// attributes: loopAndReturn(item.conditions),
// products: [...item.products],
// });
// });

// return reversedData;
// }

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

Consider removing commented-out code for better maintainability

The large block of commented-out code from lines 134 to 175 (reverseDeliveryRemap function) can be removed to improve code readability and maintainability. If this code is no longer needed, it's advisable to remove it from the codebase to keep it clean and avoid confusion.

Comment on lines +580 to +584
// useEffect(async () => {
// if (totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule) {
// const temp = restructureData(totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule);
// }
// }, [shouldUpdate]);
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

Consider removing unused useEffect hook

The useEffect hook commented out from lines 580 to 584 is no longer in use. To improve code readability and maintainability, consider removing it if it's not needed.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between a44eb1e and b238070.

📒 Files selected for processing (13)
  • health/micro-ui/web/micro-ui-internals/example/public/index.html (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DataUploadSummary.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DeliveryDetailsSummary.js (4 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DetailsTable.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js (0 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useProductVariantSearch.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/AddProduct.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (7 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/index.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (1 hunks)
  • health/micro-ui/web/public/index.html (1 hunks)
💤 Files with no reviewable changes (1)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js
🧰 Additional context used
📓 Path-based instructions (10)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.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/index.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

🪛 Biome
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DeliveryDetailsSummary.js

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

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

(lint/correctness/noUnsafeOptionalChaining)


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

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

(lint/correctness/noUnsafeOptionalChaining)

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useProductVariantSearch.js

[error] 15-15: 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)

🔇 Additional comments (22)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useProductVariantSearch.js (1)

1-1: LGTM: Function signature and structure are well-defined.

The hook is correctly exported as a named constant and uses an async arrow function, which is appropriate for handling API calls. The destructuring of input parameters is a clean approach.

health/micro-ui/web/micro-ui-internals/example/public/index.html (3)

17-17: LGTM! Verify compatibility with the new CSS version.

The update to the newer version of digit-ui-css (1.8.2-beta.34) is approved. This change likely introduces new features or bug fixes.

Please ensure that this new version is compatible with your current implementation and doesn't introduce any unexpected visual changes or breaks in the UI. Consider running the following command to check for any potential issues:

#!/bin/bash
# Description: Check for potential CSS-related issues after updating digit-ui-css version

# Test: Search for any TODO comments or console.log statements related to CSS issues
rg --type js --type jsx -i "(TODO|FIXME|XXX|console\.log).*css" ./src

17-20: Summary: CSS stylesheet versions updated

Both digit-ui-css and digit-ui-components-css have been updated to newer versions. These changes are likely to introduce improvements, new features, or bug fixes to the UI and components.

To ensure these updates don't introduce any unexpected issues, please:

  1. Test the application thoroughly, paying special attention to UI elements and component styling.
  2. Review the changelogs for both digit-ui-css and digit-ui-components-css to understand what changes have been introduced in these new versions.
  3. Run the following command to check for any recent CSS-related changes in your codebase that might be affected by these updates:
#!/bin/bash
# Description: Check for recent CSS-related changes in the codebase

# Test: List CSS files modified in the last 30 days
git log --name-only --since="30 days ago" --pretty=format: | sort -u | grep '\.css$'

20-20: LGTM! Verify compatibility with the new components CSS version.

The update to the newer version of digit-ui-components-css (0.0.2-beta.36) is approved. This minor version bump likely includes small improvements or bug fixes.

Please ensure that this new version is compatible with your current implementation and doesn't introduce any unexpected changes in component styling. Consider running the following command to check for any potential issues:

health/micro-ui/web/public/index.html (1)

11-12: 🧹 Nitpick (assertive)

Verify compatibility with updated CSS versions

The stylesheet versions have been updated:

  • @egovernments/digit-ui-css: 1.8.2-beta.11 → 1.8.2-beta.34
  • @egovernments/digit-ui-components-css: 0.0.2-beta.34 → 0.0.2-beta.36

While these updates likely include improvements and bug fixes, please ensure:

  1. The application's UI remains consistent with these new versions.
  2. There are no unintended side effects or breaking changes introduced.

To verify the impact of these changes, you can run the following script:

Consider consolidating the different versions of @egovernments/digit-ui-css being used (1.8.0-alpha.6, 1.8.2-beta.34, 1.0.75-campaign, 1.0.50-microplan) to maintain consistency and reduce potential conflicts.

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

Line range hint 1-185: Overall assessment: Changes improve data handling with minor adjustments to validation.

The modifications to this file enhance data integrity by preventing duplicate processing of product-variant combinations. The relaxed validation rules for product names and variants provide more flexibility but should be verified against business requirements. Consider the suggested refactoring to further improve code readability. Overall, the changes appear to be well-implemented and align with the intended objectives.


87-96: 🧹 Nitpick (assertive)

Efficient handling of unique product-variant combinations: Consider refactoring.

The introduction of usedCombinations Set effectively prevents duplicate processing of product-variant combinations, improving data integrity. This is a good improvement.

As suggested in a previous review, consider extracting the combination check into a separate function for improved readability:

const isUniqueCombination = (name, variant) => {
  const combination = `${name}-${variant}`;
  if (!usedCombinations.has(combination)) {
    usedCombinations.add(combination);
    return true;
  }
  return false;
};

// Then use it in the find function:
const target = formData?.["addProduct"]?.find((f) => 
  f.name === i.name && isUniqueCombination(f.name, f.variant)
);

This refactoring would improve code readability and maintainability.


Line range hint 51-56: Product variant validation adjusted: Verify business requirements.

The minimum length requirement for product variants has been slightly relaxed, now allowing 2-character variants. Ensure this aligns with your business requirements and doesn't conflict with any existing variant naming conventions.

Let's check for consistency across the codebase:

#!/bin/bash
# Search for other product variant validations
rg --type js 'variant.*length.*(?:>=|>).*2.*&&.*variant.*length.*<.*101' -g '!AddProduct.js'

Line range hint 41-46: Product name validation relaxed: Consider implications.

The minimum length requirement for product names has been reduced from 3 characters to 1. While this provides more flexibility, it may lead to less descriptive product names. Consider if this aligns with your product naming conventions and user expectations.

To ensure consistency, let's check if this change is reflected in other parts of the codebase:

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

65-65: LGTM: Improved code formatting

The reformatting of the hierarchyData variable assignment improves readability without changing functionality.

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

14-33: Previous review comments remain applicable

The issues and suggestions highlighted in the previous reviews for these lines are still valid. Please refer to them to address the outstanding concerns.

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

77-77: ⚠️ Potential issue

Verify potential off-by-one error in toValue calculation.

In the line:

toValue: toValue ? toValue - 1 : null,

Subtracting 1 from toValue may introduce an off-by-one error if the intention is to include the toValue in the range. Please verify whether this subtraction is necessary and aligns with the business logic.

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

6-6: Import getDeliveryConfig added correctly

The import statement for getDeliveryConfig is properly added and aligns with its usage in the code.


78-79: MDMS module and entity names updated appropriately

The MDMS module name is updated to "HCM-PROJECT-TYPES" and the entity name to "projectTypes", which is consistent with the expected data structure.

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

126-126: Verify the structure of cycleData after changes

Since reverseDeliveryRemap now returns the unmodified data, ensure that cycleData (assigned at line 267) has the expected structure for subsequent operations. The code later maps over cycleData to render cycle components, which may rely on a specific data format produced by the original reverseDeliveryRemap function. Verify that this change doesn't introduce runtime errors or affect the rendering of cycles.

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

5-5: Import statement is correct

The getDeliveryConfig module is correctly imported. This will help in fetching the delivery configuration based on the project type.


30-31: Data access path may be incorrect

The MDMS response data is typically nested under the MdmsRes key. Currently, the code accesses data using data?.["HCM-PROJECT-TYPES"]. To ensure accurate data retrieval, consider updating the access path to include MdmsRes.


26-27: Verify the MDMS module and master names

Ensure that the MDMS module name "HCM-PROJECT-TYPES" and the master [ { name: "projectTypes" } ] are correct and exist in the MDMS configuration.

Run the following script to confirm the existence of the module and master:

This script searches the mdms-data directory for MDMS definitions matching the provided module and master names.

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

134-175: Reminder: Remove the commented-out reverseDeliveryRemap function

The reverseDeliveryRemap function from lines 134 to 175 is still commented out and not in use. To maintain code cleanliness and readability, consider removing this block if it's no longer needed.


580-584: Reminder: Remove the commented-out useEffect hook

The useEffect hook from lines 580 to 584 remains commented out and unused. To improve code readability, consider removing it if it's no longer necessary.

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DataUploadSummary.js (2)

41-80: No issues with commenting out loopAndReturn

The function loopAndReturn has been commented out. If this is intentional and temporary, it's acceptable. Ensure that any references to this function are removed or handled appropriately to prevent potential runtime errors.


82-123: No issues with commenting out reverseDeliveryRemap

The function reverseDeliveryRemap has been commented out. If this is intentional and temporary, it's acceptable. Make sure there are no remaining references to this function elsewhere in the codebase that could cause issues.

Comment on lines +2 to +17
const data = await Digit.CustomService.getResponse({
url: `/product/variant/v1/_search`,
params: {
tenantId: tenantId,
limit: 100,
offset: 0
},
body: {
ProductVariant: {
id: [variantId],
},
},
config: {
enabled: variantId ? true : false,
},
});
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

Consider adding pagination support and error handling.

The API call configuration is generally correct, but there are two areas for improvement:

  1. Pagination: The current implementation uses a fixed limit of 100 and an offset of 0. Consider making these configurable to support pagination for larger datasets.

  2. Error Handling: Add a try-catch block to handle potential API errors gracefully.

Here's a suggested refactor addressing these points:

export const useProductVariantSearch = async ({ variantId, tenantId, limit = 100, offset = 0 }) => {
  try {
    const data = await Digit.CustomService.getResponse({
      url: `/product/variant/v1/_search`,
      params: { tenantId, limit, offset },
      body: { ProductVariant: { id: [variantId] } },
      config: { enabled: !!variantId },
    });
    return data?.ProductVariant?.[0]?.sku;
  } catch (error) {
    console.error('Error fetching product variant:', error);
    throw error; // or handle it as per your error handling strategy
  }
};

This refactored version includes error handling and allows for pagination by making limit and offset configurable.

🧰 Tools
🪛 Biome

[error] 15-15: 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)

},
},
config: {
enabled: variantId ? true : false,
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)

Simplify the boolean expression in the enabled config.

The current ternary operator is unnecessary and can be simplified.

Replace the line with:

enabled: !!variantId,

This change uses the double negation operator to ensure a boolean value, which is more concise and achieves the same result.

🧰 Tools
🪛 Biome

[error] 15-15: 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)

enabled: variantId ? true : false,
},
});
return data?.ProductVariant?.[0]?.sku;
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

Consider handling empty API results.

The current return statement uses optional chaining, which is good. However, it doesn't handle the case where the API returns an empty result.

Consider adding a fallback value or throwing an error for empty results:

const sku = data?.ProductVariant?.[0]?.sku;
if (!sku) {
  console.warn('No product variant found');
  return null; // or throw new Error('No product variant found');
}
return sku;

This approach provides more explicit handling of empty results, making it easier for the consumer of this hook to handle different scenarios.

const hierarchyData = Digit.Hooks.campaign.useBoundaryRelationshipSearch({BOUNDARY_HIERARCHY_TYPE,tenantId});
const modulePrefix = "hcm";

const moduleCode = ["hr", "campaignmanager", "workbench", "mdms", "schema", "admin-schemas", `boundary-${BOUNDARY_HIERARCHY_TYPE}`];
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Residual references to "hcm-admin-schemas" detected

The verification script found that "hcm-admin-schemas" is still referenced in the following files:

  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/Module.js
  • health/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/Module.js

These residual references may lead to inconsistencies or break existing functionality. Please update these instances to "admin-schemas" to ensure consistency across the codebase.

🔗 Analysis chain

Verify the impact of removing the "hcm" prefix from "admin-schemas"

The removal of the "hcm" prefix from "admin-schemas" in the moduleCode array might have implications for how the module interacts with admin schemas. Please ensure that this change is consistent with the rest of the codebase and doesn't break any existing functionality.

To verify the impact of this change, you can run the following script:

This script will help identify any remaining references to "hcm-admin-schemas" that might need updating, and confirm that "admin-schemas" is being used correctly throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to "hcm-admin-schemas" in the codebase

# Search for "hcm-admin-schemas" in all JavaScript and TypeScript files
echo "Searching for 'hcm-admin-schemas' references:"
rg --type js --type ts "hcm-admin-schemas"

# Search for "admin-schemas" to ensure it's being used correctly
echo "\nSearching for 'admin-schemas' usage:"
rg --type js --type ts "admin-schemas"

Length of output: 1337

}

return {
key: index + 1 + subIndex,
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

⚠️ Potential issue

Ensure uniqueness of keys in attributeConfig.

The key for each attribute is calculated as:

key: index + 1 + subIndex,

There is a possibility of duplicate keys if index and subIndex combinations result in the same value. To prevent potential rendering issues or incorrect data reference, consider modifying the key generation logic to ensure uniqueness across all attributes.

return reversedData;
// return reversedData;

return data;
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)

Assess the necessity of reverseDeliveryRemap function

At line 126, the reverseDeliveryRemap function simply returns data without any transformation. Consider whether this function is still necessary. If it doesn't perform any operations, you might remove the function and use the data directly where it's called to simplify the code.

Comment on lines 176 to 222

// function restructureData(data) {
// return data.map(cycle => ({
// mandatoryWaitSinceLastCycleInDays: null,
// id: parseInt(cycle.cycleIndex),
// deliveries: cycle.deliveries.map(delivery => ({
// id: parseInt(delivery.deliveryIndex),
// mandatoryWaitSinceLastDeliveryInDays: null,
// doseCriteria: delivery.deliveryRules.map(rule => ({
// condition: parseCondition(rule.attributes),
// ProductVariants: rule.products.map(product => ({
// productVariantId: product.value,
// name: product.name
// }))
// }))
// }))
// }));
// }

// function parseCondition(attributes) {
// const conditions = attributes.map(attr => {
// const attributeCode = attr.attribute.code;
// const operator = attr.operator.code;
// if (operator === "IN_BETWEEN") {
// const fromValue = attr.fromValue;
// const toValue = attr.toValue;
// return `${fromValue} <= ${attributeCode} < ${toValue}`;
// }

// const value = attr.value;
// return `${attributeCode}${convertOperator(operator)}${value}`;
// });

// // Join conditions into a single string
// return conditions.join(' and ');
// }

// function convertOperator(operatorCode) {
// const operators = {
// "LESS_THAN_EQUAL_TO": "<=",
// "GREATER_THAN_EQUAL_TO": ">=",
// "LESS_THAN": "<",
// "GREATER_THAN": ">",
// "EQUAL_TO": "=",
// };
// return operators[operatorCode] || "=";
// }
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)

Consider removing the commented-out restructureData and related functions

The functions restructureData, parseCondition, and convertOperator from lines 177 to 222 are commented out and not being used. Removing unused code can improve maintainability and reduce potential confusion.

Comment on lines +433 to +434
// deliveryRule: reverseDeliveryRemap(delivery),
deliveryRule: delivery
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

Ensure deliveryRule has the correct data format

By replacing deliveryRule: reverseDeliveryRemap(delivery) with deliveryRule: delivery, ensure that the delivery object conforms to the expected structure required downstream. The reverseDeliveryRemap function might have performed necessary transformations.

Comment on lines +500 to +573
// function restructureData(data) {
// const dateData = totalFormData?.HCM_CAMPAIGN_CYCLE_CONFIGURE?.cycleConfigure?.cycleData;
// const restructuredData = [];

// data.forEach((cycle) => {
// cycle.deliveries.forEach((delivery, index) => {
// delivery.deliveryRules.forEach((rule) => {
// const restructuredRule = {
// startDate: Digit.Utils.pt.convertDateToEpoch(dateData?.find((i) => i.key == cycle.cycleIndex)?.fromDate, "daystart"), // Hardcoded for now
// endDate: Digit.Utils.pt.convertDateToEpoch(dateData?.find((i) => i?.key == cycle?.cycleIndex)?.toDate), // Hardcoded for now
// cycleNumber: parseInt(cycle.cycleIndex),
// deliveryNumber: parseInt(delivery.deliveryIndex),
// deliveryType: rule?.deliveryType,
// deliveryRuleNumber: parseInt(rule.ruleKey), // New key added
// products: [],
// conditions: [],
// };

// rule.attributes.forEach((attribute) => {
// if (attribute?.operator?.code === "IN_BETWEEN") {
// restructuredRule.conditions.push({
// attribute: attribute?.attribute?.code
// ? attribute?.attribute?.code
// : typeof attribute?.attribute === "string"
// ? attribute?.attribute
// : null,
// operator: "LESS_THAN_EQUAL_TO",
// value: attribute.fromValue ? Number(attribute.fromValue) : null,
// });

// restructuredRule.conditions.push({
// attribute: attribute?.attribute?.code
// ? attribute?.attribute?.code
// : typeof attribute?.attribute === "string"
// ? attribute?.attribute
// : null,
// operator: "GREATER_THAN_EQUAL_TO",
// value: attribute.toValue ? Number(attribute.toValue) : null,
// });
// } else {
// restructuredRule.conditions.push({
// attribute: attribute?.attribute?.code
// ? attribute?.attribute?.code
// : typeof attribute?.attribute === "string"
// ? attribute?.attribute
// : null,
// operator: attribute.operator ? attribute.operator.code : null,
// value:
// attribute?.attribute?.code === "Gender" && attribute?.value?.length > 0
// ? attribute?.value
// : attribute?.attribute?.code === "TYPE_OF_STRUCTURE"
// ? attribute?.value
// : attribute?.value
// ? Number(attribute?.value)
// : null,
// });
// }
// });

// rule.products.forEach((prod) => {
// restructuredRule.products.push({
// value: prod?.value,
// name: prod?.name,
// count: prod?.count,
// });
// });

// restructuredData.push(restructuredRule);
// });
// });
// });

return restructuredData;
}
// return restructuredData;
// }
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)

Consider removing the redundant commented-out restructureData function

The restructureData function from lines 500 to 573 is a duplicate of the earlier commented-out function. If it's no longer needed, removing this redundant code can enhance code clarity.

Comment on lines +614 to +616
// const temp = restructureData(totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule);
// payloadData.deliveryRules = temp;
payloadData.deliveryRules = totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule;
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

Verify that payloadData.deliveryRules is correctly formatted

In lines 614-616, 686-688, 751-753, and 815-817, the restructureData function is commented out, and payloadData.deliveryRules is directly assigned from totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule. Please ensure that this data matches the format expected by the backend API. Previously, restructureData may have been essential for proper data transformation.

Also applies to: 686-688, 751-753, 815-817

@jagankumar-egov jagankumar-egov merged commit 8f4afb7 into console Oct 8, 2024
2 checks passed
@jagankumar-egov jagankumar-egov deleted the HCMPRE-701 branch October 8, 2024 08:29
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: 9

🧹 Outside diff range comments (16)
health/micro-ui/web/micro-ui-internals/example/public/index.html (1)

Line range hint 1-41: Consider cleaning up and documenting stylesheet usage.

The file contains several commented-out stylesheet links and scripts, as well as multiple versions of stylesheets. This could lead to confusion and maintenance issues in the future.

Suggestions:

  1. Remove any unnecessary commented-out code.
  2. Document the purpose of each stylesheet, especially those with specific versions (e.g., 1.0.75-campaign, 1.0.50-microplan).
  3. Consider using environment variables or a configuration file to manage different stylesheet versions for various environments, if applicable.
  4. Ensure that all necessary stylesheets are properly loaded and that there are no conflicts between different versions.
#!/bin/bash
# Description: Check for usage of different stylesheet versions across the project

echo "Checking for usage of different digit-ui-css versions:"
rg --type html "digit-ui-css@[0-9.a-z-]+" | sort | uniq -c

echo "Checking for usage of different digit-ui-components-css versions:"
rg --type html "digit-ui-components-css@[0-9.a-z-]+" | sort | uniq -c
health/micro-ui/web/public/index.html (1)

Line range hint 23-23: Consider reviewing the commented out script tag.

There's a commented out script tag for globalConfigs.js:

<!-- <script src="https://s3.ap-south-1.amazonaws.com/egov-dev-assets/globalConfigs.js"></script> -->

If this script is no longer needed, consider removing the commented line to keep the code clean. If it's still required but commented out for a specific reason, it might be helpful to add a comment explaining why it's currently disabled.

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

Line range hint 1-280: Consider adding error boundaries and improving error handling

The component handles errors in various places, but it might benefit from a more structured approach to error handling. Consider implementing React Error Boundaries to catch and handle errors more gracefully. Also, review the error handling in the API calls and state updates to ensure all potential error scenarios are covered.

Here's an example of how you could implement an Error Boundary:

import React from 'react';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can log the error here
    console.error('Error caught by boundary:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

// Usage
<ErrorBoundary>
  <DataUploadSummary />
</ErrorBoundary>

Consider wrapping the main component or its subcomponents with this ErrorBoundary to catch and handle unexpected errors.

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

Line range hint 111-116: Add missing dependency array to useEffect to prevent unintended behavior

The useEffect on lines 111-116 lacks a dependency array, causing it to execute after every render. This may lead to performance issues or unintended side effects, such as infinite loops. To ensure the effect runs only when intended, you should add an appropriate dependency array.

Consider revising the effect:

  • If the intention is to run this effect only once on component mount, add an empty dependency array:

     useEffect(() => {
         if (executionCount < 5) {
           onSelect("cycleConfigure", state);
           setExecutionCount((prevCount) => prevCount + 1);
         }
    - }, );
    + }, []);
  • If the effect should run when specific variables change, include those variables in the dependency array, ensuring that it doesn't create an unintended loop:

     useEffect(() => {
         if (executionCount < 5) {
           onSelect("cycleConfigure", state);
           setExecutionCount((prevCount) => prevCount + 1);
         }
    - }, );
    + }, [executionCount, state]);

Please verify the desired behavior and adjust the dependencies accordingly to prevent potential issues.

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DeliveryDetailsSummary.js (2)

Line range hint 142-142: Improve error handling in fetchcd function

In the catch block of the fetchcd function, the error is logged using console.log, but the function does not return any value or handle the error appropriately. This could lead to undefined being returned, which may cause issues in the code that relies on this function.

Consider modifying the function to handle errors properly by returning a default value or rethrowing the error. Here's how you can adjust the code:

  } catch (e) {
    console.log("error", e);
+   return null; // Return a default value or handle the error as needed
  }

Ensure that any code using fetchcd accounts for the possibility of a null return value.


Line range hint 271-279: Refactor unused asynchronous function and variable

Within the select function of the data fetching hook, the asynchronous function ss is declared and immediately invoked, but the returned value is not utilized. Additionally, the variable processid is assigned a value inside ss but is not used elsewhere. This may lead to unnecessary complexity and potential confusion.

Consider removing the unused function and variable to simplify the code. If fetching resource details is required for future implementation, ensure that the data is used appropriately.

Apply this diff to remove the unused code:

      let processid;
      setprojectId(data?.[0]?.projectId);
      setCards(data?.cards);

-     const ss = async () => {
-       let temp = await fetchResourceFile(tenantId, resourceIdArr);
-       processid = temp;
-       return;
-     };
-     ss();
+     // If resource details are needed, fetch and use them here
+     // const resourceDetails = await fetchResourceFile(tenantId, resourceIdArr);
+     // Use resourceDetails as needed

If you need to perform asynchronous operations inside select, ensure that they are properly handled, considering that select cannot be an async function. Alternatively, move the asynchronous logic to a useEffect hook within the component.

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/TimelineComponent.js (9)

Line range hint 138-149: Prevent potential TypeError with resourceId.length check

In the condition resourceId.length === 0, if resourceId is undefined or null, it will cause a TypeError. Consider adding a null check or using optional chaining to prevent this error.

Apply this diff to safeguard against potential errors:

- if (
-   resourceId.length === 0 &&
+ if (
+   (!resourceId || resourceId.length === 0) &&
    lastCompletedProcess?.type === "campaign-creation" &&
    lastCompletedProcess?.status === "completed" &&
    !dataFetched
  ) {
    // ...
  }

Line range hint 45-45: Consider using useLocation hook for consistent location access

The location object may not be available globally in all environments, especially in server-side rendering or strict mode. For better compatibility and to follow React best practices, consider using the useLocation hook from react-router-dom.

Here's how you can modify the code:

+ import { useLocation } from 'react-router-dom';

  // ...

+ const location = useLocation();
  const searchParams = new URLSearchParams(location.search);

Line range hint 69-74: Remove commented-out code to clean up the codebase

There's a block of commented-out code that seems to be obsolete. Removing unused code can improve readability and maintainability.

[code_smell]

Apply this diff to remove the unnecessary code:

- // useEffect(() => {
- //   if (newResourceId?.length > 0) {
- //     fetchUser();
- //   }
- // }, [newResourceId && lastCompletedProcess]);

Line range hint 237-259: Avoid using Immediately Invoked Function Expressions (IIFEs) inside JSX

Using IIFEs within JSX can make the code harder to read and maintain. It can also lead to unintended side effects. Consider extracting the logic into a separate function or component.

Refactor the code as follows:

  1. Extract the rendering logic into a separate function:
const renderTimelines = () => {
  const processesToRender = [];
  let foundFirstFailed = false;
  let allCompleted = true;

  // ...existing logic...

  return (
    <TimelineMolecule
      hideFutureLabel={true}
      hidePastLabel={!allCompleted}
      {...(!allCompleted && { initialVisibleCount: processesToRender.length })}
      {...(allCompleted && { initialVisibleCount: 1 })}
    >
      {processesToRender.reverse()}
    </TimelineMolecule>
  );
};
  1. Replace the IIFE in the JSX with the function call:
- {progessTrack ? (
-   (() => {
-     // rendering logic...
-   })()
- ) : (
-   <p></p>
- )}
+ {progessTrack ? renderTimelines() : <p></p>}

Line range hint 57-68: Handle errors in the fetchUser function

The fetchUser function does not currently handle errors. If the API call fails, the application may experience unhandled promise rejections. Consider adding a try-catch block to handle potential errors gracefully.

Apply this diff to add error handling:

const fetchUser = async () => {
+ try {
    const responseTemp = await Digit.CustomService.getResponse({
      url: `/project-factory/v1/data/_search`,
      body: {
        SearchCriteria: {
          tenantId: tenantId,
          id: newResourceId,
        },
      },
    });

    const response = responseTemp?.ResourceDetails?.map((i) => i?.processedFilestoreId);

    if (response?.[0]) {
      setUserCredential({ fileStoreId: response?.[0], customName: "userCredential" });
    }
+ } catch (error) {
+   console.error("Error fetching user credentials:", error);
+ }
};

Line range hint 200-204: Ensure proper dependency array in useEffect hook

The useEffect hook depends on lastCompletedProcess, but it may not update correctly if failedProcess changes. Consider adding failedProcess to the dependency array to ensure the interval is cleared or reset appropriately.

Apply this diff to update the dependency array:

useEffect(() => {
  let intervalId;

  if (failedProcess?.status !== "failed" && lastCompletedProcess?.type !== "campaign-creation") {
    intervalId = setInterval(() => {
      refetch();
    }, baseTimeOut?.["HCM-ADMIN-CONSOLE"]?.baseTimeOut?.[0]?.timelineRefetch);
  }

  return () => {
    if (intervalId) {
      clearInterval(intervalId);
    }
  };
- }, [lastCompletedProcess]);
+ }, [lastCompletedProcess, failedProcess]);

Line range hint 33-35: Improve date formatting with locale support

The epochToDateTime function manually formats date and time components. Consider using toLocaleString for better locale support and cleaner code.

Apply this diff to simplify the function:

- // Existing code formatting date and time manually
+ const epochToDateTime = (epoch) => {
+   const date = new Date(epoch);
+   return date.toLocaleString();
+ };

This approach automatically formats the date and time according to the user's locale settings.


Line range hint 235-236: Provide a loading indicator while data is being fetched

Currently, if progessTrack is null or undefined, the component renders an empty <p></p> element. For better user experience, consider displaying a loading indicator.

Apply this diff to add a loading state:

- ) : (
-   <p></p> // You can replace this with a loading spinner or any other indicator
- )}
+ ) : (
+   <div className="loading-indicator">{t("COMMON_LOADING")}</div> // Display a loading message or spinner
+ )}

Ensure that you have appropriate styling for the loading indicator.


Line range hint 229-232: Avoid unnecessary comments and commented-out code

There are several blocks of commented-out code and unnecessary comments that can be removed to improve code clarity.

[code_smell]

Apply this diff to clean up the code:

- // useEffect(()=>{
- //   const lastCompletedProcess = ...
- // }, [progessTrack])

Remove any other commented-out code that is no longer needed.

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

Line range hint 10-13: Possible inversion of fromValue and toValue in loopAndReturn function

In the loopAndReturn function, the assignment of fromValue and toValue might be inverted. Typically, fromValue should be the smaller value, and toValue should be the larger value. Currently, fromValue is assigned using Math.max(...), and toValue is assigned using Math.min(...), which may result in fromValue being greater than toValue. This could lead to incorrect range representations in conditions.

Consider swapping the assignments to ensure the correct range:

-        toValue: existingItem.value && item.value ? Math.min(existingItem.value, item.value) : null,
-        fromValue: existingItem.value && item.value ? Math.max(existingItem.value, item.value) : null,
+        fromValue: existingItem.value && item.value ? Math.min(existingItem.value, item.value) : null,
+        toValue: existingItem.value && item.value ? Math.max(existingItem.value, item.value) : null,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between b238070 and 170a984.

📒 Files selected for processing (15)
  • health/micro-ui/web/micro-ui-internals/example/public/index.html (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignSummary.js (0 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DataUploadSummary.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DeliveryDetailsSummary.js (4 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DetailsTable.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/TimelineComponent.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js (0 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useProductVariantSearch.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/AddProduct.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (8 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/index.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (1 hunks)
  • health/micro-ui/web/public/index.html (1 hunks)
💤 Files with no reviewable changes (2)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignSummary.js
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js
🧰 Additional context used
📓 Path-based instructions (11)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.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/index.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

🪛 Biome
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DeliveryDetailsSummary.js

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

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

(lint/correctness/noUnsafeOptionalChaining)


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

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

(lint/correctness/noUnsafeOptionalChaining)

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useProductVariantSearch.js

[error] 15-15: 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)

🔇 Additional comments (25)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useProductVariantSearch.js (1)

1-3: Function signature and API call setup look good.

The async function signature and the use of Digit.CustomService.getResponse for the API call are well-implemented. The destructuring of parameters in the function signature provides clear expectations for the hook's usage.

health/micro-ui/web/micro-ui-internals/example/public/index.html (2)

20-20: Confirm the update of digit-ui-components-css version.

The digit-ui-components-css package has been updated from version 0.0.2-beta.34 to 0.0.2-beta.36.

Please ensure:

  1. This update was intentional.
  2. The application has been tested with this new version to confirm compatibility.
  3. Any changes or improvements in this version have been noted and communicated to the team if necessary.
#!/bin/bash
# Description: Check for any other occurrences of the old version and verify if all have been updated.

# Test: Search for any remaining occurrences of the old version
echo "Checking for any remaining occurrences of version 0.0.2-beta.34:"
rg --type html "0\.0\.2-beta\.34"

# Test: Verify if the new version is consistently used across the project
echo "Verifying consistent usage of version 0.0.2-beta.36:"
rg --type html "0\.0\.2-beta\.36"

17-17: Verify the compatibility of the updated digit-ui-css version.

The digit-ui-css package has been updated from version 1.8.2-beta.11 to 1.8.2-beta.34. This is a significant version jump that might introduce breaking changes or new features.

Please confirm:

  1. Was this update intentional?
  2. Have you tested the application with this new version to ensure compatibility?
  3. Are there any new features or breaking changes in this version that the team should be aware of?
✅ Verification successful

digit-ui-css version update is verified successfully.

  • No remaining occurrences of version 1.8.2-beta.11 found.
  • Version 1.8.2-beta.34 is consistently used across all relevant files.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any other occurrences of the old version and verify if all have been updated.

# Test: Search for any remaining occurrences of the old version
echo "Checking for any remaining occurrences of version 1.8.2-beta.11:"
rg --type html "1\.8\.2-beta\.11"

# Test: Verify if the new version is consistently used across the project
echo "Verifying consistent usage of version 1.8.2-beta.34:"
rg --type html "1\.8\.2-beta\.34"

Length of output: 668


Script:

#!/bin/bash
# Description: Check for any remaining occurrences of the old version and verify if all have been updated.

# Test: Search for any remaining occurrences of the old version
echo "Checking for any remaining occurrences of version 1.8.2-beta.11:"
rg --type html "1\.8\.2-beta\.11"

# Test: Verify if the new version is consistently used across the project
echo "Verifying consistent usage of version 1.8.2-beta.34:"
rg --type html "1\.8\.2-beta\.34"

Length of output: 646

health/micro-ui/web/public/index.html (1)

11-12: CSS library versions have been updated.

The versions of two CSS libraries have been updated:

  1. @egovernments/digit-ui-css: 1.8.2-beta.11 → 1.8.2-beta.34
  2. @egovernments/digit-ui-components-css: 0.0.2-beta.34 → 0.0.2-beta.36

These updates may introduce new styles or fix existing styling issues. Please ensure that:

  1. The application's UI remains consistent with these new versions.
  2. Any custom styles that may have been overriding the previous versions are still effective.
  3. The changes in these libraries are compatible with the current application version.

To verify the impact of these changes, you can run the following script:

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

Line range hint 51-55: Approved: Minor adjustment to variant length validation.

The change to allow product variants with exactly two characters is a reasonable adjustment. It provides slightly more flexibility without significantly impacting data quality or meaningfulness of variant names.


Line range hint 41-45: Consider the implications of allowing single-character product names.

The validation for product names has been relaxed to allow names with a single character. While this provides more flexibility, it might lead to less meaningful or distinguishable product names. Consider if this aligns with your product naming conventions and user experience goals.

To ensure this change doesn't conflict with any existing naming conventions or cause issues in other parts of the system, you may want to run the following check:

✅ Verification successful

Validation for product name lengths is consistent across the codebase.

The relaxation to allow product names with a single character in AddProduct.js aligns with existing validations in UserProfile.js, ensuring consistency in name length requirements throughout the application.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any existing product name validations or usages
rg --type js 'product.*name.*length' -g '!*test*'

Length of output: 51


Script:

#!/bin/bash
# Search for any existing name length validations across the codebase
rg --type js 'name\s*\.\s*length\s*(?:>=|<=|>|<|==|!=)\s*\d+' -g '!*test*'

Length of output: 276

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

67-67: Verify the impact of removing the "hcm" prefix from "admin-schemas"

The removal of the "hcm" prefix from "admin-schemas" in the moduleCode array might have implications for how the module interacts with admin schemas. Please ensure that this change is consistent with the rest of the codebase and doesn't break any existing functionality.

To verify the impact of this change, you can run the following script:

This script will help identify any remaining references to "hcm-admin-schemas" that might need updating, and confirm that "admin-schemas" is being used correctly throughout the codebase.

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

41-80: Consider removing the commented-out function loopAndReturn

The loopAndReturn function has been entirely commented out. If this function is no longer needed, it's best to remove it completely rather than leaving it as commented code. This will improve code readability and maintainability.


82-123: Consider removing the commented-out function reverseDeliveryRemap

The reverseDeliveryRemap function has been entirely commented out. If this function is no longer needed, it's best to remove it completely rather than leaving it as commented code. This will improve code readability and maintainability.


Line range hint 191-268: Review the updated structure of the cards in the component

The structure of the cards rendered in the component has been significantly changed. Please ensure that this new structure aligns with the intended design and functionality of the DataUploadSummary component. Verify that all necessary information is still being displayed and that the edit functionality for each section is working as expected.

#!/bin/bash
# Description: Check for any potential issues with the new card structure

# Test: Search for references to the card names and their associated components
# Expect: Consistent usage of card names and components

rg '\b(target|facility|user)\b.*\bname:' health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DataUploadSummary.js

# Test: Check for the CampaignDocumentsPreview component usage
# Expect: Consistent usage across all cards

rg '\bCampaignDocumentsPreview\b' health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DataUploadSummary.js

Line range hint 270-278: Verify the removal of user credential download functionality

The user credential download button and its associated functionality have been commented out. Please confirm if this removal is intentional. If it's no longer needed, consider removing the commented code entirely. If it's temporary, add a TODO comment explaining why it's commented out and when it should be re-enabled.

✅ Verification successful

User Credential Download Functionality Removal Verified

The search for userCredential and downloadUserCred yielded no results outside of commented code. Therefore, the removal of the user credential download functionality is intentional and complete.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to userCredential or downloadUserCred

# Test: Search for userCredential or downloadUserCred in the file
# Expect: No matches found outside of commented code

rg '\buserCredential\b|\bdownloadUserCred\b' health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DataUploadSummary.js

Length of output: 473

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DetailsTable.js (2)

27-31: Ensure consistent optional chaining for 'attribute' properties

To prevent potential runtime errors when i.attribute or i.attribute.code is undefined, ensure that optional chaining is consistently applied.


18-18: Correct the order of 'fromValue' and 'toValue' in the range display

The value assignment in the IN_BETWEEN condition displays toValue before fromValue. Typically, a range is displayed as "fromValue to toValue".

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

80-89: Avoid using React Hooks outside of functional components or other Hooks.

The useProductVariantSearch is a React Hook, and according to React's Rules of Hooks, Hooks can only be called inside React functional components or other custom Hooks. Currently, it's being called inside a regular function generateMRDNConfig, which is neither a React component nor a Hook. This can lead to runtime errors and unpredictable behavior.


80-89: Handle asynchronous operations correctly when using map.

In generateMRDNConfig, the map function is used with an async callback on criteria.ProductVariants. This results in productConfig being an array of unresolved Promises rather than the desired product configuration objects.


178-180: Ensure the asynchronous deliveryConfig is properly awaited in convertToConfig.

Since deliveryConfig may return a Promise due to asynchronous operations, the convertToConfig function should handle this accordingly. Without proper handling, the returned configuration might be incomplete or incorrect.


42-43: Handle unknown operators explicitly in parseCondition.

In the default case of your switch statement, operatorValue is set to "UNKNOWN" without any error handling. This could lead to silent failures or unexpected behavior downstream.


136-136: Ensure uniqueness of keys in attributeConfig.

The key for each attribute is calculated as:

key: index + 1 + subIndex,

There's a possibility of duplicate keys if index and subIndex combinations result in the same value. Duplicate keys can cause rendering issues or incorrect data references. Consider enhancing the key generation logic to ensure uniqueness across all attributes.


115-115: Consistent retrieval of product names across configurations.

In generateBednetConfig, product names are obtained directly from variant.name:

name: variant.name,

Whereas in generateMRDNConfig, product names are fetched asynchronously using useProductVariantSearch. This inconsistency might lead to discrepancies in product naming or data retrieval methods. Consider standardizing the method of obtaining product names to maintain consistency across your configurations.

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

6-6: Import statement is correct

The import of getDeliveryConfig is correctly added and used appropriately in the code.

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/TimelineComponent.js (2)

84-84: ⚠️ Potential issue

Typo in variable name progessTrack

The variable progessTrack appears to be misspelled. It should likely be progressTrack for better readability and to prevent confusion.

Apply this diff to correct the typo:

- const { data: progessTrack , refetch } = Digit.Hooks.useCustomAPIHook(reqCriteria);
+ const { data: progressTrack , refetch } = Digit.Hooks.useCustomAPIHook(reqCriteria);

Remember to update all occurrences of progessTrack to progressTrack throughout the code.

Likely invalid or redundant comment.


Line range hint 150-163: Ensure searchAPIData handles campaign ID correctly

In the searchAPIData function, the CampaignDetails object in the request body includes ids: [campaignId]. Verify that campaignId is always an array or adjust the code accordingly.

Run the following script to check the type of campaignId throughout the codebase:

Ensure that campaignId is correctly used as an array when necessary.

✅ Verification successful

Verification Successful: campaignId is consistently used as a string and appropriately handled as an array where necessary.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify if `campaignId` is used consistently as an array or a string.

# Search for declarations and usages of `campaignId`
rg --type js --type jsx 'campaignId' -A 5 -B 5

Length of output: 74


Script:

#!/bin/bash
# Description: Verify if `campaignId` is used consistently as an array or a string.

# Search for declarations and usages of `campaignId` in .js and .jsx files
rg --type js --type javascript --type ts --type tsx 'campaignId' -A 5 -B 5

Length of output: 109


Script:

#!/bin/bash
# Description: Verify if `campaignId` is used consistently as an array or a string.

# Search for declarations and usages of `campaignId` in .js, .jsx, .ts, and .tsx files
rg 'campaignId' -g '*.js' -g '*.jsx' -g '*.ts' -g '*.tsx' -A 5 -B 5

Length of output: 86173

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

5-5: Import statement correctly added

The getDeliveryConfig module is properly imported from "../../../utils/getDeliveryConfig".


26-27: Verify the MDMS module and master names

The useCustomMDMS hook is now fetching data from the module "HCM-PROJECT-TYPES" and the master "projectTypes". Please ensure that these names are accurate and correspond to the correct MDMS configurations.


30-31: Previous review comment is still applicable

The concern regarding the data access path in getDeliveryConfig remains unresolved. The data is still accessed as data?.["HCM-PROJECT-TYPES"], but it should be accessed via data?.MdmsRes?.["HCM-PROJECT-TYPES"] to correctly retrieve the MDMS response.

Comment on lines +4 to +13
params: {
tenantId: tenantId,
limit: 100,
offset: 0
},
body: {
ProductVariant: {
id: [variantId],
},
},
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

Consider enhancing API call parameters for better flexibility.

The API call parameters and body are structured well, but there are opportunities for improvement:

  1. Pagination: The current implementation uses fixed limit and offset values. Consider making these configurable to support flexible pagination for larger datasets.

  2. Request Body: While the current structure is correct, evaluate if additional fields in the ProductVariant object might be beneficial for more specific searches.

Here's a suggested refactor to address these points:

export const useProductVariantSearch = async ({ variantId, tenantId, limit = 100, offset = 0, additionalFields = {} }) => {
  const data = await Digit.CustomService.getResponse({
    url: `/product/variant/v1/_search`,
    params: {
      tenantId,
      limit,
      offset
    },
    body: {
      ProductVariant: {
        id: [variantId],
        ...additionalFields
      },
    },
    // ... rest of the configuration
  });
  // ... rest of the function
};

This refactor allows for customizable pagination and the inclusion of additional search criteria if needed.

Comment on lines +14 to +17
config: {
enabled: variantId ? true : false,
},
});
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)

Simplify the enabled configuration.

The current implementation of the enabled property uses an unnecessary ternary operator. This can be simplified for better readability and to address the static analysis hint.

Replace the line:

enabled: variantId ? true : false,

with:

enabled: !!variantId,

This change uses the double negation operator to ensure a boolean value, which is more concise and achieves the same result.

🧰 Tools
🪛 Biome

[error] 15-15: 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 +18 to +19
return data?.ProductVariant?.[0]?.sku;
};
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

Enhance error handling and empty result management.

While the use of optional chaining in the return statement is good, the function could benefit from more robust error handling and empty result management.

Consider implementing the following improvements:

  1. Add a try-catch block to handle potential API errors.
  2. Implement a check for empty results.

Here's a suggested refactor:

export const useProductVariantSearch = async ({ variantId, tenantId }) => {
  try {
    const data = await Digit.CustomService.getResponse({
      // ... existing configuration
    });
    
    const sku = data?.ProductVariant?.[0]?.sku;
    if (!sku) {
      console.warn('No product variant found');
      return null;
    }
    return sku;
  } catch (error) {
    console.error('Error fetching product variant:', error);
    throw error; // or handle it as per your error handling strategy
  }
};

This approach provides more explicit handling of errors and empty results, making it easier for consumers of this hook to handle different scenarios.

Comment on lines +1 to +19
export const useProductVariantSearch = async ({ variantId, tenantId }) => {
const data = await Digit.CustomService.getResponse({
url: `/product/variant/v1/_search`,
params: {
tenantId: tenantId,
limit: 100,
offset: 0
},
body: {
ProductVariant: {
id: [variantId],
},
},
config: {
enabled: variantId ? true : false,
},
});
return data?.ProductVariant?.[0]?.sku;
};
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)

Overall, the hook implementation is solid but has room for improvement.

The useProductVariantSearch hook provides a good foundation for fetching product variant data. To enhance its functionality and robustness, consider implementing the suggested improvements:

  1. Add support for flexible pagination.
  2. Allow for additional search criteria in the request body.
  3. Simplify the enabled configuration.
  4. Implement error handling and empty result management.

These changes will make the hook more versatile and easier to use in various scenarios.

If you'd like assistance in implementing any of these suggestions or have any questions about the proposed changes, please let me know. I'd be happy to provide more detailed guidance or code examples.

🧰 Tools
🪛 Biome

[error] 15-15: 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 +87 to +96
const usedCombinations = new Set();
const variantPayload = resData.map((i) => {
const target = formData?.["addProduct"]?.find((f) => f.name === i.name);
const target = formData?.["addProduct"]?.find((f) => {
const combination = `${f.name}-${f.variant}`;
if (f.name === i.name && !usedCombinations.has(combination)) {
usedCombinations.add(combination);
return true;
}
return false;
});
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)

Approved: Efficient handling of unique product-variant combinations.

The introduction of usedCombinations Set and the modified logic for finding target products effectively prevents duplicate processing of product-variant combinations. This is a good improvement for data integrity.

As suggested in a previous review, consider extracting the combination check into a separate function for improved readability:

const usedCombinations = new Set();
const isUniqueCombination = (name, variant) => {
  const combination = `${name}-${variant}`;
  if (!usedCombinations.has(combination)) {
    usedCombinations.add(combination);
    return true;
  }
  return false;
};

const variantPayload = resData.map((i) => {
  const target = formData?.["addProduct"]?.find((f) => 
    f.name === i.name && isUniqueCombination(f.name, f.variant)
  );
  // ... rest of the code
});

This refactoring would improve code readability and maintainability.

@@ -61,15 +61,18 @@ const CampaignModule = ({ stateCode, userType, tenants }) => {
},
});

const hierarchyData = Digit.Hooks.campaign.useBoundaryRelationshipSearch({ BOUNDARY_HIERARCHY_TYPE, tenantId });
const hierarchyData = Digit.Hooks.campaign.useBoundaryRelationshipSearch({BOUNDARY_HIERARCHY_TYPE,tenantId});
const modulePrefix = "hcm";
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)

Add documentation for the modulePrefix variable

While the introduction of modulePrefix resolves the previous issue with commented-out code, it would be beneficial to add a brief comment explaining its purpose and significance. This will improve code readability and maintainability.

Example:

// The "hcm" prefix is used to identify and scope store data specific to the Health Campaign Manager module
const modulePrefix = "hcm";

const { path, url } = useRouteMatch();
const language = Digit.StoreData.getCurrentLanguage();
const { isLoading, data: store } = Digit.Services.useStore({
stateCode,
moduleCode,
language,
modulePrefix,
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)

Update useStore hook documentation if necessary

The addition of modulePrefix to the useStore hook call is consistent with the earlier introduction of the modulePrefix variable. This change appears to be correct and aligns with the module's updated structure.

Consider updating the documentation of the useStore hook (if it exists) to reflect this new parameter and its purpose in scoping or identifying store data.

Comment on lines 13 to 35
const data = React.useMemo(() => {
const temp = rowsData.map((i) => ({
const temp = rowsData.map((i) => {
if (i?.operator?.code === "IN_BETWEEN") {
return {
...i,
value: `${i?.toValue ? i?.toValue : "N/A"} to ${i?.fromValue ? i?.fromValue : "N/A"}`,
operator: t(i?.operator?.code) || t(i?.operator),
attribute: i?.attribute?.code || i?.attribute ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.code?.toUpperCase()}`) : "",
};
}
else{
return{
...i,
operator: t(i?.operator),
attribute: i?.attribute ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.toUpperCase()}`) : "",
}));
operator: t(i?.operator?.code) || t(i?.operator),
attribute: i?.attribute?.code
? t(`CAMPAIGN_ATTRIBUTE_${i.attribute.code.toUpperCase()}`)
: i?.attribute
? t(`CAMPAIGN_ATTRIBUTE_${i.attribute}`)
: "",
}
}});
return temp;
}, [rowsData]);
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

Include 't' in the dependency array of the 'data' useMemo

The translation function t is used within the data computation but is not included in the dependency array of the useMemo hook. This could lead to stale translations if the language changes, as data would not recompute.

Apply this diff to add t to the dependency array:

   }, [rowsData]);
+  }, [rowsData, t]);
📝 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 data = React.useMemo(() => {
const temp = rowsData.map((i) => ({
const temp = rowsData.map((i) => {
if (i?.operator?.code === "IN_BETWEEN") {
return {
...i,
value: `${i?.toValue ? i?.toValue : "N/A"} to ${i?.fromValue ? i?.fromValue : "N/A"}`,
operator: t(i?.operator?.code) || t(i?.operator),
attribute: i?.attribute?.code || i?.attribute ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.code?.toUpperCase()}`) : "",
};
}
else{
return{
...i,
operator: t(i?.operator),
attribute: i?.attribute ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.toUpperCase()}`) : "",
}));
operator: t(i?.operator?.code) || t(i?.operator),
attribute: i?.attribute?.code
? t(`CAMPAIGN_ATTRIBUTE_${i.attribute.code.toUpperCase()}`)
: i?.attribute
? t(`CAMPAIGN_ATTRIBUTE_${i.attribute}`)
: "",
}
}});
return temp;
}, [rowsData]);
const data = React.useMemo(() => {
const temp = rowsData.map((i) => {
if (i?.operator?.code === "IN_BETWEEN") {
return {
...i,
value: `${i?.toValue ? i?.toValue : "N/A"} to ${i?.fromValue ? i?.fromValue : "N/A"}`,
operator: t(i?.operator?.code) || t(i?.operator),
attribute: i?.attribute?.code || i?.attribute ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.code?.toUpperCase()}`) : "",
};
}
else{
return{
...i,
operator: t(i?.operator?.code) || t(i?.operator),
attribute: i?.attribute?.code
? t(`CAMPAIGN_ATTRIBUTE_${i.attribute.code.toUpperCase()}`)
: i?.attribute
? t(`CAMPAIGN_ATTRIBUTE_${i.attribute}`)
: "",
}
}});
return temp;
}, [rowsData, t]);

Comment on lines +25 to +43
switch (operator) {
case "<=":
operatorValue = "LESS_THAN_EQUAL_TO";
break;
case ">=":
operatorValue = "GREATER_THAN_EQUAL_TO";
break;
case "<":
operatorValue = "LESS_THAN";
break;
case ">":
operatorValue = "GREATER_THAN";
break;
case "=":
operatorValue = "EQUAL_TO";
break;
default:
operatorValue = "UNKNOWN";
}
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

Handle additional operators like '!=' in parseCondition.

Currently, the parseCondition function does not handle the 'not equal to' operator !=. If your conditions might include this operator, it's important to parse and process it correctly.

Apply this diff to add support for the != operator:

 const operatorRegex = /([a-zA-Z_]+)\s*(<=?|>=?|=|<|>)\s*([a-zA-Z0-9_]+)/;
+const notEqualRegex = /([a-zA-Z_]+)\s*!=\s*([a-zA-Z0-9_]+)/;

 if (betweenRegex.test(condition)) {
   // existing code
 } else if (operatorRegex.test(condition)) {
   // existing code
+} else if (notEqualRegex.test(condition)) {
+  const match = condition.match(notEqualRegex);
+  const variable = match[1];
+  const comparisonValue = match[2];
+  operatorValue = "NOT_EQUAL_TO";
+  value = { variable, comparisonValue };
 } else {
   throw new Error(`Unknown condition format: ${condition}`);
 }

This modification adds a new regular expression to detect the != operator and handles it accordingly.

Committable suggestion was skipped due to low confidence.

@coderabbitai coderabbitai bot mentioned this pull request Nov 12, 2024
This was referenced Nov 29, 2024
@nabeelmd-eGov nabeelmd-eGov mentioned this pull request Dec 10, 2024
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