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

changes for the draft flow #1780

Merged
merged 1 commit into from
Nov 8, 2024
Merged

changes for the draft flow #1780

merged 1 commit into from
Nov 8, 2024

Conversation

Bhavya-egov
Copy link
Contributor

@Bhavya-egov Bhavya-egov commented Nov 8, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Improved loading state management in the Cycle Configuration component, enhancing user experience during data retrieval.
    • Enhanced handling of campaign setup logic for better responsiveness to user input and URL parameters.
  • Bug Fixes

    • Refined data processing in the Details Table for better value translation and attribute handling.
  • Refactor

    • Streamlined data handling and standardized terminology in campaign setup helper functions, improving code clarity and maintainability.

@Bhavya-egov Bhavya-egov requested a review from a team as a code owner November 8, 2024 09:29
Copy link
Contributor

coderabbitai bot commented Nov 8, 2024

📝 Walkthrough

Walkthrough

The changes involve modifications across several components in the campaign management module. The DetailsTable component now includes enhanced data processing logic for value and attribute translations. The CycleConfiguration component introduces loading state management with a new Loader component. The SetupCampaign component has streamlined its state management and URL parameter handling. Additionally, the getDeliveryConfig function has been updated for more dynamic delivery configuration based on index, while setupCampaignHelpers.js has improved data handling practices and standardized terminology.

Changes

File Change Summary
.../campaign-manager/src/components/DetailsTable.js Enhanced data processing logic for value and attribute translations in DetailsTable.
.../campaign-manager/src/pages/employee/CycleConfiguration.js Added Loader for loading state management; introduced isLoading state variable; modified useEffect for loading logic based on filteredDeliveryConfig.
.../campaign-manager/src/pages/employee/SetupCampaign.js Introduced new useEffect for managing isDraftCreated and currentKey; streamlined logic for handling draft data and URL parameters; refined state management for fetchUpload and fetchBoundary.
.../campaign-manager/src/utils/getDeliveryConfig.js Updated generateMRDNConfig to include an index parameter for conditional delivery type assignment; refined logic for constructing conditionConfig.
.../campaign-manager/src/utils/setupCampaignHelpers.js Introduced cloneDeep for deep copying DeliveryConfig; standardized terminology by renaming deliveryStrategy to deliveryType; updated functions for consistency in handling delivery types.

Possibly related PRs

  • fixed summary and campaign creation #1479: Changes in SetupCampaign.js regarding restructuring data handling and validation logic are related to modifications in DetailsTable.js, both enhancing data processing within campaign management.
  • updated summary redirection #1488: Updates in SetupCampaign.js that manage currentKey state are relevant to changes in DetailsTable.js, both dealing with data handling and state management.
  • project type config simplified #1539: Modifications in CampaignSummary.js that enhance data handling are related to changes in DetailsTable.js, both managing campaign data presentation.
  • added condition for update #1541: Changes in UpdateBoundary.js that improve validation logic are relevant to updates in DetailsTable.js, focusing on data integrity in campaign information.
  • fixed NA issue of summary #1681: Enhancements in SetupCampaign.js integrating cycle configuration relate to changes in DetailsTable.js, both refining data processing in campaign setup.

Suggested reviewers

  • jagankumar-egov

Poem

🐇 In the meadow where data flows,
A rabbit hops where the campaign grows.
With loaders and states, we dance and play,
Translating values in a clever way.
So here's to the code, both bright and new,
A joyful leap for the team, it's true! 🌼


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

🧹 Outside diff range comments (8)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DetailsTable.js (2)

Line range hint 26-40: Improve code structure and readability.

The nested ternary operations and complex conditional logic make the code harder to maintain.

Consider restructuring the attribute translation logic:

-      attribute: i?.attribute?.code 
-    ? t(`CAMPAIGN_ATTRIBUTE_${i.attribute.code.toUpperCase()}`) 
-    : i?.attribute 
-        ? t(`CAMPAIGN_ATTRIBUTE_${i.attribute}`) 
-        : "",
+      attribute: getAttributeTranslation(i?.attribute),

Add a helper function at the top of the file:

const getAttributeTranslation = (attribute) => {
  if (!attribute) return "";
  const code = attribute.code || attribute;
  return t(`CAMPAIGN_ATTRIBUTE_${code.toUpperCase()}`);
};

Line range hint 13-40: Consider memoizing translation function calls.

The component re-renders might trigger unnecessary translation calls for static content.

Consider memoizing frequently used translations or moving them outside the memoized data calculation:

const memoizedTranslations = React.useMemo(() => ({
  inBetween: t('IN_BETWEEN'),
  na: t('N/A')
}), [t]);
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (2)

Line range hint 105-135: Add error handling and optimize the implementation.

The implementation could benefit from several improvements:

  1. Error handling:
 return data?.deliveries?.map(delivery => {
+  if (!delivery?.doseCriteria?.length) {
+    return { delivery: delivery.id, conditionConfig: [] };
+  }
   const conditionConfig = delivery.doseCriteria.map((dose, index) => {
  1. Performance and maintainability:
-      const productConfig = dose.ProductVariants.map(variant => ({
-        key: 1,
-        name: variant.name,
-        count: variant.quantity,
-        value: variant.productVariantId
-      }));
+      const productConfig = dose.ProductVariants?.map((variant, idx) => ({
+        key: idx + 1,
+        name: variant.name,
+        count: variant.quantity,
+        value: variant.productVariantId
+      })) ?? [];
  1. Dynamic attribute type:
-          attrType: "dropdown",
+          attrType: dose.attrType || "dropdown",

Line range hint 105-135: Consider extracting mapping logic into separate functions.

The nested mapping operations make the code harder to maintain. Consider extracting the product and attribute configuration logic into separate functions:

+const mapProductConfig = (variants = []) => 
+  variants.map((variant, idx) => ({
+    key: idx + 1,
+    name: variant.name,
+    count: variant.quantity,
+    value: variant.productVariantId
+  }));

+const mapAttributeConfig = (condition, dose) => {
+  const { operatorValue, value } = parseCondition(condition);
+  return {
+    key: 1,
+    label: "Custom",
+    attrType: dose.attrType || "dropdown",
+    attrValue: value.variable,
+    fromValue: value.minValue || value.comparisonValue,
+    toValue: value.maxValue || null,
+    operatorValue
+  };
+};

 const generateMRDNConfig = (data) => {
   return data?.deliveries?.map(delivery => {
     const conditionConfig = delivery.doseCriteria.map((dose, index) => {
-      const productConfig = dose.ProductVariants.map(variant => ({
-        key: 1,
-        name: variant.name,
-        count: variant.quantity,
-        value: variant.productVariantId
-      }));
+      const productConfig = mapProductConfig(dose.ProductVariants);
       
       const conditions = dose.condition.split('and');
-      const attributeConfigs = conditions.map(condition => {
-        const { operatorValue, value } = parseCondition(condition);
-        return {
-          key: 1,
-          label: "Custom",
-          attrType: "dropdown",
-          attrValue: value.variable,
-          fromValue: value.minValue || value.comparisonValue,
-          toValue: value.maxValue || null,
-          operatorValue
-        };
-      });
+      const attributeConfigs = conditions.map(condition => 
+        mapAttributeConfig(condition, dose)
+      );
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.js (2)

Line range hint 77-91: Simplify the enabled property in useCustomMDMS hook.

The boolean expression can be simplified by directly using the selectedProjectType variable.

-      enabled: selectedProjectType ? true : false,
+      enabled: !!selectedProjectType,
🧰 Tools
🪛 Biome

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


The executionCount implementation is unnecessary and can be removed

The executionCount implementation in CycleConfiguration.js is redundant because:

  1. The component already has a dedicated useEffect hook that updates the state through onSelect("cycleConfigure", state) whenever state changes
  2. The additional useEffect with executionCount creates unnecessary re-renders by forcing the same state update up to 5 times without any conditional logic

The following code block should be removed as it's redundant:

useEffect(() => {
  if (executionCount < 5) {
    onSelect("cycleConfigure", state);
    setExecutionCount((prevCount) => prevCount + 1);
  }
});
🔗 Analysis chain

Line range hint 134-140: Review the necessity of executionCount implementation.

The useEffect with executionCount seems to force state updates up to 5 times. This could indicate an underlying issue with state management that should be investigated.

Consider refactoring to avoid the need for forced state updates. If you need assistance with the refactoring, I can help propose a more robust solution.


Let me search for the usage pattern of executionCount to understand its implementation better.


Let me try a different approach to find the executionCount usage pattern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar patterns of execution counting in the codebase
rg -A 2 "executionCount.*useState.*0" 

Length of output: 8871


Script:

#!/bin/bash
# Search for useEffect patterns with executionCount in CycleConfiguration.js
rg -A 10 "useEffect.*executionCount" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.js

Length of output: 152


Script:

#!/bin/bash
# Get the content of CycleConfiguration.js to understand the executionCount implementation
cat health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.js

Length of output: 12631

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

Line range hint 1-400: Consider improving documentation and code organization.

While the code is functional, it could benefit from:

  1. Adding JSDoc comments for each exported function
  2. Breaking down complex functions into smaller, more focused ones
  3. Adding type annotations for better maintainability

Example improvement for one of the functions:

/**
 * Restructures campaign delivery data into a standardized format
 * @param {Object} data - Raw campaign data
 * @param {Object} cycleData - Cycle configuration data
 * @param {Array} DeliveryConfig - Available delivery configurations
 * @param {string} projectType - Type of the project
 * @returns {Array} Restructured delivery configuration
 */
export const restructureData = (data, cycleData, DeliveryConfig, projectType) => {
  // ... existing implementation
}
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (1)

Line range hint 1-24: Consider architectural improvements for better maintainability.

The component would benefit from several architectural improvements:

  1. Consider using a reducer for complex state management
  2. Implement proper error boundaries
  3. Split the component into smaller, more focused components
  4. Add proper TypeScript types for better type safety

Example reducer structure:

const campaignReducer = (state, action) => {
  switch (action.type) {
    case 'SET_DRAFT':
      return { ...state, isDraft: true, currentKey: action.payload };
    case 'UPDATE_FORM_DATA':
      return { ...state, formData: { ...state.formData, ...action.payload } };
    // ... other cases
  }
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 6eb526a and f07aa9d.

📒 Files selected for processing (5)
  • 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/pages/employee/CycleConfiguration.js (4 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/setupCampaignHelpers.js (5 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
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/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/utils/getDeliveryConfig.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

🪛 Biome
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.js

[error] 84-84: 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 (5)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DetailsTable.js (1)

26-28: 🛠️ Refactor suggestion

Verify translation key existence for dynamic values.

The direct translation of i.value might fail if the translation key doesn't exist in the translation files. Consider adding a fallback mechanism.

Consider implementing a safer translation approach:

-      value: typeof i?.value === "string" 
-      ? t(i.value) 
-      : i?.value,
+      value: typeof i?.value === "string" 
+        ? t(i.value, { defaultValue: i.value }) 
+        : i?.value,
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (1)

Line range hint 105-135: Verify the impact of disableDeliveryType flag.

The implementation sets disableDeliveryType: index === 0, which means only the first delivery type will be enabled. Let's verify if this change is intentional and properly handled in the UI.

✅ Verification successful

Let me gather more information about how this flag is used in the UI component.


Let me check one more thing to understand the delivery strategy selection implementation.


The disableDeliveryType flag is correctly implemented and handled in the UI

The verification shows that:

  • The flag is properly used in AddDeliverycontext.js to disable the delivery type selection for the first dose
  • The UI component correctly handles this through a disabled prop that evaluates the disableDeliveryType flag
  • The implementation allows changing delivery types for subsequent doses while keeping the first dose's delivery type fixed

This is an intentional design choice to maintain consistency in the delivery strategy, where the first dose's delivery type serves as the base configuration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for components that handle the disableDeliveryType prop
rg -l "disableDeliveryType" --type js

# Search for any UI components that might be affected by this flag
ast-grep --pattern 'disabled={$_?.disableDeliveryType}'

Length of output: 326


Script:

#!/bin/bash
# Check the implementation in AddDeliverycontext.js
rg "disableDeliveryType" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddDeliverycontext.js -B 2 -A 2

# Look for any dropdown or select components that might be using this flag
rg -A 5 "Select|Dropdown" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddDeliverycontext.js

Length of output: 2943


Script:

#!/bin/bash
# Look for the delivery strategy selection component and its usage
rg "deliveryStrategy|updateDeliveryType" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddDeliverycontext.js -B 2 -A 5

Length of output: 933

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

1-2: LGTM: Loading state management follows React best practices.

The addition of the Loader component and loading state management is implemented correctly.

Also applies to: 75-75

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

5-6: Great optimization on lodash import!

The change from importing the entire lodash library to importing just the cloneDeep function will help reduce the bundle size through better tree-shaking.


127-127: Verify consistent usage of deliveryType across the codebase.

The renaming from deliveryStrategy to deliveryType with a default value of "DIRECT" has been applied consistently in this file. Let's verify this change across the entire codebase to ensure all references have been updated.

Also applies to: 143-143, 164-164

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