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

cleanup and roles from mdms v2 #1634

Merged
merged 8 commits into from
Oct 23, 2024
Merged

cleanup and roles from mdms v2 #1634

merged 8 commits into from
Oct 23, 2024

Conversation

suryansh-egov
Copy link
Contributor

@suryansh-egov suryansh-egov commented Oct 23, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced state management in the CreateQuestionContext component for better handling of question data.
    • Introduced a new MobileChecklist component for improved checklist preview in the UpdateChecklist component.
  • Improvements

    • Streamlined API request structures and state management across several components, including SearchChecklist and ViewChecklist.
    • Improved layout and readability in the CreateQuestion component.
    • Enhanced functionality related to service definition updates in the UICustomizations configuration.
    • Updated submission handling in the UpdateChecklist component for clearer distinction between submission types.
  • Bug Fixes

    • Refined error handling and submission logic in the UpdateChecklist component.
  • Chores

    • Removed unnecessary commented code and improved overall code clarity across multiple components.

@suryansh-egov suryansh-egov requested a review from a team as a code owner October 23, 2024 07:41
Copy link
Contributor

coderabbitai bot commented Oct 23, 2024

Caution

Review failed

The pull request is closed.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several modifications across multiple components in the campaign manager module. Key changes include restructuring the JSX layout of the CreateQuestion component for improved readability, enhancements to the state management logic in CreateQuestionContext, updates to the UICustomizations to accommodate a new parameter, and adjustments to API request structures in various components. Additionally, several components have been cleaned up by removing commented-out code and redundant state variables, streamlining their functionality and improving code clarity.

Changes

File Path Change Summary
.../CreateQuestion.js Restructured JSX layout, added wrapping div for Card, reformatted initialQuestionData, minor spacing adjustments.
.../CreateQuestionContext.js Added CLEAR_DATA action, simplified DELETE_QUESTION logic, updated useEffect for prop changes.
.../UICustomizations.js Updated updateServiceDefinition method to accept sdcode, modified additionalCustomizations logic.
.../checklistSearchConfig.js Updated schemaCode in apiDetails from "HCM-ADMIN-CONSOLE.ChecklistTemplates_DEMO" to "HCM-ADMIN-CONSOLE.Checklist_Templates".
.../CreateChecklist.js Removed commented-out localization code, updated schema code for fetching templates, modified clearData and onSubmit logic.
.../SearchChecklist.js Updated API request structure, modified state management for codesopt, removed redundant code, added loading state check.
.../UpdateChecklist.js Added MobileChecklist component, refined onSubmit logic, adjusted spacing with a new div.
.../ViewChecklist.js Introduced new serviceCode variable, streamlined state management, updated API request structure, removed unnecessary variables.

Possibly related PRs

  • cleanup and roles from mdms v2 #1634: The changes in the CreateQuestion and CreateQuestionContext components are directly related to the main PR's modifications in the CreateQuestion.js file, as both involve restructuring and enhancing the functionality of the question management components.

Suggested reviewers

  • nipunarora-eGov

🐇 In the code we hop and play,
Restructured bits to brighten the day.
With every change, our paths align,
A cleaner code, oh how divine!
Let's leap ahead, with joy we cheer,
For better code is finally here! 🌟


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.

@@ -453,8 +453,6 @@ const UpdateChecklist = () => {
]}
sortFooterChildren={true}
Copy link
Collaborator

Choose a reason for hiding this comment

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

can you make the same implementation in update checklist flow as well


const [listsopt, setListsOpt] = useState([]);
const reqCriteria = {
url: `/mdms-v2/v2/_search`,
Copy link
Collaborator

Choose a reason for hiding this comment

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

also get this url from global config

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

🧹 Outside diff range comments (7)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/checklistSearchConfig.js (1)

Line range hint 1-120: Consider refactoring configuration for better maintainability.

Several improvements could make the configuration more maintainable:

  1. Extract translation prefixes to constants
  2. Remove commented code in the searchResult columns
  3. Consider moving hardcoded values like pagination limits to constants

Example refactor:

const TRANSLATION_PREFIXES = {
  ROLE: "ACCESSCONTROL_ROLES_ROLES_",
  CHECKLIST_TYPE: "HCM_CHECKLIST_TYPE_"
};

const PAGINATION_DEFAULTS = {
  offset: 0,
  limit: 5
};

export const checklistSearchConfig = [
  {
    // ... rest of the config
    apiDetails: {
      // ... other details
      Pagination: PAGINATION_DEFAULTS,
    },
    sections: {
      searchResult: {
        uiConfig: {
          columns: [
            {
              label: "CHECKLIST_ROLE",
              prefix: TRANSLATION_PREFIXES.ROLE,
              jsonPath: "data.role",
              translate: true
            },
            {
              label: "CHECKLIST_TYPE",
              prefix: TRANSLATION_PREFIXES.CHECKLIST_TYPE,
              jsonPath: "data.checklistType",
              translate: true
            },
            // ... other columns
          ]
        }
      }
    }
  }
];
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CreateQuestionContext.js (1)

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

  1. Add error handling for localStorage operations:
const saveToStorage = (data) => {
  try {
    localStorage.setItem("questions", JSON.stringify(data));
  } catch (error) {
    console.error("Failed to save questions:", error);
    // Consider implementing a fallback or user notification
  }
};
  1. Consider implementing an error boundary to gracefully handle runtime errors.

  2. The component could benefit from being split into smaller, more focused components to reduce complexity and prop drilling.

Would you like assistance in implementing any of these architectural improvements?

🧰 Tools
🪛 Biome

[error] 42-45: 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] 46-51: 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)

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

Line range hint 12-24: Consider separating concerns for better maintainability

The component currently handles multiple responsibilities including:

  • UI state management
  • API interactions
  • Error handling
  • Localization

Consider:

  1. Moving API calls to a separate service layer
  2. Creating a custom hook for state management
  3. Implementing a dedicated error handling utility

This would improve maintainability and testability of the code.

Also applies to: 371-417

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

Line range hint 63-82: Add proper error handling in useEffect.

The error handling in the data fetching useEffect is empty. This could lead to silent failures and poor user experience.

             }
             catch (error) {
+                setSearching(false);
+                setShowToast({ 
+                    label: "ERROR_FETCHING_CHECKLIST_DATA",
+                    isError: true 
+                });
+                console.error("Error fetching checklist data:", error);
             }
🧰 Tools
🪛 Biome

[error] 475-475: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)


Line range hint 42-48: Prevent memory leak in Toast timeout.

The timeout for hiding the toast should be cleaned up when the component unmounts or when showToast changes.

     useEffect(() => {
         if (showToast) {
-            setTimeout(closeToast, 5000);
+            const timer = setTimeout(closeToast, 5000);
+            return () => clearTimeout(timer);
         }
     }, [showToast]);
🧰 Tools
🪛 Biome

[error] 475-475: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)


Line range hint 10-31: Consider using reducer for complex state management.

The component uses multiple useState hooks which could make state updates harder to track and maintain. Consider using useReducer for better state management.

Would you like me to help refactor the state management using useReducer?

🧰 Tools
🪛 Biome

[error] 475-475: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)

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

Line range hint 19-37: Improve error handling in updateServiceDefinition.

The error handling could be enhanced to provide better debugging capabilities and error reporting.

Consider this improvement:

 const updateServiceDefinition = async (tenantId, newStatus, sdcode) => {
   try {
     const res = await Digit.CustomService.getResponse({
       url: "/service-request/service/definition/v1/_update",
       body: {
         ServiceDefinition: {
           "tenantId": tenantId,
           "code": sdcode,
           "isActive": newStatus
         },
       },
     });
-    if (res) {
-    }
     return res;
   } catch (error) {
-    // console.error("Error updating service definition:", error);
+    console.error("Error updating service definition:", error);
+    throw new Error(`Failed to update service definition: ${error.message}`);
     return null;
   }
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 6c9afaf and b96ed50.

📒 Files selected for processing (8)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CreateQuestion.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CreateQuestionContext.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/checklistSearchConfig.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CreateChecklist.js (5 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SearchChecklist.js (4 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/UpdateChecklist.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/ViewChecklist.js (5 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CreateQuestion.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

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


[error] 378-378: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)


[error] 379-393: Enforce to have the onClick mouse event with the onKeyUp, the onKeyDown, or the onKeyPress keyboard event.

Actions triggered using mouse events should have corresponding keyboard events to account for keyboard-only navigation.

(lint/a11y/useKeyWithClickEvents)


[error] 499-499: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)


[error] 503-503: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)


[error] 344-344: This let declares a variable that is only assigned once.

'dis' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 351-351: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CreateQuestionContext.js

[error] 42-45: 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] 46-51: 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)

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

[error] 76-84: 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] 95-95: 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] 96-96: 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] 97-97: 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)

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

[error] 520-520: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)


[error] 540-540: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)

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

[error] 55-55: This let declares a variable that is only assigned once.

'data' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

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

[error] 475-475: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)

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

[error] 40-40: This let declares a variable that is only assigned once.

'temp_data' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 41-41: This let declares a variable that is only assigned once.

'formatted_data' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 42-42: This let declares a variable that is only assigned once.

'nvd' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 212-212: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)

🔇 Additional comments (10)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/checklistSearchConfig.js (1)

16-16: LGTM! Schema code update looks good.

The schema code update to "HCM-ADMIN-CONSOLE.Checklist_Templates" follows proper naming conventions and aligns with MDMS v2 migration.

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

142-142: LGTM: Consistent isActive flag implementation

The addition of isActive flag in the question template maintains consistency with the payload structure.


153-153: Verify checklistCreateConfig handles "clear" parameter

A new "clear" parameter has been added to checklistCreateConfig. Ensure this parameter is properly handled.

Let's check the implementation:

#!/bin/bash
# Search for checklistCreateConfig implementation
ast-grep --pattern 'function checklistCreateConfig($_, $_, $_) {
  $$$
}'

74-74: Verify schema code update impact

The schema code has been updated from a demo version to what appears to be a production version. This change could affect existing data retrieval.

Let's verify if there are any other files still using the old schema code:

✅ Verification successful

Let me try a broader search to better understand the schema usage patterns in the codebase.

This will help us understand:

  1. The usage pattern of HCM-ADMIN-CONSOLE schemas
  2. Any other checklist template schema variations that might exist
  3. The context around these schema usages

Based on the search results, I can now provide a final response:

Schema code update is consistent across the codebase

The schema code HCM-ADMIN-CONSOLE.Checklist_Templates is consistently used in both the CreateChecklist.js and checklistSearchConfig.js files. There are no remaining references to the old demo schema code (ChecklistTemplates_DEMO2), and the new schema code follows the same pattern as other HCM-ADMIN-CONSOLE schemas used throughout the codebase (as seen in the multiple examples of other schema usages like hierarchyConfig, adminSchema, etc.).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to the old schema code
rg "ChecklistTemplates_DEMO2"

Length of output: 75


Script:

#!/bin/bash
# Search for similar schema patterns in the codebase
rg "HCM-ADMIN-CONSOLE" -A 2 -B 2

# Also search for Checklist related schema patterns
rg "Checklist_Templates|ChecklistTemplates" -A 2 -B 2

Length of output: 41760

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

Line range hint 271-339: Add error boundary for data transformation.

The data transformation logic in transformQuestions is complex and could fail silently. Consider adding error handling and validation.

🧰 Tools
🪛 Biome

[error] 475-475: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)

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

107-107: Verify mutation of 'checklistSearchConfig' object

Assigning additionalDetails to checklistSearchConfig[0] mutates the configuration object. If checklistSearchConfig is imported from a shared or constant configuration, mutating it might lead to unintended side effects in other parts of the application.

Ensure that mutating checklistSearchConfig here is intentional and does not affect other components that rely on this configuration.


213-213: LGTM

The Stepper component is correctly configured with the appropriate props and should function as expected.

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

21-21: LGTM!

The introduction of serviceCode variable is correct and aligns with the codebase conventions.


129-131: Display Loader while data is loading

The loading state is appropriately handled by displaying the <Loader /> component when isLoading is true.


214-220: Verify form submission handling before navigation

In the onSubmit handler of FormComposerV2, the form redirects to the update checklist page without handling or saving the form data. Please ensure that any user input is properly processed or validated before navigation to prevent potential loss of data.

Comment on lines 15 to 18
// schemaCode: "HCMadminconsole.checklisttemplates"
schemaCode: "HCM-ADMIN-CONSOLE.ChecklistTemplates_DEMO",
schemaCode: "HCM-ADMIN-CONSOLE.Checklist_Templates",
filters : {}
}
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)

Remove commented out schema code.

Clean up the old commented schema code to improve code readability.

-            // schemaCode: "HCMadminconsole.checklisttemplates"
             schemaCode: "HCM-ADMIN-CONSOLE.Checklist_Templates",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// schemaCode: "HCMadminconsole.checklisttemplates"
schemaCode: "HCM-ADMIN-CONSOLE.ChecklistTemplates_DEMO",
schemaCode: "HCM-ADMIN-CONSOLE.Checklist_Templates",
filters : {}
}
schemaCode: "HCM-ADMIN-CONSOLE.Checklist_Templates",
filters : {}
}

Comment on lines +41 to +53
case "CLEAR_DATA":
const newState = state.map(item => {
// Set isActive to false for all previous items
return { ...item, isActive: false };
});
const updatedState = [
...newState,
{
...action.payload[0],
}
];
return updatedState;

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Add block scoping and payload validation to the CLEAR_DATA case.

The current implementation has potential issues:

  1. Switch case declarations need block scoping
  2. Missing payload validation

Apply this fix:

 case "CLEAR_DATA": {
+  if (!action.payload?.[0]) {
+    return state;
+  }
   const newState = state.map(item => ({
     ...item,
     isActive: false
   }));
   return [
     ...newState,
     { ...action.payload[0] }
   ];
 }

Consider filtering out inactive items to improve memory efficiency:

 case "CLEAR_DATA": {
   if (!action.payload?.[0]) {
     return state;
   }
-  const newState = state.map(item => ({
-    ...item,
-    isActive: false
-  }));
+  const newState = state
+    .filter(item => item.isActive)
+    .map(item => ({
+      ...item,
+      isActive: false
+    }));
   return [
     ...newState,
     { ...action.payload[0] }
   ];
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
case "CLEAR_DATA":
const newState = state.map(item => {
// Set isActive to false for all previous items
return { ...item, isActive: false };
});
const updatedState = [
...newState,
{
...action.payload[0],
}
];
return updatedState;
case "CLEAR_DATA": {
if (!action.payload?.[0]) {
return state;
}
const newState = state
.filter(item => item.isActive)
.map(item => ({
...item,
isActive: false
}));
return [
...newState,
{ ...action.payload[0] }
];
}
🧰 Tools
🪛 Biome

[error] 42-45: 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] 46-51: 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)

Comment on lines +168 to +183
if(props?.props?.typeOfCall === "clear")
{
dispatchQuestionData({
type: "CLEAR_DATA",
payload: props?.props?.data
})

}
else{
dispatchQuestionData({
type: "UPDATE_QUESTION_DATA",
payload: props?.props?.data,
});

}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve useEffect robustness and clarity.

The current implementation has several potential issues:

  1. The condition props?.props?.data !== 0 is unclear and could be improved
  2. Deep prop access without proper null checks
  3. Missing cleanup function

Apply these improvements:

 useEffect(() => {
-  if (props?.props?.data !== 0) {
+  // Ensure we have valid data to process
+  if (!props?.props) {
+    return;
+  }
+
+  const { data, typeOfCall } = props.props;
+  if (!data) {
+    return;
+  }
+
   setTypeOfCall(props?.props?.typeOfCall);
-  if(props?.props?.typeOfCall === "clear") {
+  if(typeOfCall === "clear") {
     dispatchQuestionData({
       type: "CLEAR_DATA",
-      payload: props?.props?.data
+      payload: data
     });
   } else {
     dispatchQuestionData({
       type: "UPDATE_QUESTION_DATA",
-      payload: props?.props?.data,
+      payload: data,
     });
   }
-  }
+
+  // Cleanup function
+  return () => {
+    setTypeOfCall(null);
+  };
 }, [props?.props?.data]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(props?.props?.typeOfCall === "clear")
{
dispatchQuestionData({
type: "CLEAR_DATA",
payload: props?.props?.data
})
}
else{
dispatchQuestionData({
type: "UPDATE_QUESTION_DATA",
payload: props?.props?.data,
});
}
// Ensure we have valid data to process
if (!props?.props) {
return;
}
const { data, typeOfCall } = props.props;
if (!data) {
return;
}
setTypeOfCall(props?.props?.typeOfCall);
if(typeOfCall === "clear") {
dispatchQuestionData({
type: "CLEAR_DATA",
payload: data
});
} else {
dispatchQuestionData({
type: "UPDATE_QUESTION_DATA",
payload: data,
});
}
// Cleanup function
return () => {
setTypeOfCall(null);
};

Comment on lines +403 to 410
{/* <TextInput
// style={{ maxWidth: "40rem" }}
name="title"
value={field?.title || ""}
onChange={(event) => handleUpdateField(event.target.value, "title", field.key, field.id)}
placeholder={"Type your questions here"}
className={"example"}
/> */}
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)

Clean up commented code and extract inline styles

Remove commented code and move inline styles to CSS for better maintainability.

  1. Remove commented TextInput component (lines 403-410)
  2. Extract inline styles:
-<div className="question-field" style={{ display: "flex", height: "3.5rem", gap: "1.5rem" }}>
+<div className="question-field question-field--layout">

Add to CSS:

.question-field--layout {
  display: flex;
  height: 3.5rem;
  gap: 1.5rem;
}

Also applies to: 411-432

Comment on lines +434 to +481
{field?.isRegex && (
<Dropdown
style={{ width: "70%" }}
t={t}
option={regexOption}
optionKey={"code"}
selected={field?.regex || ""}
select={(value) => {
handleUpdateField(value, "regex", field.key, field.id);
}}
props={{ fieldStyle: example }}
name="Short Answer"
value={field.value || ""}
onChange={(event) => handleUpdateField(event.target.value, "value", field.key, field.id)}
placeholder={""}
placeholder="Choose Regex"
/>
)
}
{!dis && field.dependency && (
<CreateQuestion
onSelect={onSelect}
className="subSection"
level={level + 1}
parent={field}
parentId={field.id}
initialQuestionData={initialQuestionData} // Pass sub-questions data to nested component
>
</CreateQuestion>
)}
)}
{(field?.type?.code === "SingleValueList" || field?.type?.code === "MultiValueList" || field?.type?.code === "Dropdown") && (
<FieldSelector
t={t}
type={field?.type}
name={"value"}
value={field?.value || ""}
onChange={(event) => handleUpdateField(event.target.value, "value", field?.key, field.id)}
placeholder={"Answer"}
dispatchQuestionData={dispatchQuestionData}
field={field}
subQclassName="subSection"
subQlevel={level + 1}
subQparent={field}
subQparentId={field.id}
subQinitialQuestionData={initialQuestionData}
typeOfCall={typeOfCall}
/>
)}
{
(field?.type?.code === "Short Answer") && (
<FieldV1
disabled="true"
className="example"
type={"textarea"}
populators={{
resizeSmart: true
}}
props={{ fieldStyle: example }}
name="Short Answer"
value={field.value || ""}
onChange={(event) => handleUpdateField(event.target.value, "value", field.key, field.id)}
placeholder={""}
/>
)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Extract regex and field selector logic into separate components

Consider extracting the regex dropdown and field selector logic into separate components to improve maintainability and reusability.

Create new components:

  1. RegexSelector.js for the regex dropdown
  2. AnswerField.js for the short answer field
    This will make the code more modular and easier to test.

Comment on lines +19 to 21
useEffect(() => {
setCampaignName(campaignName);
}, campaignName);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unnecessary useEffect hook or correct its dependency array

The useEffect hook is setting campaignName to its current value and may be unnecessary. Additionally, the dependency array should be an array, but currently, campaignName is passed directly.

Consider removing the useEffect hook if it's not needed, or adjust the dependency array to be an array.

Proposed fix:

-useEffect(() => {
-  setCampaignName(campaignName);
-}, campaignName);
+// Remove this useEffect if it's not needed
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
setCampaignName(campaignName);
}, campaignName);

// <div>
// <CardText style={{ margin: 0 }}>{"testing" + " "}</CardText>
// </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)

Remove unnecessary empty 'children' prop

The children prop in the PopUp component is passed an empty array, which is unnecessary. Omitting the children prop simplifies the code without affecting functionality.

Apply this diff to fix the issue:

<PopUp
    className={"custom-pop-up"}
    type={"default"}
    heading={t("CHECKLIST_PREVIEW")}
-   children={[
-
-   ]}
    onOverlayClick={() => {
        setShowPopUp(false);
    }}
    onClose={() => {
        setShowPopUp(false);
    }}
    footerChildren={[ /* ... */ ]}
    sortFooterChildren={true}
>

Committable suggestion was skipped due to low confidence.

…gn-manager/src/pages/employee/ViewChecklist.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
jagankumar-egov and others added 2 commits October 23, 2024 14:21
…gn-manager/src/pages/employee/SearchChecklist.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
…gn-manager/src/pages/employee/ViewChecklist.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@jagankumar-egov jagankumar-egov merged commit 3b1a466 into console Oct 23, 2024
1 of 3 checks passed
@jagankumar-egov jagankumar-egov deleted the feature/cl-final branch October 23, 2024 08:51
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 (4)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/checklistSearchConfig.js (1)

Line range hint 46-47: Clean up commented code blocks throughout the file.

There are several instances of commented-out code that should be removed to improve code maintainability and readability:

  • Commented options in dropdown configs
  • Commented columns configuration
  • Commented tenantId

Would you like me to provide a diff showing all the cleanup changes?

Also applies to: 54-55, 66-71, 76-77

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

Line range hint 27-29: 'module' variable is used before it's assigned

The module variable is used in the call to useUpsertLocalisation before it is assigned a value. This can lead to module being undefined during the function call.

Apply this diff to assign module before its usage:

+        const module = "hcm-checklist";
         const { mutateAsync: localisationMutateAsync } = Digit.Hooks.campaign.useUpsertLocalisation(tenantId, module, locale);
-        module = "hcm-checklist";
🧰 Tools
🪛 Biome

[error] 27-27: This let declares a variable that is only assigned once.

'locale' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


Line range hint 200-216: Duplicate createQuestionObject function declarations

There are two functions named createQuestionObject defined in the code. This can cause conflicts or unexpected behaviors. Consider removing or renaming one of them to avoid confusion and potential errors.

🧰 Tools
🪛 Biome

[error] 27-27: This let declares a variable that is only assigned once.

'locale' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


Line range hint 339-341: Replace placeholder condition with actual success check

In the onSubmit function, the condition if (data.success) includes a comment indicating it needs replacement. Ensure you use the correct condition to check if the API call was successful, based on the actual structure of the response from mutateAsync.

🧰 Tools
🪛 Biome

[error] 27-27: This let declares a variable that is only assigned once.

'locale' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between b96ed50 and 910d68a.

📒 Files selected for processing (5)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/checklistSearchConfig.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/services/createTypeOfChecklist.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CreateChecklist.js (5 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SearchChecklist.js (4 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/UpdateChecklist.js (4 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/checklistSearchConfig.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

[error] 523-523: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)


[error] 543-543: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)

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

[error] 56-56: This let declares a variable that is only assigned once.

'data' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 78-78: This let declares a variable that is only assigned once.

'data' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

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

[error] 72-72: This let declares a variable that is only assigned once.

'temp_data' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 73-73: This let declares a variable that is only assigned once.

'formatted_data' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 74-74: This let declares a variable that is only assigned once.

'nvd' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 459-459: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)

🔇 Additional comments (7)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/checklistSearchConfig.js (4)

3-3: LGTM! Well-implemented configuration handling.

The implementation correctly retrieves the MDMS V2 context path from global configs with a proper fallback value, using safe optional chaining.


9-9: LGTM! Good use of configuration-driven endpoint.

The service name is now properly derived from the configured MDMS context path, making it more maintainable.


17-17: LGTM! Schema code update is correct.

The updated schema code aligns with the expected format for HCM admin console checklist templates.


3-3: Verify MDMS v2 migration impact.

The changes indicate a migration from MDMS v1 to v2. Let's verify that all related components are consistently updated.

Also applies to: 9-9, 17-17

✅ Verification successful

Let me analyze the results and generate a final response based on the verification performed.

MDMS v2 migration appears consistent in the codebase

The verification results show:

  • No instances of old MDMS v1 endpoints (/mdms/v1/_search) were found
  • The MDMS_V2_CONTEXT_PATH configuration is consistently used across relevant files:
    • In campaign-manager module's configuration and pages
    • In the core libraries (urls.js)
  • The fallback value "mdms-v2" is consistently set across all usages

The changes are properly aligned with the MDMS v2 migration, and no inconsistencies were detected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining MDMS v1 endpoints or inconsistent schema codes

# Test 1: Search for old MDMS v1 endpoints
echo "Checking for MDMS v1 endpoints..."
rg -l '/mdms/v1/_search'

# Test 2: Check for inconsistent schema codes
echo "Checking for inconsistent schema codes..."
rg -l 'HCMadminconsole\.checklisttemplates'

# Test 3: Verify consistent usage of MDMS_V2_CONTEXT_PATH config
echo "Checking MDMS_V2_CONTEXT_PATH usage..."
rg 'MDMS_V2_CONTEXT_PATH'

Length of output: 1478

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

145-145: LGTM: Form data handling improvements

The addition of isActive flag and clear parameter enhances the form reset functionality.

Also applies to: 156-156


523-523: Self-closing div elements issue

This issue has been previously identified in past reviews.

Also applies to: 543-543

🧰 Tools
🪛 Biome

[error] 523-523: JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing.

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)


63-77: Verify schema code update across the codebase

The schema code has been updated from demo to production. Let's verify this change is consistent across the codebase.

✅ Verification successful

Based on the search results, I can now generate the final response:

Schema code update is consistent across the codebase

The schema code HCM-ADMIN-CONSOLE.Checklist_Templates is consistently used in both relevant files:

  • CreateChecklist.js: For creating new checklists
  • checklistSearchConfig.js: For search configuration

No instances of the old schema code ChecklistTemplates_DEMO2 were found, confirming a complete migration to the new schema.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to the old schema code
rg "ChecklistTemplates_DEMO2"

# Search for all occurrences of the new schema code to ensure consistency
rg "Checklist_Templates"

Length of output: 405

@@ -1,7 +1,9 @@
const createTypeOfChecklist = async (req, tenantId) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unused tenantId parameter.

The function accepts a tenantId parameter but never uses it. Either remove the unused parameter or document why it's needed for future use.

-const createTypeOfChecklist = async (req, tenantId) => {
+const createTypeOfChecklist = async (req) => {

Committable suggestion was skipped due to low confidence.

@@ -1,7 +1,9 @@
const createTypeOfChecklist = async (req, tenantId) => {
const mdms_context_path = window?.globalConfigs?.getConfig("MDMS_V2_CONTEXT_PATH") || "mdms-v2";
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider moving configuration retrieval outside the function.

The MDMS context path configuration is retrieved on every function call. Consider moving this to a module-level constant or a configuration hook for better performance and reusability.

+const MDMS_CONTEXT_PATH = window?.globalConfigs?.getConfig("MDMS_V2_CONTEXT_PATH") || "mdms-v2";
+
 const createTypeOfChecklist = async (req, tenantId) => {
-  const mdms_context_path = window?.globalConfigs?.getConfig("MDMS_V2_CONTEXT_PATH") || "mdms-v2";
-
   try {
     const response = await Digit.CustomService.getResponse({
-      url: `/${mdms_context_path}/v1/_search`,
+      url: `/${MDMS_CONTEXT_PATH}/v1/_search`,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const mdms_context_path = window?.globalConfigs?.getConfig("MDMS_V2_CONTEXT_PATH") || "mdms-v2";
const MDMS_CONTEXT_PATH = window?.globalConfigs?.getConfig("MDMS_V2_CONTEXT_PATH") || "mdms-v2";
const mdms_context_path = window?.globalConfigs?.getConfig("MDMS_V2_CONTEXT_PATH") || "mdms-v2";

try {
const response = await Digit.CustomService.getResponse({
url: "/mdms-v2/v1/_search",
url: `/${mdms_context_path}/v1/_search`,
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validate MDMS context path to prevent path injection.

The URL is constructed using a configurable value without validation. This could potentially lead to path injection if the configuration is compromised.

Add validation for the context path:

+const validateContextPath = (path) => {
+  return /^[a-zA-Z0-9-]+$/.test(path) ? path : "mdms-v2";
+};
+
 const createTypeOfChecklist = async (req, tenantId) => {
-  const mdms_context_path = window?.globalConfigs?.getConfig("MDMS_V2_CONTEXT_PATH") || "mdms-v2";
+  const mdms_context_path = validateContextPath(window?.globalConfigs?.getConfig("MDMS_V2_CONTEXT_PATH"));

Committable suggestion was skipped due to low confidence.

Comment on lines +91 to +93
// useEffect(() => {
// setListsOpt(HCM?.HCM?.CHECKLIST_TYPES?.map((item) => ({ list: `HCM_CHECKLIST_TYPE_${item.code}` })));
// }, [HCM]);
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Remove commented-out code if it's no longer needed

The code in lines 91-93 is commented out and may not be necessary. Removing unused code enhances maintainability and reduces clutter.

const { isLoading, data: HCM, isFetching } = Digit.Hooks.useCustomAPIHook(reqCriteriaResource);
const { isLoading, data: HCM, isFetching } = Digit.Hooks.useCustomAPIHook(reqCriteria1);
useEffect(() => {
let data = HCM?.mdms;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use 'const' instead of 'let' for 'data' variable

The variable data is assigned once and never reassigned. Using const improves code readability and indicates that the variable will not change.

Apply this diff to fix the issue:

-let data = HCM?.mdms;
+const data = HCM?.mdms;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let data = HCM?.mdms;
const data = HCM?.mdms;
🧰 Tools
🪛 Biome

[error] 78-78: This let declares a variable that is only assigned once.

'data' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

return (
<div>
{submitting && <Loader />}
{/* {submitting && <Loader />} */}
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)

Remove unnecessary commented-out code

It's advisable to remove commented-out code to keep the codebase clean and maintainable.

Comment on lines +70 to +77
select: (res) => {
if (res?.ServiceDefinitions?.[0]?.attributes) {
setSearching(false);
let temp_data = res?.ServiceDefinitions?.[0]?.attributes
let formatted_data = temp_data.map((item) => item.additionalDetails);
let nvd = formatted_data.filter((value, index, self) =>
index === self.findIndex((t) => t.id === value.id)
);
setViewData(nvd);
// setViewData(formatted_data);

);
return nvd;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use 'const' instead of 'let' for variables that are not reassigned

Variables temp_data, formatted_data, and nvd are declared with let but are never reassigned. Using const for variables that are not reassigned helps prevent accidental reassignments and improves code readability.

Apply this diff to change let to const:

             select: (res) => {
                 if (res?.ServiceDefinitions?.[0]?.attributes) {
-                    let temp_data = res?.ServiceDefinitions?.[0]?.attributes
-                    let formatted_data = temp_data.map((item) => item.additionalDetails);
-                    let nvd = formatted_data.filter((value, index, self) =>
+                    const temp_data = res?.ServiceDefinitions?.[0]?.attributes
+                    const formatted_data = temp_data.map((item) => item.additionalDetails);
+                    const nvd = formatted_data.filter((value, index, self) =>
                         index === self.findIndex((t) => t.id === value.id)
                     );
                     return nvd;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
select: (res) => {
if (res?.ServiceDefinitions?.[0]?.attributes) {
setSearching(false);
let temp_data = res?.ServiceDefinitions?.[0]?.attributes
let formatted_data = temp_data.map((item) => item.additionalDetails);
let nvd = formatted_data.filter((value, index, self) =>
index === self.findIndex((t) => t.id === value.id)
);
setViewData(nvd);
// setViewData(formatted_data);
);
return nvd;
select: (res) => {
if (res?.ServiceDefinitions?.[0]?.attributes) {
const temp_data = res?.ServiceDefinitions?.[0]?.attributes
const formatted_data = temp_data.map((item) => item.additionalDetails);
const nvd = formatted_data.filter((value, index, self) =>
index === self.findIndex((t) => t.id === value.id)
);
return nvd;
🧰 Tools
🪛 Biome

[error] 72-72: This let declares a variable that is only assigned once.

'temp_data' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 73-73: This let declares a variable that is only assigned once.

'formatted_data' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 74-74: This let declares a variable that is only assigned once.

'nvd' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

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