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

Edit in Draft flow #2014

Open
wants to merge 17 commits into
base: console
Choose a base branch
from
Open

Edit in Draft flow #2014

wants to merge 17 commits into from

Conversation

abishekTa-egov
Copy link
Contributor

@abishekTa-egov abishekTa-egov commented Dec 11, 2024

Choose the appropriate template for your PR:

Feature PR

Feature Request

JIRA ID

Module

Description

Related Issues


Bugfix PR

Bugfix Request

JIRA ID

Module

Description

Root Cause

Related Issues


Release PR

Summary by CodeRabbit

  • New Features

    • Enhanced handling of action selections and file downloads in MicroplanSearchConfig.
    • Added user hierarchy level display in the FacilityCatchmentMapping, PlanInbox, and PopInbox components.
    • Improved user feedback and error handling in the UserUpload component.
  • Bug Fixes

    • Enhanced state synchronization in the AssumptionsForm component for better responsiveness to prop updates.
  • Documentation

    • Updated method signatures in UICustomizations to reflect new logic for action handling and URL construction.
  • Chores

    • Adjusted control flow in createUpdatePlanProject to incorporate a new parameter for dynamic updates.

@abishekTa-egov abishekTa-egov requested a review from a team as a code owner December 11, 2024 12:19
Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces significant modifications across several JavaScript files related to UI customizations and form management. Key updates include new configurations for search and user management, enhancements to existing functions for improved data handling, and the integration of a key parameter in various functions to support dynamic updates. The changes aim to refine user interactions and ensure better synchronization between component state and props.

Changes

File Change Summary
health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js - Updated MicroplanSearchConfig with dynamic status mapping based on tabId.
- Enhanced additionalCustomizations for file download actions.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/AssumptionsForm.js - Added useEffect for synchronizing local state with props.
- Adjusted existing useEffect hooks for improved selection logic based on new state values.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/configs/UICustomizations.js - Updated onActionSelect function for URL construction based on row?.additionalDetails?.key.
- Enhanced action handling for MicroplanSearchConfig and MyMicroplanSearchConfig.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js - Added key parameter to createUpdatePlanProject and associated functions for enhanced dynamic updates.
- Refactored error handling in "ROLE_ACCESS_CONFIGURATION" case.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/FacilityCatchmentMapping.js - Added hierarchy level to user role display.
- Refined logic for disabledAction state based on process instance actions.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PlanInbox.js - Updated user role display to include hierarchy level.
- No changes to logic or control flow.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PopInbox.js - Modified user role display to include hierarchy level.
- Adjusted action bar visibility logic based on user role and data state.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UserUpload.js - Updated success message in onSubmit function.
- Enhanced error handling for file upload and validation processes.

Possibly related PRs

  • Facility data fix #1829: The changes in UICustomizations.js enhance the additionalCustomizations method for MicroplanSearchConfig, which is directly related to the modifications made in the main PR regarding the MicroplanSearchConfig in UICustomizations.js.
  • My MICROPLAN fixes, formula fixes #1835: This PR includes updates to the UICustomizations object, particularly in the MyMicroplanSearchConfig section, where the preProcess method is updated to refine handling based on tabId, which aligns with the changes made in the main PR.
  • Po finding fixes2 #1845: Modifications to UICustomizations object, specifically enhancing the MICROPLAN_FACILITY_RESIDINGVILLAGE key, which is relevant to the changes made in the main PR regarding UICustomizations.js.
  • Updated hrms path #1979: This PR refactors the UserManagementConfig to dynamically retrieve the hrms_context_path, which may relate to the overall configuration and customization logic in the main PR.
  • Some handlings #1980: This PR introduces error handling improvements in the UploadDataCustom component, which may connect to the overall enhancements in user interaction and error management discussed in the main PR.

Suggested reviewers

  • nipunarora-eGov

🐰 In the code we hop and play,
New configs brighten up the way.
With each change, the UI sings,
Enhancing all the little things.
So let us cheer, both loud and clear,
For better flows and less to fear! 🥕

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ac6cf5d and 7872f44.

📒 Files selected for processing (1)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js (12 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js (1)

Pattern **/*.js: check

🪛 Biome (1.9.4)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js

[error] 817-842: This case is falling through to the next case.

Add a break or return statement to the end of this case to prevent fallthrough.

(lint/suspicious/noFallthroughSwitchClause)

🔇 Additional comments (11)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js (11)

202-202: Be mindful not to overwrite existing properties in additionalDetails.

If currentPlanObject.additionalDetails already contains a key attribute, this code replaces it by default with "2". Confirm whether this behavior is intended or whether the existing value should be preserved or renamed.


278-279: Verify the usage of key from Query Params vs. Config.

You’re extracting key from query parameters while also referencing req?.config?.key. Confirm whether you need both or rename them to reduce potential confusion.


404-404: Confirm 'key' addition does not overwrite existing properties.

If fetchedPlanForBoundaryInvalidate.additionalDetails already contains a key, this code overwrites it. Consider renaming or checking before overwriting.


486-486: Confirm 'key' addition does not overwrite existing properties.

Check if planObject?.additionalDetails may already contain a key. If so, validate whether overwriting it is the intended behavior.


523-523: Confirm 'key' addition does not overwrite existing properties.

When merging fetchedPlanForHypothesis.additionalDetails with a new key, ensure that overwriting an existing key is intentional.


565-565: Confirm 'key' addition does not overwrite existing properties.

Before assigning key, consider verifying if fetchedPlanForSubHypothesis.additionalDetails contains a key to avoid unintended data loss.


611-611: Confirm 'key' addition does not overwrite existing properties.

When adding a new key, ensure you’re not unintentionally discarding an existing key property in fetchedPlanForFormula.additionalDetails.


664-664: Confirm 'key' addition does not overwrite existing properties.

Double-check if fetchedPlanForSubFormula.additionalDetails has a key attribute you need to preserve or if overwriting it is deliberate.


696-696: Confirm 'key' addition does not overwrite existing properties.

Ensure fetchedPlanForBoundary.additionalDetails does not lose a relevant key value if it already exists in the object.


739-739: Confirm 'key' addition does not overwrite existing properties.

Attaching key to fetchedPlanForFacility.additionalDetails may potentially overwrite an existing key field. Consider verifying your intent.


817-842: ⚠️ Potential issue

Add a break or return statement to prevent fallthrough.

In the "ROLE_ACCESS_CONFIGURATION" case, if response is falsy, the code sets setShowToast but never breaks or returns, inadvertently falling through to the default case. Fix this by returning or breaking:

} else {
  setShowToast({ key: "error", label: "ERR_FAILED_TO_UPDATE_PLAN" });
+ return {
+   triggeredFrom,
+ };
}

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome (1.9.4)

[error] 817-842: This case is falling through to the next case.

Add a break or return statement to the end of this case to prevent fallthrough.

(lint/suspicious/noFallthroughSwitchClause)


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 4

🧹 Outside diff range comments (1)
health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js (1)

Line range hint 110-119: Use Number.parseInt and specify radix for integer parsing

In lines 111 and 112, you are using the global parseInt function without specifying a radix. This can lead to unexpected results if the input string starts with '0'. It's recommended to use Number.parseInt with an explicit radix of 10 for consistency and to avoid potential issues.

Apply this diff to update the code:

- if(parseInt(row?.additionalDetails?.key)!==9){
+ if(Number.parseInt(row?.additionalDetails?.key, 10)!==9){
- window.location.href = `/${window.contextPath}/employee/microplan/setup-microplan?key=${String(parseInt(row?.additionalDetails?.key || '2'))}&microplanId=${row.id}&campaignId=${
+ window.location.href = `/${window.contextPath}/employee/microplan/setup-microplan?key=${String(Number.parseInt(row?.additionalDetails?.key || '2', 10))}&microplanId=${row.id}&campaignId=${
🧰 Tools
🪛 Biome (1.9.4)

[error] 829-829: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)


[error] 830-830: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 1f0888b and d4fea63.

📒 Files selected for processing (4)
  • health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/AssumptionsForm.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/configs/UICustomizations.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js (12 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/AssumptionsForm.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js (1)

Pattern **/*.js: check

🪛 Biome (1.9.4)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/configs/UICustomizations.js

[error] 111-111: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)


[error] 112-112: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)

health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js

[error] 829-829: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)


[error] 830-830: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)

🔇 Additional comments (10)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js (9)

202-202: Ensure consistent default value for 'key' in 'UpdateResource'

In the UpdateResource function, you are setting the key in additionalDetails as req?.config?.key || "2". Please verify that defaulting to "2" when req?.config?.key is undefined is intentional and consistent with how key is handled elsewhere in the codebase. This default value should not cause unintended behavior in subsequent logic.


278-279: Handle potential undefined 'key' from query parameters

You are destructuring key from Digit.Hooks.useQueryParams(). Ensure that the key parameter is always present in the URL's query parameters when this function is called, or add a default value to handle cases when it's undefined to prevent possible errors.


486-486: Confirm correct assignment of 'key' in 'additionalDetails'

In line 486, you're adding key: key to additionalDetails. Ensure that the value of key is as expected and that this assignment aligns with the application's logic.


523-523: Ensure 'key' is properly assigned in 'additionalDetails'

Verify that adding key: key to additionalDetails at this point does not conflict with existing data and that key holds the correct value needed for downstream processes.


565-565: Check for potential conflicts when setting 'key' in 'additionalDetails'

On line 565, you're updating additionalDetails with key: key. Please ensure this does not overwrite important data and that key is intended to be set or updated here.


611-611: Verify 'key' assignment in formula updates

In line 611, confirm that adding key: key to additionalDetails when updating formulas is necessary and does not interfere with existing keys or data.


664-664: Ensure correct handling of 'key' in sub-formula updates

When updating additionalDetails on line 664, check that assigning key: key aligns with the application's state management and does not cause unintended side effects.


696-696: Confirm 'key' inclusion in boundary file updates

At line 696, verify that adding key: key to additionalDetails during boundary file updates is appropriate and does not overwrite any existing key values unintentionally.


739-739: Check 'key' assignment when updating facility files

On line 739, ensure that adding key: key to additionalDetails is correct and consistent with how key is used in other parts of the code.

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

71-75: State synchronization with props is correctly implemented

The useEffect hook updates the local state variables when assumptionsForm in props changes, ensuring the component reflects the latest data from the parent. This approach helps keep the state in sync with prop updates.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

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

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

The component has grown complex with multiple responsibilities:

  • Multiple API calls and state management
  • Complex conditional rendering
  • Workflow state handling

Consider these architectural improvements:

  1. Extract API calls into a custom hook (e.g., useFacilityMapping)
  2. Break down into smaller components (e.g., FacilityHeader, FacilityActions)
  3. Implement a workflow state machine for better state management

Line range hint 25-85: Improve error handling for API calls

The component fetches data from multiple endpoints but doesn't handle error states properly. Consider implementing proper error handling for better user experience.

Example implementation for error handling:

const ErrorDisplay = ({ error, onRetry }) => (
  <div className="error-container">
    <p>{error.message || 'An error occurred'}</p>
    {onRetry && <Button onClick={onRetry} label="Retry" />}
  </div>
);

// Usage in component:
if (planEmployeeError) {
  return <ErrorDisplay error={planEmployeeError} onRetry={refetchPlanEmployee} />;
}

Line range hint 86-93: Optimize workflow state management

The current workflow state check using array.some() in the useEffect could be optimized to prevent unnecessary re-renders.

Consider this optimization:

- useEffect(() => {
-   if (processData && processData.some((instance) => instance.action === "FINALIZE_CATCHMENT_MAPPING")) {
-     setDisabledAction(true);
-   }
- }, [processData]);

+ const isActionDisabled = useMemo(() => {
+   return processData?.some((instance) => instance.action === "FINALIZE_CATCHMENT_MAPPING") ?? false;
+ }, [processData]);
+ 
+ useEffect(() => {
+   setDisabledAction(isActionDisabled);
+ }, [isActionDisabled]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d4fea63 and 60951f6.

📒 Files selected for processing (3)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/FacilityCatchmentMapping.js (1 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/PopInbox.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PopInbox.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

📓 Learnings (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PopInbox.js (2)
Learnt from: rachana-egov
PR: egovernments/DIGIT-Frontend#1832
File: health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PopInbox.js:592-594
Timestamp: 2024-11-14T12:48:23.024Z
Learning: In `PopInbox.js`, when integrating the `ConfirmationPopUp` component, error handling for API failures is managed internally within the component, so explicitly passing an `onError` prop is not necessary.
Learnt from: rachana-egov
PR: egovernments/DIGIT-Frontend#1837
File: health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PopInbox.js:559-561
Timestamp: 2024-11-15T10:15:57.370Z
Learning: In `PopInbox.js`, error handling for the `onError` callback in `WorkflowCommentPopUp` is handled within the component, so explicit error handling in the parent component is unnecessary.

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

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

Line range hint 144-157: Standardize error handling patterns

The error handling across different functions could be improved for consistency and better user experience:

  1. In fetchData, error parsing is inconsistent between different catch blocks
  2. In onSubmit, error handling could be simplified and standardized

Consider applying these improvements:

 } catch (error) {
-  var errorLabel;
-  if (error?.response && error?.response?.data) {
-    const errorMessage = error?.response?.data?.Errors?.[0]?.message;
-    const errorDescription = error?.response?.data?.Errors?.[0]?.description;
-    if (errorDescription) {
-      errorLabel = `${errorMessage} : ${errorDescription}`;
-    } else {
-      errorLabel = String(error?.message);
-    }
-  }
-  console.error("Error fetching data:", error);
-  setShowToast({ key: "error", label: errorLabel });
+  const errorMessage = error?.response?.data?.Errors?.[0];
+  const errorLabel = errorMessage
+    ? t("ERROR_WITH_DESC", {
+        message: errorMessage.message,
+        description: errorMessage.description
+      })
+    : t("ERROR_DEFAULT_MESSAGE");
+  setShowToast({ key: "error", label: errorLabel });
   setDownloadTemplateLoader(false);
   return;
 }

Also applies to: 365-380


Line range hint 27-42: Improve state management and side effects handling

The component's state management could be improved to prevent potential race conditions and memory leaks:

  1. The useEffect hook doesn't have a cleanup function
  2. Multiple async operations could lead to race conditions
  3. Complex state management could benefit from useReducer

Consider these improvements:

+ const [abortController] = useState(new AbortController());
+ 
  useEffect(async () => {
+   const signal = abortController.signal;
    const fetchData = async () => {
      if (!errorsType[type] && uploadedFile?.length > 0 && !isSuccess) {
        setIsValidation(true);
        setLoader(true);
        try {
-         const temp = await Digit.Hooks.campaign.useResourceData(/*...*/);
+         const temp = await Digit.Hooks.campaign.useResourceData(
+           uploadedFile,
+           state?.hierarchyType,
+           type,
+           tenantId,
+           id,
+           baseTimeOut?.["HCM-ADMIN-CONSOLE"],
+           { source: "microplan", signal }
+         );
          // ... rest of the code
        } catch (error) {
+         if (error.name === 'AbortError') return;
          console.log(error);
        }
      }
    };

    await fetchData();
+   return () => {
+     abortController.abort();
+   };
-  }, [errorsType]);
+  }, [errorsType, abortController]);

Also consider refactoring the complex state management using useReducer:

const initialState = {
  isError: false,
  isSuccess: false,
  isValidation: false,
  loader: false,
  showToast: null,
  // ... other state
};

function reducer(state, action) {
  switch (action.type) {
    case 'START_VALIDATION':
      return { ...state, isValidation: true, loader: true };
    case 'VALIDATION_SUCCESS':
      return { 
        ...state, 
        isValidation: false, 
        loader: false,
        isSuccess: true,
        showToast: { key: 'success', label: 'HCM_VALIDATION_COMPLETED' }
      };
    // ... other cases
    default:
      return state;
  }
}

Also applies to: 52-157


Line range hint 183-227: Add security measures for file upload handling

The current file upload implementation lacks several important security measures:

  1. No file type validation
  2. Missing file size limits
  3. No content validation before processing

Implement these security measures:

 const onBulkUploadSubmit = async (file) => {
   try {
     if (file.length > 1) {
       setShowToast({ key: "error", label: t("HCM_ERROR_MORE_THAN_ONE_FILE") });
       return;
     }
 
+    // Validate file type
+    const allowedTypes = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'];
+    if (!allowedTypes.includes(file[0]?.type)) {
+      setShowToast({ key: "error", label: t("HCM_ERROR_INVALID_FILE_TYPE") });
+      return;
+    }
+
+    // Validate file size (e.g., 5MB limit)
+    const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB in bytes
+    if (file[0]?.size > MAX_FILE_SIZE) {
+      setShowToast({ key: "error", label: t("HCM_ERROR_FILE_TOO_LARGE") });
+      return;
+    }

     setFileName(file?.[0]?.name);
     const module = "HCM-ADMIN-CONSOLE-CLIENT";

Line range hint 26-26: Optimize component performance and structure

While the component is already wrapped in React.memo, there are several opportunities for performance optimization:

  1. The component is large and handles multiple responsibilities
  2. Complex rendering logic could benefit from memoization
  3. API calls could be optimized

Consider breaking down the component into smaller, focused components:

// FileUploadSection.js
const FileUploadSection = React.memo(({ onSubmit, fileData, onDelete, onDownload }) => (
  <>
    <Button
      label={t("WBH_DOWNLOAD_TEMPLATE")}
      // ... props
    />
    <BulkUpload
      onSubmit={onSubmit}
      fileData={fileData}
      onFileDelete={onDelete}
      onFileDownload={onDownload}
    />
  </>
));

// ErrorDisplay.js
const ErrorDisplay = React.memo(({ errors, onViewError }) => (
  <InfoCard
    variant="error"
    // ... props
  />
));

// ActionButtons.js
const ActionButtons = React.memo(({ onSubmit }) => (
  <ActionBar>
    {/* ... buttons */}
  </ActionBar>
));

Also, consider memoizing expensive computations:

const memoizedFileData = useMemo(() => 
  fileUrl.map(i => ({
    filestoreId: id,
    filename: fileName,
    type: fileType,
  })), [fileUrl, fileName]);

Also applies to: 436-536

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 60951f6 and 1c968ca.

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

Pattern **/*.js: check

📓 Learnings (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UserUpload.js (1)
Learnt from: siddhant-nawale-egov
PR: egovernments/DIGIT-Frontend#204
File: micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/Upload.js:468-481
Timestamp: 2024-11-12T10:40:17.779Z
Learning: The error message in the `checkForErrorInUploadedFile` function within `Upload.js` is being localized and improved for better user experience, as clarified by the user.
🔇 Additional comments (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UserUpload.js (1)

413-413: LGTM: Improved i18n support

The change from a hardcoded string to a translation key (MP_USER_DATA_UPLOADED_WILL_BE_AVAILABLE) improves internationalization support.

const searchAndUpdatePlanConfig = async (body) => {
try {
// Make the API call
planObject.additionalDetails.key=key
Copy link
Contributor

Choose a reason for hiding this comment

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

here make a copy don't update planObject @abishekTa-egov updatedObj = {...planObject, rest}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

If it goes into this switch case, then planObject.additionalDetails.key, should be updated, as it reflects the newest planObject

Copy link
Contributor

@nipunarora-eGov nipunarora-eGov left a comment

Choose a reason for hiding this comment

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

Pls make the requested changes

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

🔭 Outside diff range comments (2)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/configs/UICustomizations.js (2)

Line range hint 829-829: Use Number.parseInt and specify radix for integer parsing

In line 829, consider using Number.parseInt instead of the global parseInt and explicitly specify the radix as 10 to ensure consistent parsing of the key.

Apply this diff to fix the code:

-                   const key = parseInt(row?.additionalDetails?.key);
+                   const key = Number.parseInt(row?.additionalDetails?.key, 10);
🧰 Tools
🪛 Biome (1.9.4)

[error] 111-111: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)


Line range hint 817-833: Add a break or return statement to prevent case fallthrough

In the case "ROLE_ACCESS_CONFIGURATION", if the response is falsy, there is no return or break after the else block, which causes execution to fall through to the next case unintentionally. To prevent unexpected behavior, add a return statement after setting the toast message.

Apply this diff to fix the issue:

              } else {
                setShowToast({ key: "error", label: "ERR_FAILED_TO_MAKE_PLAN_CALL" });
+               return {
+                 triggeredFrom,
+               };
              }
🧰 Tools
🪛 Biome (1.9.4)

[error] 111-111: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1c968ca and 0464fd3.

📒 Files selected for processing (3)
  • health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/configs/UICustomizations.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js (12 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

🪛 Biome (1.9.4)
health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js

[error] 802-802: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 803-803: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 804-804: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 812-825: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 827-839: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 829-829: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js

[error] 817-833: This case is falling through to the next case.

Add a break or return statement to the end of this case to prevent fallthrough.

(lint/suspicious/noFallthroughSwitchClause)

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/configs/UICustomizations.js

[error] 111-111: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)

🔇 Additional comments (12)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/configs/UICustomizations.js (2)

111-112: Use Number.parseInt and specify radix for integer parsing

In lines 111 and 112, consider using Number.parseInt instead of the global parseInt and explicitly specify the radix as 10 to prevent unexpected results due to different numeral systems.

🧰 Tools
🪛 Biome (1.9.4)

[error] 111-111: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)


Line range hint 202-202: Ensure 'key' addition does not overwrite existing properties

When updating additionalDetails with {...currentPlanObject.additionalDetails, key: req?.config?.key || "2"}, verify that you're not unintentionally overwriting an existing key property. If additionalDetails may already contain a key, consider checking or renaming to avoid conflicts.

🧰 Tools
🪛 Biome (1.9.4)

[error] 111-111: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js (9)

202-202: Ensure 'key' addition does not overwrite existing properties

When merging additionalDetails with {...currentPlanObject.additionalDetails, key: req?.config?.key || "2"}, confirm that this does not unintentionally overwrite an existing key property. If necessary, check for existing keys or consider using a different property name to avoid conflicts.


404-404: Ensure 'key' addition does not overwrite existing properties

When updating additionalDetails with {...fetchedPlanForBoundaryInvalidate.additionalDetails, key: key}, verify that you're not unintentionally overwriting an existing key property in additionalDetails. Consider checking for the existence of key or using a different property name to prevent data loss.


486-486: Ensure 'key' addition does not overwrite existing properties

When updating additionalDetails with {...planObject?.additionalDetails, ..., key: key}, ensure that you're not overwriting an existing key property unintentionally. Verify that this assignment is intended and won't cause issues with existing data.


523-523: Ensure 'key' addition does not overwrite existing properties

In line 523, when updating additionalDetails with {...fetchedPlanForHypothesis.additionalDetails, key: key}, confirm that this action does not overwrite an existing key property. If additionalDetails may already contain key, consider handling it appropriately to avoid conflicts.


565-565: Ensure 'key' addition does not overwrite existing properties

When updating additionalDetails with {...fetchedPlanForSubHypothesis.additionalDetails, key: key}, ensure that you're not unintentionally overwriting an existing key property. Verify that this is the desired behavior to prevent potential issues.


611-611: Ensure 'key' addition does not overwrite existing properties

In line 611, verify that adding key to additionalDetails with {...fetchedPlanForFormula.additionalDetails, key: key} does not overwrite an existing key property, unless this is intentional.


664-664: Ensure 'key' addition does not overwrite existing properties

When updating additionalDetails with {...fetchedPlanForSubFormula.additionalDetails, key: key}, confirm that you are not overwriting an existing key property unintentionally.


696-696: Ensure 'key' addition does not overwrite existing properties

In line 696, when updating additionalDetails with {...fetchedPlanForBoundary.additionalDetails, key: key}, ensure that adding key does not overwrite an existing property unintentionally.


739-739: Ensure 'key' addition does not overwrite existing properties

When updating additionalDetails with {...fetchedPlanForFacility.additionalDetails, key: key}, confirm that you are not unintentionally overwriting an existing key property.

health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js (1)

891-891: 🧹 Nitpick (assertive)

Use template literals instead of string concatenation

In line 891, consider using template literals for better readability when concatenating strings.

Apply this diff to enhance the code:

-                 return <p>{t(Digit.Utils.locale.getTransformedLocale("MICROPLAN_STATUS_" + value))}</p>;
+                 return <p>{t(Digit.Utils.locale.getTransformedLocale(`MICROPLAN_STATUS_${value}`))}</p>;

Likely invalid or redundant comment.

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
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0464fd3 and 46fe9f1.

📒 Files selected for processing (3)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/FacilityCatchmentMapping.js (1 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/PopInbox.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
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/PopInbox.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

194-195: LGTM! Null checks implemented correctly.

The code now safely handles the hierarchy level display with proper null checks using optional chaining, addressing the previous review comment's concerns.

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

839-841: LGTM! Safe property access and clean string formatting.

The code properly uses optional chaining (?.) to safely access the nested hierarchyLevel property and employs template literals for clean string concatenation. This ensures the component won't throw errors if the hierarchy level is undefined.

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

614-617: 🧹 Nitpick (assertive)

Consider improving string localization and null safety.

The current implementation can be enhanced in several ways:

  1. Move the entire format string to the translation file for better localization support
  2. Strengthen null checks using optional chaining consistently
  3. Simplify the template literal structure

Consider this refactor:

-          {`${t("LOGGED_IN_AS")} ${userName} - ${t(userRole)}${planEmployee?.planData 
-            ? ` (${t(planEmployee.planData[0].hierarchyLevel.toUpperCase())})` : ""}`
-          }
+          {t("LOGGED_IN_AS_WITH_ROLE_AND_HIERARCHY", {
+            userName,
+            userRole: t(userRole),
+            hierarchyLevel: planEmployee?.planData?.[0]?.hierarchyLevel 
+              ? t(planEmployee.planData[0].hierarchyLevel.toUpperCase())
+              : ''
+          })}

Add to translation file:

"LOGGED_IN_AS_WITH_ROLE_AND_HIERARCHY": "{{userName}} - {{userRole}}{{hierarchyLevel ? ` (${hierarchyLevel})` : ''}}"

Likely invalid or redundant comment.

Comment on lines +839 to +841
<div>{`${t("LOGGED_IN_AS")} ${userName} - ${t(userRole)}${planEmployee?.planData?.[0]?.hierarchyLevel ?
` (${t(planEmployee.planData[0].hierarchyLevel.toUpperCase())})` : ""}`}
</div>
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 extracting user role display logic into a custom hook.

The user role display logic could be moved to a custom hook (e.g., useUserRoleDisplay) to:

  • Improve reusability across components
  • Centralize the role display formatting logic
  • Make the component more maintainable

Example implementation:

const useUserRoleDisplay = (userName, userRole, planEmployee) => {
  return useMemo(() => {
    const hierarchyLevel = planEmployee?.planData?.[0]?.hierarchyLevel;
    return `${t("LOGGED_IN_AS")} ${userName} - ${t(userRole)}${
      hierarchyLevel ? ` (${t(hierarchyLevel.toUpperCase())})` : ""
    }`;
  }, [userName, userRole, planEmployee]);
};

Usage in component:

const userRoleDisplay = useUserRoleDisplay(userName, userRole, planEmployee);
return <div>{userRoleDisplay}</div>;

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
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 46fe9f1 and 2d6863a.

📒 Files selected for processing (1)
  • health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js (1)

Pattern **/*.js: check

🪛 Biome (1.9.4)
health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js

[error] 802-802: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 803-803: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 804-804: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 812-825: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 827-839: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 829-829: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)

🔇 Additional comments (9)
health/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js (9)

829-830: Use Number.parseInt with a radix
This is consistent with ES2015 recommendations and eliminates potential ambiguity.

- const key = parseInt(row?.additionalDetails?.key);
+ const key = Number.parseInt(row?.additionalDetails?.key, 10);
🧰 Tools
🪛 Biome (1.9.4)

[error] 829-829: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)


829-830: Good job addressing earlier feedback
You’ve correctly handled the case where key === 8 results in key = 7. This aligns with the prior comment from nipunarora-eGov.

🧰 Tools
🪛 Biome (1.9.4)

[error] 829-829: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)


903-903: 🧹 Nitpick (assertive)

Use template literals instead of string concatenation
Ensures clarity and reduces potential whitespace errors.

- return <p>{t(Digit.Utils.locale.getTransformedLocale("MICROPLAN_DISEASE_" + value))}</p>;
+ return <p>{t(Digit.Utils.locale.getTransformedLocale(`MICROPLAN_DISEASE_${value}`))}</p>;

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome (1.9.4)

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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


914-914: 🧹 Nitpick (assertive)

Use template literals instead of string concatenation
Enhances readability.

- return <p>{t(Digit.Utils.locale.getTransformedLocale("MICROPLAN_TYPE_" + value))}</p>;
+ return <p>{t(Digit.Utils.locale.getTransformedLocale(`MICROPLAN_TYPE_${value}`))}</p>;

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome (1.9.4)

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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


925-925: 🧹 Nitpick (assertive)

Use template literals instead of string concatenation
Aligns with modern JavaScript standards.

- return <p>{t(Digit.Utils.locale.getTransformedLocale("MICROPLAN_DISTRIBUTION_" + value))}</p>;
+ return <p>{t(Digit.Utils.locale.getTransformedLocale(`MICROPLAN_DISTRIBUTION_${value}`))}</p>;

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome (1.9.4)

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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


812-825: 🛠️ Refactor suggestion

Restrict function access to the current switch case
The function “handleDownload” is declared in lines 812-825 and can be accessed by other switch cases unintentionally. Encapsulating it in braces fixes the “noSwitchDeclarations” rule and prevents scoping issues.

Proposed fix:

          case "ACTIONS":
+           {
              const handleDownload = () => {
                // ...
              };
              // ...
+           }

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome (1.9.4)

[error] 812-825: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


892-892: 🧹 Nitpick (assertive)

Use template literals instead of string concatenation
Using a template literal here is typically safer and more readable.

- return <p>{t(Digit.Utils.locale.getTransformedLocale("MICROPLAN_STATUS_" + value))}</p>;
+ return <p>{t(Digit.Utils.locale.getTransformedLocale(`MICROPLAN_STATUS_${value}`))}</p>;

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome (1.9.4)

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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


827-839: 🛠️ Refactor suggestion

Restrict function access to the current switch case
Likewise, the “onActionSelect” function declared in lines 827-839 can leak into other switch contexts. Wrap it in an additional block to limit its scope.

          case "ACTIONS":
            {
              // ...
              const handleDownload = () => { /* ... */ };

+             const onActionSelect = (e) => {
+               // ...
+             };
              // ...
            }

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome (1.9.4)

[error] 827-839: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 829-829: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)


797-801: 🛠️ Refactor suggestion

Wrap variable declarations in a block for scoping
Variables “dummyFile”, “microplanFileId”, and “options” declared at lines 802-804 can inadvertently leak to other switch cases, which can cause subtle bugs.

Apply the following diff to wrap lines 802-804 in braces:

+          {
            const dummyFile = "c22a7676-d5d7-49b6-bcdb-83e9519f58df"
            const microplanFileId = row?.campaignDetails?.additionalDetails?.microplanFileId || dummyFile;
            let options = [];
+          }

Likely invalid or redundant comment.

Comment on lines +768 to +796
MicroplanSearchConfig: {
preProcess: (data, additionalDetails) => {
const { name, status } = data?.state?.searchForm || {};
data.body.PlanConfigurationSearchCriteria = {};
data.body.PlanConfigurationSearchCriteria.limit = data?.state?.tableForm?.limit;
// data.body.PlanConfigurationSearchCriteria.limit = 10
data.body.PlanConfigurationSearchCriteria.offset = data?.state?.tableForm?.offset;
data.body.PlanConfigurationSearchCriteria.name = name;
data.body.PlanConfigurationSearchCriteria.tenantId = Digit.ULBService.getCurrentTenantId();
data.body.PlanConfigurationSearchCriteria.userUuid = Digit.UserService.getUser().info.uuid;
// delete data.body.PlanConfigurationSearchCriteria.pagination
data.body.PlanConfigurationSearchCriteria.status = status?.status;
data.body.PlanConfigurationSearchCriteria.name = data?.state?.searchForm?.microplanName;
cleanObject(data.body.PlanConfigurationSearchCriteria);

const dic = {
0: null,
1: ["DRAFT"],
2: ["EXECUTION_TO_BE_DONE"],
3: ["CENSUS_DATA_APPROVAL_IN_PROGRESS", "CENSUS_DATA_APPROVED", "RESOURCE_ESTIMATION_IN_PROGRESS"],
4: ["RESOURCE_ESTIMATIONS_APPROVED"],
};
const url = Digit.Hooks.useQueryParams();

const tabId = url.tabId || "0"; // Default to '0' if tabId is undefined
data.body.PlanConfigurationSearchCriteria.status = dic[String(tabId)];
cleanObject(data.body.PlanConfigurationSearchCriteria);
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)

Ensure consistent naming or removal of unused variables
The “preProcess” function references both “name, status” (line 770) and “microplanName” (line 780) for the same property. Make sure “microplanName” is consistently referenced or that unused variables are removed to avoid confusion and reduce complexity.

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