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

ESTIMATION & FORMULA FIXES #1804

Merged
merged 11 commits into from
Nov 12, 2024
Merged

ESTIMATION & FORMULA FIXES #1804

merged 11 commits into from
Nov 12, 2024

Conversation

nabeelmd-eGov
Copy link
Contributor

@nabeelmd-eGov nabeelmd-eGov commented Nov 12, 2024

  • user tagging fixes
  • Vehicle Assumptions and Vehicle Formula
  • Update health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/Hypothesis.js
  • yarn
  • locaisaton code fixes
  • estimationa and formula fixes

Choose the appropriate template for your PR:

Summary by CodeRabbit

  • New Features

    • Enhanced formula management with improved state handling and user feedback mechanisms.
    • Added tooltips for better visibility of formula outputs.
    • Introduced a new property for formulas to control visibility on the estimation dashboard.
  • Bug Fixes

    • Improved validation for mandatory fields before proceeding with actions.
    • Refined deletion logic for assumptions and formulas to prevent unintended removals.
  • Documentation

    • Updated comments and documentation for improved clarity on component functionalities.
  • Style

    • Adjusted layout styles for better user interface responsiveness.

@nabeelmd-eGov nabeelmd-eGov requested a review from a team as a code owner November 12, 2024 07:12
Copy link
Contributor

coderabbitai bot commented Nov 12, 2024

📝 Walkthrough

Walkthrough

The pull request introduces several enhancements to the FormulaConfigWrapper, FormulaConfiguration, Hypothesis, and SetupMicroplan components. Key changes include improved state management and validation in FormulaConfigWrapper, refined formula deletion logic in FormulaConfiguration, updated assumption handling in Hypothesis, and streamlined data fetching and state handling in SetupMicroplan. These modifications aim to enhance user feedback mechanisms and ensure robust management of formulas and assumptions across the application.

Changes

File Change Summary
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/FormulaConfigWrapper.js Enhanced useEffect for customFormula state, refined handleFormulaChange, added validation in handleNext, and improved visibility logic for formulas.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/FormulaConfiguration.js Updated formula deletion logic, improved safety with optional chaining, refined rendering of formula outputs with tooltips, and enhanced addition of new formulas with default properties.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/Hypothesis.js Modified deletion logic for assumptions, updated rendering for mandatory indicators, improved addition logic for assumptions, and introduced handleUpdateField for assumption name updates.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/SetupMicroplan.js Reformatted imports, streamlined useEffect logic, clarified session invalidation handling, and improved onSubmit function for toast object creation.

Possibly related PRs

Suggested reviewers

  • nipunarora-eGov

🐰 In the garden of code, we play,
With formulas and logic, bright as day.
Assumptions dance, validations sing,
A toast to changes, let the joy spring!
In every line, a story unfolds,
A rabbit's delight in the code it holds! 🥕


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.

@nabeelmd-eGov nabeelmd-eGov changed the title HCMPRE 1131 ESTIMATION & FORMULA FIXES Nov 12, 2024
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: 7

🧹 Outside diff range comments (7)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/Hypothesis.js (1)

Line range hint 82-134: Refactor addNewAssumption for better maintainability

The function is complex with multiple nested conditions and repeated logic patterns. Consider these improvements:

  1. Extract the common logic for adding assumptions into a separate helper function
  2. Add error handling for edge cases (e.g., null selectedDeletedAssumption)
  3. Use early returns to reduce nesting

Here's a suggested structure:

const addAssumptionToState = (assumptionToAdd, source = "MDMS") => {
  if (!assumptionToAdd) return false;
  
  setAssumptions(prev => [...prev, assumptionToAdd.key]);
  if (!assumptionValues.some(assumption => assumption.key === assumptionToAdd.key)) {
    setAssumptionValues(prev => [...prev, { 
      source, 
      key: assumptionToAdd.key, 
      value: null, 
      category 
    }]);
  }
  return true;
};

const addNewAssumption = () => {
  if (!selectedDeletedAssumption) return;

  let success = false;
  if (category === "CAMPAIGN_VEHICLES") {
    success = addAssumptionToState({
      key: selectedDeletedAssumption?.model,
      category
    }, "CUSTOM");
  } else if (selectedDeletedAssumption?.code === "NEW_ASSUMPTION") {
    success = addAssumptionToState({
      key: selectedDeletedAssumption?.name,
      category
    }, "CUSTOM");
  } else {
    const assumptionToAdd = deletedAssumptions.find(
      assumption => assumption === selectedDeletedAssumption.code
    );
    success = addAssumptionToState({ key: assumptionToAdd });
  }

  if (success) {
    setSelectedDeletedAssumption(null);
    setAssumptionsPopUp(false);
  }
};
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/SetupMicroplan.js (2)

Line range hint 228-232: Add defensive checks for form data

The form validation lacks defensive checks for the formData parameter. Consider adding type checking to prevent potential runtime errors.

- const toastObject = Digit.Utils.microplanv1.formValidator(formData?.[currentConfBody?.key], currentConfBody?.key, state, t);
+ const toastObject = formData && currentConfBody?.key 
+   ? Digit.Utils.microplanv1.formValidator(formData[currentConfBody.key], currentConfBody.key, state, t)
+   : { key: 'error', label: 'INVALID_FORM_DATA' };

Line range hint 13-434: Consider breaking down the component for better maintainability

The SetupMicroplan component is handling multiple responsibilities including:

  • State management
  • Form validation
  • Navigation
  • Session storage
  • Event handling

Consider breaking it down into smaller, more focused components to improve maintainability and testing.

Suggestions:

  1. Extract form handling logic into a custom hook
  2. Create separate components for different steps
  3. Consider using React Context for state management instead of direct session storage
  4. Implement a proper state machine for step management
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/FormulaConfiguration.js (1)

Line range hint 40-47: Consider extracting category-specific logic

The special case handling for "CAMPAIGN_VEHICLES" category is embedded in the deletion validation. Consider extracting this business rule into a configuration or utility function for better maintainability.

+const CATEGORIES_ALLOWING_EMPTY_FORMULAS = ['CAMPAIGN_VEHICLES'];
+
+const isFormulaDeleteAllowed = (formulas, category) => {
+  return formulas?.length > 1 || CATEGORIES_ALLOWING_EMPTY_FORMULAS.includes(category);
+};
+
 if (formulas?.length === 1 && category !== "CAMPAIGN_VEHICLES") {
-  setShowToast({
-    key: "error",
-    label: t("ERR_ATLEAST_ONE_MANDATORY_FORMULA"),
-    transitionTime: 3000,
-  });
-  return;
+  if (!isFormulaDeleteAllowed(formulas, category)) {
+    setShowToast({
+      key: "error",
+      label: t("ERR_ATLEAST_ONE_MANDATORY_FORMULA"),
+      transitionTime: 3000,
+    });
+    return;
+  }
 }
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/FormulaConfigWrapper.js (3)

Line range hint 146-157: Centralize error handling and ensure consistent error message internationalization.

The error handling is scattered and some error messages might not be internationalized. Consider creating a centralized error handling utility.

+const ERROR_TYPES = {
+  MANDATORY_FIELD: 'ERR_MANDATORY_FIELD',
+  UPDATE_FAILED: 'FAILED_TO_UPDATE_RESOURCE',
+};
+
+const handleError = (error, setShowToast, t) => {
+  const errorMessage = error?.message ? error.message : t(ERROR_TYPES.UPDATE_FAILED);
+  setShowToast({ 
+    key: "error", 
+    label: t(errorMessage),
+    transitionTime: 3000 
+  });
+};

 if (formulaConfigValues.filter((row) => row.category === currentCategory)
   .every((row) => {
     return row.assumptionValue && row.input && row.output && row.operatorName;
   })) {
   // ... existing code
 } else {
-  setShowToast({
-    key: "error",
-    label: t("ERR_MANDATORY_FIELD"),
-    transitionTime: 3000,
-  });
+  handleError(null, setShowToast, t);
   return;
 }

Line range hint 16-40: Consider using useReducer for complex state management.

The component manages multiple related states that could be better organized using useReducer. This would make state updates more predictable and easier to maintain.

+const formulaReducer = (state, action) => {
+  switch (action.type) {
+    case 'SET_FORMULA_CONFIG':
+      return { ...state, formulaConfigValues: action.payload };
+    case 'SET_DELETED_FORMULAS':
+      return { ...state, deletedFormulas: action.payload };
+    case 'SET_CUSTOM_FORMULA':
+      return { ...state, customFormula: action.payload };
+    default:
+      return state;
+  }
+};
+
 const FormulaConfigWrapper = ({ onSelect, props: customProps }) => {
-  const [formulaConfigValues, setFormulaConfigValues] = useState([]);
-  const [deletedFormulas, setDeletedFormulas] = useState([]);
-  const [customFormula, setCustomFormula] = useState([]);
+  const [state, dispatch] = useReducer(formulaReducer, {
+    formulaConfigValues: [],
+    deletedFormulas: [],
+    customFormula: []
+  });

Line range hint 1-576: Consider breaking down the component for better maintainability and performance.

The component is handling too many responsibilities which makes it hard to maintain and potentially impacts performance. Consider splitting it into smaller, focused components.

  1. Extract the formula configuration logic into a separate hook:
// useFormulaConfiguration.js
export const useFormulaConfiguration = (props) => {
  // Formula-related state and logic
  return {
    formulaState,
    handleFormulaChange,
    // ... other formula-related functions
  };
};
  1. Extract the stepper logic into a separate component:
// FormulaConfigStepper.js
const FormulaConfigStepper = ({ steps, currentStep, onStepClick }) => {
  // Stepper-related logic
};
  1. Create a dedicated context provider component:
// FormulaContextProvider.js
const FormulaContextProvider = ({ children }) => {
  // Context-related logic
  return (
    <FormulaContext.Provider value={contextValue}>
      {children}
    </FormulaContext.Provider>
  );
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 4bf3640 and 48934c2.

📒 Files selected for processing (4)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/FormulaConfigWrapper.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/FormulaConfiguration.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/Hypothesis.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/SetupMicroplan.js (5 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/FormulaConfigWrapper.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/FormulaConfiguration.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/Hypothesis.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/SetupMicroplan.js (1)

Pattern **/*.js: check

🪛 Biome
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/FormulaConfiguration.js

[error] 314-314: Avoid passing children using a prop

The canonical way to pass children in React is to use JSX elements

(lint/correctness/noChildrenProp)

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/Hypothesis.js

[error] 163-163: Avoid passing children using a prop

The canonical way to pass children in React is to use JSX elements

(lint/correctness/noChildrenProp)

🔇 Additional comments (2)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/Hypothesis.js (2)

181-181: Verify translation coverage for new placeholder text

The category-specific placeholder is a good UX improvement. However, ensure that all translation keys are properly defined.

#!/bin/bash
# Check if the translation keys exist in the translation files
rg "MP_ENTER_ASSUMPTION_CAMPAIGN_VEHICLES|MP_ENTER_ASSUMPTION" public/localization/

Line range hint 41-50: Verify deletion restriction logic against business requirements

The condition ensures at least one assumption remains for non-CAMPAIGN_VEHICLES categories, which is good for data integrity. However, consider these improvements:

  1. Add a comment explaining why CAMPAIGN_VEHICLES is exempt from this rule
  2. Consider extracting the error message key to a constant for maintainability
✅ Verification successful

Special handling for CAMPAIGN_VEHICLES category is consistently implemented

The verification reveals that the CAMPAIGN_VEHICLES exception is consistently implemented across the codebase:

  1. In Hypothesis.js:

    • Deletion restriction is properly enforced (non-CAMPAIGN_VEHICLES categories must retain at least one assumption)
    • Special UI handling (custom placeholders, labels, and popup messages)
    • Mandatory field indicators are suppressed
  2. In FormulaConfiguration.js:

    • Same deletion restriction pattern is applied
    • Consistent UI treatment for mandatory indicators

The comment about "atleast one assumption in each category has to be mandatory to support draft functionality" adequately explains the business requirement, making the CAMPAIGN_VEHICLES exception clear.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify if this deletion restriction is consistently applied across the codebase
rg -l "CAMPAIGN_VEHICLES" . | xargs rg "handleDeleteClick|deletion|remove" -A 5

Length of output: 240


Script:

#!/bin/bash
# Search for CAMPAIGN_VEHICLES usage in the codebase
rg "CAMPAIGN_VEHICLES" -B 2 -A 2

# Search for assumption deletion related logic
rg "handleDeleteClick|setAssumptionToDelete|assumptions\?.length" -B 2 -A 2

Length of output: 14732

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.

3 participants