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

not selected added in single value list #1824

Merged
merged 3 commits into from
Nov 13, 2024
Merged

Conversation

suryansh-egov
Copy link
Collaborator

@suryansh-egov suryansh-egov commented Nov 13, 2024

Choose the appropriate template for your PR:

Summary by CodeRabbit

  • New Features

    • Enhanced handling for "SingleValueList" question types in checklist creation and updating, including default value management.
    • Improved error handling with toast notifications for checklist submission failures, providing user feedback.
    • Standardized data structure for checklist payloads, particularly for "Short Answer" questions, ensuring consistency.
    • Updated search functionality to only retrieve active checklist templates and entries.
    • Added functionality to manage question options, ensuring only active options are displayed.
  • Bug Fixes

    • Refined logic for generating question codes, ensuring all questions are accounted for regardless of their active status.
  • Improvements

    • Overall robustness of the checklist creation and updating processes has been increased, enhancing user experience and data handling.

@suryansh-egov suryansh-egov requested a review from a team as a code owner November 13, 2024 12:56
Copy link
Contributor

coderabbitai bot commented Nov 13, 2024

Caution

Review failed

The pull request is closed.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes involve modifications to the CreateChecklist, UpdateChecklist, CreateQuestion, checklistSearchConfig, and SearchChecklist components within their respective JavaScript files. Enhancements include the addition of conditional checks for handling specific question types, improved error handling during submission processes, and adjustments to payload data structures. The onSubmit function in both CreateChecklist and UpdateChecklist now utilizes mutateAsync for better asynchronous operation management. Additionally, the useEffect hooks have been updated to manage user feedback more effectively through toast notifications, and the search configuration now filters for active entries.

Changes

File Change Summary
.../CreateChecklist.js - Updated createQuestionObject to handle "SingleValueList".
- Enhanced onSubmit with mutateAsync and improved error handling.
- Modified payloadData for "Short Answer" type.
.../UpdateChecklist.js - Added conditional check in createQuestionObject for "SingleValueList".
- Improved error handling in onSubmit with toast notifications.
- Adjusted generateCodes to process all questions.
.../CreateQuestion.js - Added isActive: true to reqCriteria for fetching active field types.
- Enhanced option management functions in FieldSelector.
.../checklistSearchConfig.js - Added isActive: true in MdmsCriteria to filter for active checklist templates.
.../SearchChecklist.js - Updated request criteria to include isActive: true for fetching active roles and checklist types.

Possibly related PRs

  • checklist-bugs-fixes #1513: The changes in the CreateChecklist component are related to the updates made in the UpdateChecklist component, particularly in how both components handle the createQuestionObject and payloadData functions, which now utilize additionalFields instead of additionalDetails.
  • error toast and checklist updates #1805: This PR also modifies the CreateChecklist component, specifically updating the createQuestionObject and payloadData functions to reflect the renaming of additionalDetails to additionalFields, aligning with the changes made in the main PR.
  • toast and minor ui #1809: The changes in this PR focus on UI elements and toast notifications, which are relevant to the user feedback mechanisms enhanced in the main PR's onSubmit function, where error handling and user notifications are improved.

Suggested reviewers

  • jagankumar-egov

🐇 In the garden where bunnies play,
New checklists bloom, brightening the day.
With toasts of joy for tasks we create,
Single values now have a lovely fate!
So hop along, let’s celebrate,
For every change, we appreciate! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range comments (4)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CreateChecklist.js (2)

Line range hint 590-614: Enhance error handling in onSubmit function

The current error handling could be improved to provide more specific feedback and better error tracking.

Consider applying this enhancement:

   try {
     const data = await mutateAsync(payload);
-    // Handle successful checklist creation  
     if (data.success) {
       const localisations = uniqueLocal;
       const localisationResult = await localisationMutateAsync(localisations);
       if (!localisationResult.success) {
         setShowToast({ label: "CHECKLIST_CREATED_LOCALISATION_ERROR", isError: "true" });
+        console.error("Localization failed:", localisationResult.error);
         return;
       }
       history.push(`/${window.contextPath}/employee/campaign/response?isSuccess=${true}`, {
         message: "ES_CHECKLIST_CREATE_SUCCESS_RESPONSE",
         preText: "ES_CHECKLIST_CREATE_SUCCESS_RESPONSE_PRE_TEXT",
         actionLabel: "CS_CHECKLIST_NEW_RESPONSE_ACTION",
         actionLink: `/${window.contextPath}/employee/campaign/checklist/search?name=${projectName}&campaignId=${campaignId}&projectType=${projectType}`,
         secondaryActionLabel: "MY_CAMPAIGN",
         secondaryActionLink: `/${window?.contextPath}/employee/campaign/my-campaign`,
       });
     } else {
-      setShowToast({ label: "CHECKLIST_CREATED_FAILED", isError: "true" });
+      setShowToast({ 
+        label: data.error?.message || "CHECKLIST_CREATED_FAILED", 
+        isError: "true" 
+      });
+      console.error("Checklist creation failed:", data.error);
     }
   } catch (error) {
-    setShowToast({ label: "CHECKLIST_CREATED_FAILED", isError: "true" });
+    const isNetworkError = error.name === 'NetworkError';
+    setShowToast({ 
+      label: isNetworkError ? "NETWORK_ERROR" : "CHECKLIST_CREATED_FAILED", 
+      isError: "true" 
+    });
+    console.error("Error in checklist creation:", error);
   } finally {
     setSubmitting(false);
   }

Line range hint 1-24: Consider component decomposition and code organization

The component is quite large and handles multiple responsibilities. Consider breaking it down into smaller, more manageable pieces.

Suggestions for improvement:

  1. Extract utility functions (generateCodes, createQuestionObject, transformQuestions) into a separate utils file
  2. Create custom hooks for form state management and API interactions
  3. Split the preview functionality into a separate component

Example structure:

// utils/checklistUtils.js
export const generateCodes = (questions) => { ... }
export const createQuestionObject = (item, tenantId, idCodeMap) => { ... }
export const transformQuestions = (questions, tenantId, idCodeMap) => { ... }

// hooks/useChecklistForm.js
export const useChecklistForm = (initialData) => {
  const [formData, setFormData] = useState(initialData);
  // ... other form-related state and logic
  return { formData, ... };
}

// components/ChecklistPreview.js
export const ChecklistPreview = ({ data, onSubmit, onClose }) => { ... }

// CreateChecklist.js
const CreateChecklist = () => {
  const { formData, ... } = useChecklistForm(initialData);
  // ... reduced component logic
}
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/UpdateChecklist.js (2)

Line range hint 1-24: Consider extracting toast configuration to constants

The toast timeout and other UI-related constants should be defined as named constants at the top of the file.

Add these constants:

const TOAST_TIMEOUT_MS = 5000;
const LOADING_STATES = {
  IDLE: 'idle',
  SUBMITTING: 'submitting',
  ERROR: 'error',
  SUCCESS: 'success'
};

Line range hint 1-700: Consider restructuring for better maintainability

The component is handling too many responsibilities and could benefit from better separation of concerns.

Consider these architectural improvements:

  1. Extract utility functions to a separate file:

    • generateCodes
    • createQuestionObject
    • transformQuestions
    • organizeQuestions
  2. Create separate custom hooks for:

    • Form state management
    • API interactions
    • Toast notifications
  3. Split the component into smaller, focused components:

    • ChecklistForm
    • ChecklistPreview
    • ChecklistHeader

This would improve maintainability, testability, and reusability of the code.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 28c5ea4 and 1be0b62.

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

Pattern **/*.js: check

Comment on lines 332 to 335
console.log("hieeee", String(item?.type?.code));
if(String(item?.type?.code) === "SingleValueList"){
labelsArray.push("NOT_SELECTED");
}
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

Remove console.log and improve type comparison

The code has two issues:

  1. Console.log statement should be removed from production code
  2. String comparison can be made more robust

Apply this diff to fix both issues:

-    console.log("hieeee", String(item?.type?.code));
-    if(String(item?.type?.code) === "SingleValueList"){
+    if(String(item?.type?.code)?.toLowerCase() === "singlevaluelist"){
       labelsArray.push("NOT_SELECTED");
     }
📝 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
console.log("hieeee", String(item?.type?.code));
if(String(item?.type?.code) === "SingleValueList"){
labelsArray.push("NOT_SELECTED");
}
if(String(item?.type?.code)?.toLowerCase() === "singlevaluelist"){
labelsArray.push("NOT_SELECTED");
}

Comment on lines +279 to +281
if(String(item?.type?.code) === "SingleValueList"){
labelsArray.push("NOT_SELECTED");
}
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

Improve error handling specificity

The error handling could be more specific about what went wrong during the update process.

Consider enhancing the error handling:

 } catch (error) {
-    setShowToast({ label: "CHECKLIST_UPDATE_FAILED", isError: "true" });
+    const errorMessage = error.response?.data?.message || "CHECKLIST_UPDATE_FAILED";
+    setShowToast({ 
+      label: errorMessage,
+      isError: "true",
+      details: error.message 
+    });
     // console.error("Error creating checklist:", error);
 }

Also applies to: 279-281


🧹 Nitpick (assertive)

Improve string comparison robustness

The string comparison for question type could be more resilient to edge cases.

Consider this improvement:

-if(String(item?.type?.code) === "SingleValueList"){
+if(String(item?.type?.code)?.toUpperCase() === "SINGLEVALUELIST"){

This change makes the comparison case-insensitive and more maintainable.

📝 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(String(item?.type?.code) === "SingleValueList"){
labelsArray.push("NOT_SELECTED");
}
if(String(item?.type?.code)?.toUpperCase() === "SINGLEVALUELIST"){
labelsArray.push("NOT_SELECTED");
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range comments (8)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SearchChecklist.js (4)

Line range hint 56-67: Consider adding error handling for MDMS data fetch

The useEffect for processing MDMS data should handle potential errors and edge cases.

 useEffect(() => {
   const data = dataBT?.mdms;
-  if(data)
+  if (!data) {
+    console.error('Failed to fetch MDMS roles data');
+    return;
+  }
+  try {
     const newCodesOpt = data.map((item) => ({
       code: `ACCESSCONTROL_ROLES_ROLES_${item?.data?.code}`
     }));
     setCodesOpt(newCodesOpt)
+  } catch (error) {
+    console.error('Error processing MDMS roles data:', error);
+    setCodesOpt([]);
+  }
 }, [dataBT]);

Line range hint 82-93: Add error handling for HCM data processing

Similar to the previous comment, the HCM data processing should include error handling.

 useEffect(() => {
   let data = HCM?.mdms;
-  if(data)
+  if (!data) {
+    console.error('Failed to fetch HCM data');
+    return;
+  }
+  try {
     const newListsOpt = data.map((item) => ({
       list: `HCM_CHECKLIST_TYPE_${item?.data?.code}`
     }));
     setListsOpt(newListsOpt)
+  } catch (error) {
+    console.error('Error processing HCM data:', error);
+    setListsOpt([]);
+  }
 }, [HCM]);

Line range hint 119-122: Improve loading state handling

The current loading state implementation could be enhanced to provide better user feedback.

-if (isFetching) return <div></div>;
+if (isFetching) {
+  return (
+    <div className="loader-container">
+      <Loader /> {/* Assuming you have a Loader component */}
+    </div>
+  );
+}

Line range hint 95-98: Remove commented code

There's commented code that appears to be obsolete. If it's no longer needed, it should be removed for better code maintainability.

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

Line range hint 28-108: Consider refactoring option management for better maintainability

The option management logic (handleAddOption, handleUpdateOption, handleOptionDependency, etc.) follows similar patterns and could be consolidated using a reducer pattern. This would:

  • Centralize option state management
  • Reduce code duplication
  • Make the logic more maintainable

Consider refactoring the option management code to use a reducer:

+const optionReducer = (state, action) => {
+  switch (action.type) {
+    case 'ADD_OPTION':
+      return [...state, {
+        id: crypto.randomUUID(),
+        key: state.length + 1,
+        parentQuestionId: action.parentId,
+        label: `${action.t("HCM_CHECKLIST_OPTION")} ${state.length + 1}`,
+        optionDependency: false,
+        optionComment: false,
+      }];
+    case 'UPDATE_OPTION':
+      return state.map(item => 
+        item.key === action.payload.id 
+          ? { ...item, label: action.payload.value }
+          : item
+      );
+    case 'TOGGLE_DEPENDENCY':
+      return state.map(option =>
+        option.id === action.id
+          ? { ...option, optionDependency: !option.optionDependency }
+          : option
+      );
+    // Add other cases...
+    default:
+      return state;
+  }
+};
+
+const [options, dispatch] = useReducer(optionReducer, initialOptions);
+
+const handleAddOption = () => {
+  dispatch({ type: 'ADD_OPTION', parentId: field.id, t });
+};
+
+const handleUpdateOption = (param) => {
+  dispatch({ type: 'UPDATE_OPTION', payload: param });
+};

Line range hint 437-611: Consider splitting the component for better separation of concerns

The CreateQuestion component currently handles multiple responsibilities:

  • Question creation
  • Question updates
  • View mode rendering
  • Option management
  • Sub-question handling

This makes the component complex and harder to maintain. Consider splitting it into smaller, more focused components:

  • QuestionForm (base form structure)
  • QuestionOptions (option management)
  • SubQuestions (nested question handling)

This would:

  • Improve code organization
  • Make testing easier
  • Reduce cognitive load when maintaining the code
  • Make it easier to add new features or modify existing ones
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CreateChecklist.js (2)

Line range hint 590-596: Consider using a cleanup function in useEffect

The current implementation might lead to race conditions if multiple toasts are triggered in quick succession. Consider using a cleanup function.

 useEffect(()=>{
+  let timeoutId;
   if(showToast !== null)
   {
     setShowPopUp(false);
+    timeoutId = setTimeout(() => setShowToast(null), 5000);
   }
+  return () => {
+    if (timeoutId) clearTimeout(timeoutId);
+  };
 }, [showToast])

Line range hint 526-548: Enhance error handling in onSubmit

The error handling could be more specific to help users understand and resolve issues better.

 } catch (error) {
-  // Handle error scenario
-  setShowToast({ label: "CHECKLIST_CREATED_FAILED", isError: "true" });
-  // console.error("Error creating checklist:", error);
+  const errorMessage = error.response?.data?.message || "CHECKLIST_CREATED_FAILED";
+  setShowToast({ 
+    label: errorMessage, 
+    isError: "true",
+    details: error.response?.data?.errors?.map(e => e.message).join(', ')
+  });
 } finally {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 1be0b62 and e1e08be.

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

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

18-18: Verify the impact of filtering only active templates.

The addition of isActive: true will filter out inactive checklist templates from search results. While this aligns with showing active status in the results table, please ensure this is the intended behavior.

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

53-53: MDMS filtering looks good, but verify data consistency

The addition of isActive filters and type constraints in the MDMS criteria will help ensure only relevant data is fetched. However, we should verify that this doesn't accidentally filter out valid entries.

Also applies to: 75-76

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

259-259: LGTM: Filtering for active field types

The addition of isActive: true improves the UX by filtering out inactive field types from the dropdown options.

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

75-76: LGTM: Improved MDMS search criteria

Adding isActive: true to the search criteria is a good optimization that ensures only active checklist templates are retrieved.


333-335: Past review comment is still applicable

A previous review has already addressed the string comparison improvement needed in this code segment.

@@ -15,6 +15,7 @@
MdmsCriteria: {
tenantId: tenantId,
schemaCode: `HCM-ADMIN-CONSOLE.ChecklistTemplates`,
isActive: true,
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)

Document the active-only filtering behavior.

Consider adding a code comment to document that this configuration only returns active checklist templates. This helps other developers understand the filtering behavior.

 schemaCode: `HCM-ADMIN-CONSOLE.ChecklistTemplates`,
+// Only fetch active checklist templates
 isActive: true,
 filters : {},
📝 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
isActive: true,
schemaCode: `HCM-ADMIN-CONSOLE.ChecklistTemplates`,
// Only fetch active checklist templates
isActive: true,
filters : {},

@jagankumar-egov jagankumar-egov merged commit eb972fc into console Nov 13, 2024
3 checks passed
@jagankumar-egov jagankumar-egov deleted the feature/cl-new-req branch November 13, 2024 13:26
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