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

draft issue fix, table reload fix, table no data fix #1664

Merged
merged 6 commits into from
Oct 25, 2024

Conversation

nabeelmd-eGov
Copy link
Contributor

@nabeelmd-eGov nabeelmd-eGov commented Oct 24, 2024

Choose the appropriate template for your PR:

Summary by CodeRabbit

  • New Features
    • Enhanced loading state visibility in the PlanInbox component with immediate feedback via a Loader component.
  • Improvements
    • Refined state management in the CampaignDetails component for better synchronization with session data.
    • Updated initialization of microplanConfig in the SetupMicroplan component for improved data handling.
    • Streamlined loading state checks in the PlanInbox component for a better user experience during data fetching.
    • Improved organization and readability of code across components for better maintainability.
  • Bug Fixes
    • Improved error handling and loading state clarity across components.

@nabeelmd-eGov nabeelmd-eGov requested a review from a team as a code owner October 24, 2024 15:14
Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces modifications to three components: CampaignDetails, PlanInbox, and SetupMicroplan. Key changes include the addition of a useEffect hook in CampaignDetails for state synchronization, improved loading state management in PlanInbox, and a shift in data handling in SetupMicroplan from params to totalFormData. Formatting adjustments for readability have been made across all components, with no alterations to exported entities.

Changes

File Change Summary
.../CampaignDetails.js Reformatted destructuring of customProps, added useEffect for state synchronization, and improved JSX formatting.
.../PlanInbox.js Introduced conditional rendering for a Loader, updated DataTable rendering logic, and streamlined loading state checks.
.../SetupMicroplan.js Changed initialization of microplanConfig from params to totalFormData, with adjustments in state handling.

Possibly related PRs

Suggested reviewers

  • nipunarora-eGov

🐇 "In the code where rabbits hop,
Changes made will never stop.
With loaders bright and states aligned,
Our components now are well-defined!
So let’s rejoice, both near and far,
For cleaner code, we raise the bar!" 🐇


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 4a13d09 and 2d1e6c3.

📒 Files selected for processing (1)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PlanInbox.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PlanInbox.js (1)

Pattern **/*.js: check

🔇 Additional comments (3)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PlanInbox.js (3)

472-472: LGTM! Payload key updated for bulk update endpoint.

The change from Plan to Plans in the request payload aligns with the bulk update endpoint /plan-service/plan/bulk/_update.


478-478: Loading state implementation needs improvement.

Referring to the previous review comment about improving the loading state implementation using skeleton loaders and showing partial data.


109-109: Verify API contract for parameter renaming.

The parameter has been renamed from executionPlanId to planConfigurationId. While this aligns with the ongoing parameter renaming effort, we should verify the API contract.

✅ Verification successful

Based on the search results, I can make a definitive assessment. The codebase shows consistent usage of planConfigurationId in API endpoints and request payloads, particularly in the microplan module. The old parameter executionPlanId is only used in mapping operations (converting from campaignId) but not in API endpoints.

Parameter renaming is consistent with API contract

The change from executionPlanId to planConfigurationId aligns with the API contract as evidenced by:

  • Multiple components using /plan-service/config/_update endpoint with planConfigurationId
  • No direct API endpoints using executionPlanId
  • Consistent usage of planConfigurationId across the microplan module
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining instances of executionPlanId in API-related files
rg -g "*.js" "executionPlanId" -A 3

# Search for planConfigurationId usage in API calls
rg -g "*.js" "planConfigurationId.*_search|_update" -A 3

Length of output: 26738


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 (3)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/SetupMicroplan.js (2)

Line range hint 156-167: Enhance error handling in form validation

The form validation logic could benefit from more detailed error messages and structured error handling. Currently, it only shows a generic toast message.

Consider enhancing the validation:

 const toastObject = Digit.Utils.microplanv1.formValidator(formData?.[currentConfBody?.key], currentConfBody?.key, state);
 if (toastObject) {
+  const errorDetails = {
+    field: currentConfBody?.key,
+    formData: formData?.[currentConfBody?.key],
+    message: toastObject.label
+  };
+  console.debug('Form validation failed:', errorDetails);
   setShowToast(toastObject);
+  setIsSubmitting(false);  // Reset submission state on validation failure
   return;
 }

Line range hint 211-234: Consolidate navigation event handlers

The component has multiple event listeners for navigation (moveToPrevious, revertToPreviousScreenFromFormula) with similar functionality. This could be consolidated into a single, more maintainable navigation handler.

Consider consolidating the navigation logic:

+const handleNavigation = (type) => {
+  setCurrentStep((prev) => prev - 1);
+  setCurrentKey((prev) => prev - 1);
+};
+
 useEffect(() => {
-  window.addEventListener("moveToPrevious", moveToPreviousStep);
-  return () => {
-    window.removeEventListener("moveToPrevious", moveToPreviousStep);
-  };
-}, []);
-
-useEffect(() => { 
-  window.addEventListener("revertToPreviousScreenFromFormula", goToPreviousScreenFromFormula);
+  const events = ["moveToPrevious", "revertToPreviousScreenFromFormula"];
+  events.forEach(event => {
+    window.addEventListener(event, () => handleNavigation(event));
+  });
   return () => {
-    window.removeEventListener("revertToPreviousScreenFromFormula", goToPreviousScreenFromFormula);
+    events.forEach(event => {
+      window.removeEventListener(event, () => handleNavigation(event));
+    });
   };
 }, []);
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PlanInbox.js (1)

Line range hint 1-549: Consider architectural improvements for better maintainability and performance.

The component has grown complex with multiple responsibilities. Consider these architectural improvements:

  1. State Management:

    • Consider using useReducer for complex state
    • Extract table-related state into a custom hook
    • Memoize expensive computations
  2. Error Handling:

    • Add error boundaries
    • Show error states for failed API calls
    • Add retry mechanisms for failed requests
  3. Performance:

    • Memoize callback functions with useCallback
    • Memoize derived data with useMemo
    • Split into smaller components

Example implementation for table state extraction:

const useTableState = (initialRowsPerPage = 5) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [rowsPerPage, setRowsPerPage] = useState(initialRowsPerPage);
  const [selectedRows, setSelectedRows] = useState([]);
  
  const limitAndOffset = useMemo(() => ({
    limit: rowsPerPage,
    offset: (currentPage - 1) * rowsPerPage
  }), [currentPage, rowsPerPage]);

  return {
    currentPage,
    setCurrentPage,
    rowsPerPage,
    setRowsPerPage,
    selectedRows,
    setSelectedRows,
    limitAndOffset
  };
};

Example error boundary implementation:

const withErrorBoundary = (WrappedComponent) => {
  return class extends React.Component {
    state = { hasError: false };
    
    static getDerivedStateFromError(error) {
      return { hasError: true };
    }
    
    render() {
      if (this.state.hasError) {
        return <Card>Error loading plan inbox. Please try again.</Card>;
      }
      return <WrappedComponent {...this.props} />;
    }
  };
};

export default withErrorBoundary(PlanInbox);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 34b5150 and e192cb7.

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

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PlanInbox.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/CampaignDetails.js

[error] 29-29: 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 (2)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/CampaignDetails.js (1)

90-137: 🛠️ Refactor suggestion

Extract common dropdown props and implement error handling.

The dropdowns share common props and have commented-out error handling code.

Consider creating a reusable dropdown component:

const CommonDropdown = ({ label, options, optionKey, selected, onSelect, disabled }) => (
  <LabelFieldPair>
    <div className="campaign-type" style={{ minWidth: "17rem" }}>
      <span>{t(label)}</span>
      <span className="mandatory-span">*</span>
    </div>
    <Dropdown
      style={{ width: "40rem", paddingBottom: "1rem" }}
      t={t}
      option={options}
      optionKey={optionKey}
      selected={selected}
      select={onSelect}
      disabled={disabled}
    />
  </LabelFieldPair>
);

Also, please implement proper error handling instead of leaving it commented out.

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

42-42: ⚠️ Potential issue

Validate totalFormData before initialization

The initialization of microplanConfig now depends on totalFormData instead of params, but there's no validation to ensure totalFormData is properly initialized. This could lead to undefined behavior if totalFormData is empty during initial render.

Let's verify the initialization flow:

Consider adding validation:

-const [microplanConfig, setMicroplanConfig] = useState(MicroplanConfig(totalFormData, null, isSubmitting, null, hierarchyData));
+const [microplanConfig, setMicroplanConfig] = useState(() => {
+  if (!totalFormData || Object.keys(totalFormData).length === 0) {
+    return MicroplanConfig({}, null, isSubmitting, null, hierarchyData);
+  }
+  return MicroplanConfig(totalFormData, null, isSubmitting, null, hierarchyData);
+});

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

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

Line range hint 149-164: Improve error handling in handleUpdates

The error handling could be enhanced:

  1. The error message fallback uses t("FAILED_TO_UPDATE_RESOURCE") directly, but the error object might contain more specific information
  2. Consider adding error logging for debugging
 onError: (error, variables) => {
   setLoader(false)
+  // Log error for debugging
+  console.error('Resource update failed:', error);
+  
+  // Extract specific error details if available
+  const errorMessage = error?.response?.data?.message || 
+                      error?.message || 
+                      t("FAILED_TO_UPDATE_RESOURCE");
   
   setShowToast({
     key: "error",
-    label: error?.message ? error.message : t("FAILED_TO_UPDATE_RESOURCE"),
+    label: errorMessage,
   });
 },

Line range hint 313-385: Clean up commented code and simplify popup implementation

There are two popup implementations, with one completely commented out. This makes the code harder to maintain.

  1. Remove the commented popup implementation if it's no longer needed
  2. Consider extracting the popup logic into a separate component for better maintainability
-  {/* Default popup */}
-  {/* {showPopUp && (<PopUp
-        className={"boundaries-pop-module"}
-        onClose={()=> setShowPopUp(false)}
-        type={"default"}
-        heading={t("ES_CAMPAIGN_UPDATE_TYPE_MODAL_HEADER")}
-        children={[
-          <div>
-            <CardText style={{ margin: 0 }}>{t("ES_CAMPAIGN_UPDATE_TYPE_MODAL_TEXT") + " "}</CardText>
-          </div>,
-        ]}
-        onOverlayClick={() => {
-          setShowPopUp(false);
-        }}
-        footerChildren={[
-          <Button
-            className={"campaign-type-alert-button"}
-            type={"button"}
-            size={"large"}
-            variation={"secondary"}
-            label={t("Heloo")}
-            onClick={() => {
-              setShowPopUp(false);
-            }}
-          />,
-          <Button
-            className={"campaign-type-alert-button"}
-            type={"button"}
-            size={"large"}
-            variation={"primary"}
-            label={t("ES_CAMPAIGN_BOUNDARY_MODAL_SUBMIT")}
-            onClick={() => {
-              setShowPopUp(false);
-              // setCanUpdate(false);
-            }}
-          />,
-        ]}
-        sortFooterChildren={true}
-      ></PopUp>)} */}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 9eab6ec and 635e026.

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

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PlanInbox.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/CampaignDetails.js

[error] 29-29: 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 (4)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/CampaignDetails.js (2)

23-27: LGTM! Well-implemented state synchronization.

The useEffect hook correctly synchronizes the component's state with session data, including proper dependency tracking and fallback handling.


29-29: ⚠️ Potential issue

Simplify the boolean expression.

The boolean expression can be simplified by removing the redundant ternary operator.

-const [isFreezed, setIsFreezed] = useState(campaignId && microplanId ? true : false);
+const [isFreezed, setIsFreezed] = useState(Boolean(campaignId && microplanId));

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome

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

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

(lint/complexity/noUselessTernary)

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

42-42: Consider tracking hierarchyData changes

The microplanConfig initialization uses hierarchyData but changes to hierarchyData won't trigger a recalculation. This could lead to stale configurations if hierarchyData updates.

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

478-478: Loading state implementation could be improved further.

While showing a loader when any loading state is true is better than waiting for all states, the past review suggestions for using a skeleton loader and showing partial data are still valid to prevent layout shifts and improve user experience.

Let's verify if the Digit UI components support skeleton loading:

#!/bin/bash
# Search for skeleton loader component usage
rg -i 'skeleton|cardSkeleton' --type js

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 635e026 and 4a13d09.

📒 Files selected for processing (1)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PlanInbox.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PlanInbox.js (1)

Pattern **/*.js: check

🔇 Additional comments (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PlanInbox.js (1)

478-478: Loading state implementation could be improved.

A previous review comment already suggested improvements to the loading state implementation, including using skeleton loading and showing partial data. That suggestion is still valid and applicable.

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

3 participants