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

Hcmpre 1290 #1834

Merged
merged 7 commits into from
Nov 15, 2024
Merged

Hcmpre 1290 #1834

merged 7 commits into from
Nov 15, 2024

Conversation

Bhavya-egov
Copy link
Contributor

@Bhavya-egov Bhavya-egov commented Nov 14, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced the "My Microplans" page for managing microplans within the campaign manager.
    • Enhanced campaign management links in the CampaignCard component.
    • Improved campaign type selection logic based on the new source parameter.
    • Added new configurations for Microplan Campaign Search functionality.
    • Expanded routing functionality to navigate to the "My Microplans" page.
  • Bug Fixes

    • Refined error handling and display logic in campaign selection.
  • Improvements

    • Updated campaign management configurations to better reflect the latest data fields and improve clarity.
    • Reduced maximum length for campaign names to enhance validation.

These changes enhance the functionality and user experience of the campaign management interface.

@Bhavya-egov Bhavya-egov requested a review from a team as a code owner November 14, 2024 13:32
Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several modifications across multiple components and configuration files related to campaign management. Key changes include the addition of a new link in the CampaignCard for managing microplans, updates to the CampaignType component to incorporate a new source variable affecting UI behavior, and the introduction of a new configuration object for microplan search functionality. Additionally, a new component, MyMicroplans, is added to manage microplans display, and routing is updated to include this new page.

Changes

File Change Summary
.../CampaignCard.js Modified to include userId and microplanStatus in the campaign setup link URL.
.../CampaignType.js Introduced source variable from URL parameters, updated conditional logic for popup display and dropdown enablement based on productType.
.../UICustomizations.js Added MicroplanCampaignSearchConfig with preProcess and additionalCustomizations methods. Modified existing configurations to replace CAMPAIGN_END_DATE with LAST_MODIFIED_TIME and added new cases for CM_DRAFT_TYPE.
.../myCampaignConfig.js Removed CAMPAIGN_END_DATE field and added LAST_MODIFIED_TIME in "CAMPAIGN_DRAFTS"; added CM_DRAFT_TYPE in "CAMPAIGN_FAILED".
.../myMicroplanConfig.js Introduced new configuration object MicroplanCampaignSearchConfig for managing microplan search functionality, detailing API interaction and UI components.
.../MyMicroplans.js Created a new React component to display and manage microplans, including state management and event handling.
.../SetupCampaign.js Added source and microplanName variables to manage campaign setup logic based on URL parameters, affecting navigation flow.
.../index.js Added a new route for MyMicroplans component within the App component's routing structure.

Possibly related PRs

  • Finalised microplan download #1762: The changes in the main PR involve updates to the UICustomizations object, specifically enhancing the additionalCustomizations method for the MicroplanSearchConfig, which aligns with the main PR's focus on enhancing campaign management links and user interactions.
  • Microplan name update #1821: The modifications in the main PR regarding the MicroplanDetails component, particularly the handling of input fields, relate to the changes in the UICustomizations object that improve user interaction and data handling.
  • changes for the draft flow #1780: The updates in the main PR to the SetupCampaign component, particularly around campaign setup logic, are relevant to the changes in the createUpdatePlanProject function that enhance campaign management processes.
  • Allowed to update the name of microplan #1795: The changes in the main PR to allow updates to the microplan name are directly related to the modifications in the createUpdatePlanProject function, which now includes logic for updating existing campaign and plan names.
  • Facility data fix #1829: The enhancements in the main PR regarding the FacilityMappingConfig and the addition of new properties in the UICustomizations object are relevant to the updates made in the main PR that focus on improving the handling of facility data and user interactions.

Suggested reviewers

  • nipunarora-eGov

🐰 In the garden where ideas bloom,
New links and configs dispel the gloom.
Microplans now dance with delight,
In the campaign's warm, guiding light.
With routes and states all set in play,
Let's hop along and seize the day! 🌼✨


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

🧹 Outside diff range comments (7)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignCard.js (2)

Line range hint 29-53: Remove or implement commented API integration code

There's a significant block of commented code related to API integration for count functionality. Consider either:

  1. Implementing the count feature if it's required
  2. Removing the commented code and tracking it in a separate issue
  3. Adding a TODO comment with the issue reference if implementation is planned

Line range hint 1-82: Clean up commented count properties across link definitions

Multiple links have commented-out count properties. This pattern appears throughout the links array and should be addressed consistently:

 {
   label: t("MICROPLAN_CAMPAIGN"),
   link: `/${window?.contextPath}/employee/campaign/my-microplan`,
   roles: ROLES.CAMPAIGN_MANAGER,
-  // count: isLoading?"-":data
 },
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignType.js (1)

Line range hint 122-133: Fix inconsistent popup behavior between onClick and onFocus handlers

The productType!=="microplan" check is present in onClick but missing in onFocus handler, which could lead to inconsistent behavior.

  onClick={(e) => {
    if (props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType && !canUpdate && productType!=="microplan") {
      setShowPopUp(true);
      return;
    }
    return;
  }}
  onFocus={(e) => {
-   if (props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType && !canUpdate) {
+   if (props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType && !canUpdate && productType!=="microplan") {
      setShowPopUp(true);
      return;
    }
    return;
  }}
🧰 Tools
🪛 Biome

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

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

Line range hint 1-24: Add JSDoc documentation for component props.

The component lacks proper documentation for its props. Add JSDoc to document the expected props and their types.

+/**
+ * SetupCampaign component for managing campaign setup workflow
+ * @param {Object} props
+ * @param {string} props.hierarchyType - Type of hierarchy for the campaign
+ * @param {Object} props.hierarchyData - Data structure defining the hierarchy
+ * @returns {React.ReactElement}
+ */
const SetupCampaign = ({ hierarchyType, hierarchyData }) => {

Line range hint 32-45: Consider implementing error boundaries.

The component handles complex state management and API calls but lacks error boundaries. This could lead to unhandled runtime errors affecting the user experience.

Consider implementing React Error Boundaries to gracefully handle and recover from runtime errors:

class CampaignErrorBoundary extends React.Component {
  state = { hasError: false };
  
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  
  render() {
    if (this.state.hasError) {
      return <ErrorFallback onReset={() => this.setState({ hasError: false })} />;
    }
    return this.props.children;
  }
}

Line range hint 46-52: Consider memoizing search params.

The search params are being parsed on every render. Consider memoizing them using useMemo to optimize performance.

-const searchParams = new URLSearchParams(location.search);
-const id = searchParams.get("id");
-const isPreview = searchParams.get("preview");
+const searchParams = useMemo(() => {
+  const params = new URLSearchParams(location.search);
+  return {
+    id: params.get("id"),
+    isPreview: params.get("preview"),
+    // ... other params
+  };
+}, [location.search]);

Based on the search results, I can now provide a final response as there's clear evidence of inconsistent error handling patterns in the codebase:

Error handling needs standardization across API calls

The codebase shows multiple inconsistent patterns in error handling:

  • Some handlers only log to console and show toast: console.log(error); setShowToast()
  • Some show toast without logging: setShowToast({ key: "error", label: error })
  • Some include additional error state management: setLoader(false); setShowToast()
  • Inconsistent error message formatting:
    • Direct error message: error?.message
    • Translated error codes: t(error?.response?.data?.Errors?.[0]?.code)
    • Generic messages: t("FAILED_TO_UPDATE_RESOURCE")

Specific locations needing standardization:

  • SetupCampaign.js: Mixes console logging with conditional toast messages
  • UpdateCampaign.js: Similar inconsistent patterns as SetupCampaign
  • CreateMicroplan.js: Uses different toast message structure
  • HypothesisWrapper.js: Includes console.error with toast
🔗 Analysis chain

Line range hint 391-394: Verify API error handling consistency.

The error handling in API calls is inconsistent. Some error callbacks only log to console while others show toasts. Ensure consistent error handling across all API calls.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for inconsistent error handling patterns in API calls
rg -A 5 "onError: \(error" .

Length of output: 22306

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 5b8e5e0 and c075921.

📒 Files selected for processing (8)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignCard.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignType.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/myCampaignConfig.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/myMicroplanConfig.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/MyMicroplans.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/index.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignCard.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignType.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/myCampaignConfig.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

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

[error] 24-24: 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] 40-47: 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/pages/employee/MyMicroplans.js (2)

40-48: 🛠️ Refactor suggestion

Fix component syntax and contextPath usage

  1. The InboxSearchComposer should be self-closing
  2. Verify window.contextPath availability to prevent runtime errors
-        <InboxSearchComposer
-        configs={MicroplanCampaignSearchConfig?.[0]}
-        additionalConfig={{
-          resultsTable: {
-            onClickRow,
-          },
-        }}
-        ></InboxSearchComposer>
+        <InboxSearchComposer
+          configs={MicroplanCampaignSearchConfig?.[0]}
+          additionalConfig={{
+            resultsTable: {
+              onClickRow,
+            },
+          }}
+        />
#!/bin/bash
# Check for contextPath definition and usage
rg "contextPath" 
🧰 Tools
🪛 Biome

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


9-11: ⚠️ Potential issue

Initialize defaultSearchValues with expected search parameters

The empty defaultSearchValues object might cause issues if the search configuration expects certain default values. Consider initializing it with the expected search parameters from MicroplanCampaignSearchConfig.

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

73-89: Verify column customization implementation

All columns are marked with additionalCustomization: true, but the implementation details are not clear. Please ensure the customization logic is properly implemented.

#!/bin/bash
# Search for column customization implementation
rg -A 10 "additionalCustomization.*PlanConfiguration" --type js

63-63: Verify the campaign type population function

The dropdown uses a custom function populateCampaignTypeReqCriteria. Please ensure this function is properly implemented and available.

✅ Verification successful

Function is properly implemented and available

The custom function populateCampaignTypeReqCriteria is correctly implemented in the UICustomizations.js file. It's used consistently across different campaign configurations (ongoing, completed, upcoming, drafts) to populate campaign type dropdown options by making an MDMS API call to fetch project types. The implementation includes proper error handling and data transformation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the custom function implementation
rg -A 5 "populateCampaignTypeReqCriteria" --type js

Length of output: 65


Script:

#!/bin/bash
# Search for the function with a broader context
rg -A 10 "populateCampaignTypeReqCriteria" --type js --type jsx --type ts --type tsx

# Search in campaign manager related files
fd . health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager -e js -e jsx -e ts -e tsx --exec rg -l "populateCampaignTypeReqCriteria" {}

# Search for any campaign type related functions
rg -A 5 "campaign.*type.*criteria" --type js --type jsx --type ts --type tsx -i

Length of output: 694


Script:

#!/bin/bash
# Let's check the implementation in UICustomizations.js
cat health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js

# Also check the usage in other config files
cat health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/myCampaignConfig.js

Length of output: 62242

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

17-17: LGTM! Import statement follows existing patterns.

The import statement for MyMicroplans is correctly placed with other page component imports.


Line range hint 92-106: Verify session storage cleanup requirements for microplan route.

The useEffect cleanup logic specifically checks for 'setup-campaign' and 'response' routes. Verify if the new microplan route requires similar session storage cleanup.

Let's check for any session storage usage in the MyMicroplans component:

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

527-532: Verify impact of removing CAMPAIGN_END_DATE field

The removal of the campaign end date field could impact features that depend on campaign duration tracking. Please ensure:

  1. No existing features rely on this field
  2. Campaign lifecycle management remains intact without the end date

Comment on lines 22 to 30
const onTabChange = (n) => {

setTabData((prev) => prev.map((i, c) => ({ ...i, active: c === n ? true : false }))); //setting tab enable which is being clicked
// setConfig(TabSearchconfig?.TabSearchconfig?.[n]);// as per tab number filtering the config
const url = new URL(window.location.href);
url.searchParams.set("tabId", `${n}`);
window.history.replaceState({}, "", url);

};
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Fix undefined tabData state

The onTabChange function references tabData and setTabData but these are not defined in the component. The state needs to be initialized using useState hook.

  • Remove or properly implement the onTabChange function as it's currently not being used by any tab component in the rendered JSX
  • If tabs are needed, initialize the tabData state: const [tabData, setTabData] = useState([]);
🔗 Analysis chain

Fix incomplete tab implementation

The onTabChange function has several issues:

  1. It references undefined variables (tabData, setTabData)
  2. Contains commented code suggesting incomplete implementation
  3. Updates URL params but the tab state isn't properly managed

Let me search for the state definitions and React imports in the specific file to verify if tabData is properly initialized.


Let me check the complete file content to see how tabData is initialized and used in the component.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for tab-related state definitions in the file
rg "tabData|setTabData" 

Length of output: 88832


Script:

#!/bin/bash
# Search for tabData state definition in the specific file
rg -A 5 "tabData|setTabData" "health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/MyMicroplans.js"

# Search for useState imports
rg "useState" "health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/MyMicroplans.js"

Length of output: 806


Script:

#!/bin/bash
# Get more context around the file to see tabData initialization
cat "health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/MyMicroplans.js"

Length of output: 1947

🧰 Tools
🪛 Biome

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

resultsJsonPath: "PlanConfiguration",

enableColumnSort: true,
// resultsJsonPath: "mdms",
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 code

Remove the commented out resultsJsonPath line as it's no longer needed.

-            // resultsJsonPath: "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
// resultsJsonPath: "mdms",

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;
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

Verify correct assignment of status in PlanConfigurationSearchCriteria

At line 317, data.body.PlanConfigurationSearchCriteria.status = status?.status;. Since status is destructured from data?.state?.searchForm || {}, ensure that status?.status is the intended value. It might need to be status?.code or simply status.

Please confirm that the correct value is being assigned to status.


case "CAMPAIGN_TYPE":
if (value && value != "NA") {
return <p>{t(Digit.Utils.locale.getTransformedLocale("MICROPLAN_TYPE_" + value))}</p>;
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)

Use template literals instead of string concatenation

Line 348 concatenates strings using +. For better readability and to adhere to best practices, use template literals.

Modify line 348 as follows:

- return <p>{t(Digit.Utils.locale.getTransformedLocale("MICROPLAN_TYPE_" + value))}</p>;
+ return <p>{t(Digit.Utils.locale.getTransformedLocale(`MICROPLAN_TYPE_${value}`))}</p>;
📝 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
return <p>{t(Digit.Utils.locale.getTransformedLocale("MICROPLAN_TYPE_" + value))}</p>;
return <p>{t(Digit.Utils.locale.getTransformedLocale(`MICROPLAN_TYPE_${value}`))}</p>;
🧰 Tools
🪛 Biome

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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

Comment on lines 313 to 318
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;
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

Avoid duplicate assignments to PlanConfigurationSearchCriteria.name

In the preProcess method, data.body.PlanConfigurationSearchCriteria.name is assigned twice, at lines 313 and 318. This could lead to unintended behavior or confusion.

Consider consolidating the assignments to ensure only one definitive value is set:

- data.body.PlanConfigurationSearchCriteria.name = name;
...
- data.body.PlanConfigurationSearchCriteria.name = data?.state?.searchForm?.microplanName;
+ data.body.PlanConfigurationSearchCriteria.name = data?.state?.searchForm?.microplanName || name;
📝 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
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;
data.body.PlanConfigurationSearchCriteria.name = data?.state?.searchForm?.microplanName || 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;

Copy link
Collaborator

@jagankumar-egov jagankumar-egov left a comment

Choose a reason for hiding this comment

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

check all, @Bhavya-egov

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

🧹 Outside diff range comments (6)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignName.js (2)

Line range hint 41-54: Consolidate error handling logic

The error handling is spread across multiple useEffect hooks, making it harder to maintain and understand the validation flow.

Consider consolidating the validation logic:

+ const validateName = (name, isSubmitting) => {
+   if (isSubmitting && !name) {
+     return "CAMPAIGN_FIELD_ERROR_MANDATORY";
+   }
+   if (startValidation && !name) {
+     return "CAMPAIGN_NAME_FIELD_ERROR";
+   }
+   return null;
+ };

  useEffect(() => {
-   if (props?.props?.isSubmitting && !name) {
-     setError({ message: "CAMPAIGN_FIELD_ERROR_MANDATORY" });
-   } else {
-     setError(null);
-   }
-  }, [props?.props?.isSubmitting]);
-
-  useEffect(() => {
-   if (startValidation && !name) {
-     setError({ message: "CAMPAIGN_NAME_FIELD_ERROR" });
-   } else if (name) {
-     setError(null);
-     onSelect("campaignName", name);
-   }
+   const errorMessage = validateName(name, props?.props?.isSubmitting);
+   setError(errorMessage ? { message: errorMessage } : null);
+   if (!errorMessage && name) {
+     onSelect("campaignName", name);
+   }
-  }, [name, props?.props?.sessionData?.HCM_CAMPAIGN_NAME?.campaignName]);
+  }, [name, props?.props?.isSubmitting, startValidation]);

Line range hint 65-73: Improve URL parameter management and event handling

The current implementation has potential race conditions with window events and scattered URL parameter management.

Consider these improvements:

- useEffect(() =>{
-   setKey(currentKey);
-   setCurrentStep(currentKey);
- }, [currentKey])

- useEffect(() => {
-   updateUrlParams({ key: key });
-   window.dispatchEvent(new Event("checking"));
- }, [key]);

+ useEffect(() => {
+   if (currentKey) {
+     const newKey = parseInt(currentKey);
+     setKey(newKey);
+     setCurrentStep(newKey);
+     updateUrlParams({ key: newKey });
+     // Use a more specific custom event name and add necessary data
+     window.dispatchEvent(new CustomEvent('campaignKeyUpdate', { 
+       detail: { key: newKey }
+     }));
+   }
+ }, [currentKey]);
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignType.js (1)

Line range hint 122-126: Fix undefined variable and extract condition check

There are several issues in this code segment:

  1. productType is undefined, which could cause unexpected behavior
  2. The condition check is duplicated between onClick and onFocus handlers

Apply this fix:

const checkIfMicroplan = () => {
  return source === "microplan";
};

// In JSX
onClick={(e) => {
  if (props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType && !canUpdate && !checkIfMicroplan()) {
    setShowPopUp(true);
    return;
  }
}}
onFocus={(e) => {
  if (props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType && !canUpdate && !checkIfMicroplan()) {
    setShowPopUp(true);
    return;
  }
}}
🧰 Tools
🪛 Biome

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

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/setupCampaignValidators.js (3)

Line range hint 219-221: Fix date comparison logic

There's a bug in the date comparison. The getTime() method is used on one side but not the other.

Apply this fix:

-      } else if (endDateObj.getTime() < startDateObj) {
+      } else if (endDateObj.getTime() < startDateObj.getTime()) {

Line range hint 1-400: Standardize error handling pattern

The error handling pattern varies across different validation cases. Some use direct string keys, others use template literals with t(), and some include additional parameters.

Consider standardizing the error handling pattern:

  1. Use consistent error message keys
  2. Always use the translation function
  3. Include relevant parameters in the error object

Example pattern:

setShowToast({
  key: "error",
  label: errorKey,
  labelParams: params,  // Optional parameters for translation
  transitionTime: time  // Optional transition time
});

Line range hint 286-321: Add security validations for file uploads

The file upload validation lacks important security checks:

  1. File type validation
  2. File size limits
  3. Path traversal prevention

Consider adding these security checks:

    case "uploadBoundary":
+     const allowedTypes = ['csv', 'xlsx'];
+     const maxSize = 5 * 1024 * 1024; // 5MB
+     
+     if (!formData?.uploadBoundary?.uploadedFile?.[0]) {
+       setShowToast({ key: "error", label: t("HCM_FILE_MISSING") });
+       return false;
+     }
+     
+     const file = formData.uploadBoundary.uploadedFile[0];
+     const fileType = file.name.split('.').pop().toLowerCase();
+     
+     if (!allowedTypes.includes(fileType)) {
+       setShowToast({ key: "error", label: t("HCM_INVALID_FILE_TYPE") });
+       return false;
+     }
+     
+     if (file.size > maxSize) {
+       setShowToast({ key: "error", label: t("HCM_FILE_TOO_LARGE") });
+       return false;
+     }
+     
      if (formData?.uploadBoundary?.isValidation) {

Apply similar changes to uploadFacility and uploadUser cases.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between a86b7f7 and f076ed0.

📒 Files selected for processing (9)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignCard.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignName.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignType.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js (7 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/myMicroplanConfig.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/MyMicroplans.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/index.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/setupCampaignValidators.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignCard.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignType.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/myMicroplanConfig.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

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

[error] 20-27: 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 (9)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/MyMicroplans.js (2)

1-5: LGTM! Imports are well-organized and necessary.

All imported modules are being used in the component, and the import structure follows good practices.


7-9: LGTM! Component structure follows React best practices.

The component is properly defined as a functional component with necessary hooks initialization.

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

41-44: ⚠️ Potential issue

Fix incorrect URL query parameter format.

The URL format for query parameters is incorrect. The first parameter should use ? instead of &.

-      link: `/${window?.contextPath}/employee/campaign/setup-microplan&userId=${userId}&status=${microplanStatus}`,
+      link: `/${window?.contextPath}/employee/campaign/setup-microplan?userId=${userId}&status=${microplanStatus}`,

The previous review comments about route path mismatch and translation keys are still valid and should be addressed.

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

48-64: 🧹 Nitpick (assertive)

Remove commented code block

Remove the commented campaign type dropdown configuration to improve code maintainability.


72-88: Verify additionalCustomization implementation

The columns are configured with additionalCustomization: true, but we need to ensure the customization logic is properly implemented.

✅ Verification successful

Implementation for additionalCustomization is properly handled

The codebase shows that timestamp formatting is properly implemented:

  1. The lastModifiedTime field is handled by Digit.DateUtils.ConvertEpochToDate() in UICustomizations.js
  2. The codebase has consistent timestamp formatting using various date utilities:
    • Digit.DateUtils.ConvertEpochToDate() for display formatting
    • Digit.Utils.date.convertDateToEpoch() for epoch conversion
    • epochToDateTime() for timeline displays

The additionalCustomization flag is working as intended to enable this date formatting functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for additionalCustomization implementation for these columns
rg -A 10 "additionalCustomization.*MicroplanCampaignSearchConfig" --type js

# Search for timestamp formatting implementation
rg -A 5 "lastModifiedTime.*format" --type js

Length of output: 124


Script:

#!/bin/bash
# Search for any implementation related to additionalCustomization in campaign manager
rg -A 10 "additionalCustomization" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/

# Search for any table component or search result component that might handle these customizations
rg -A 10 "SearchResult|Table" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/

# Look for timestamp formatting in campaign manager
rg -A 5 "lastModifiedTime" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/

Length of output: 90409


Script:

#!/bin/bash
# Search for the implementation of additionalCustomization in UICustomizations.js for timestamp formatting
rg -A 10 "LAST_MODIFIED_TIME.*additionalCustomization" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js

# Look for any utility functions that handle timestamp formatting
rg -A 5 "epochToDateTime|formatDate" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/

Length of output: 9831


Script:

#!/bin/bash
# Search for the implementation of additionalCustomization in UICustomizations.js for lastModifiedTime
rg -B 5 -A 15 "case \"LAST_MODIFIED_TIME\"" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js

# Look for any date formatting utilities in the codebase
rg -A 5 "Digit.*date|DateFormatter|formatDateTime" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/

Length of output: 37204

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

7-7: 🧹 Nitpick (assertive)

Verify props usage and consider prop drilling alternatives

The component receives several props through destructuring, but some might be unnecessary. Additionally, the nested props.props structure suggests potential prop drilling.

Let's analyze the props usage:

Consider using React Context or a state management solution if this component is deeply nested in the component tree.

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

17-17: LGTM!

The import statement follows the existing pattern and is correctly placed with other page imports.

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

194-195: 🛠️ Refactor suggestion

Verify the impact of reducing campaign name length limit

The maximum allowed length for campaign names has been significantly reduced from 250 to 30 characters. This is a breaking change that could affect existing campaigns and integrations.

Let's verify the impact:

Consider improving the validation:

-      } else if (formData.campaignName.length > 30) {
-        setShowToast({ key: "error", label: "CAMPAIGN_NAME_LONG_ERROR" });
+      } else if (formData.campaignName.trim().length > 30) {
+        setShowToast({ 
+          key: "error", 
+          label: "CAMPAIGN_NAME_LONG_ERROR",
+          labelParams: { MAX_LENGTH: 30, CURRENT_LENGTH: formData.campaignName.trim().length }
+        });

The improvements:

  1. Use trim() to accurately count characters without leading/trailing spaces
  2. Add dynamic parameters to the error message for better user feedback
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js (1)

309-309: ⚠️ Potential issue

Fix Typo: Use 'url.includes' Instead of 'urlIncludes'

At line 309, urlIncludes appears to be a typo. The correct method is url.includes.

Apply this diff to fix the typo:

- const queryString = urlIncludes("?") ? url.split("?")[1] : url.split("&").slice(1).join("&");
+ const queryString = url.includes("?") ? url.split("?")[1] : url.split("&").slice(1).join("&");

Likely invalid or redundant comment.

const { t } = useTranslation();
const history = useHistory();
const onClickRow = ({ original: row }) => {
console.log("row" , row);
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 console.log statement.

Remove debugging statements before deploying to production.

-    console.log("row" , row);
📝 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("row" , row);

Comment on lines +20 to +28
<InboxSearchComposer
configs={MicroplanCampaignSearchConfig?.[0]}
additionalConfig={{
resultsTable: {
onClickRow,
},
}}
></InboxSearchComposer>
</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)

Use self-closing tag for InboxSearchComposer.

Since the InboxSearchComposer component doesn't have any children, it should use a self-closing tag.

-        <InboxSearchComposer
-        configs={MicroplanCampaignSearchConfig?.[0]}
-        additionalConfig={{
-          resultsTable: {
-            onClickRow,
-          },
-        }}
-        ></InboxSearchComposer>
+        <InboxSearchComposer
+          configs={MicroplanCampaignSearchConfig?.[0]}
+          additionalConfig={{
+            resultsTable: {
+              onClickRow,
+            },
+          }}
+        />
📝 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
<InboxSearchComposer
configs={MicroplanCampaignSearchConfig?.[0]}
additionalConfig={{
resultsTable: {
onClickRow,
},
}}
></InboxSearchComposer>
</div>
<InboxSearchComposer
configs={MicroplanCampaignSearchConfig?.[0]}
additionalConfig={{
resultsTable: {
onClickRow,
},
}}
/>
</div>
🧰 Tools
🪛 Biome

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

Comment on lines +12 to +13
const updatedName = row.name.replace(/&/g, "and");
history.push(`/${window.contextPath}/employee/campaign/setup-campaign?id=${row.campaignId}&draft=true&fetchBoundary=true&draftBoundary=true&source=microplan&microName=${updatedName}`);
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 enhancing string handling and URL construction.

The current implementation has potential areas for improvement:

  1. The string replacement might need more robust handling for special characters
  2. URL parameters should be properly encoded
-    const updatedName = row.name.replace(/&/g, "and");
-    history.push(`/${window.contextPath}/employee/campaign/setup-campaign?id=${row.campaignId}&draft=true&fetchBoundary=true&draftBoundary=true&source=microplan&microName=${updatedName}`);
+    const updatedName = encodeURIComponent(row.name.replace(/&/g, "and"));
+    const params = new URLSearchParams({
+      id: row.campaignId,
+      draft: "true",
+      fetchBoundary: "true",
+      draftBoundary: "true",
+      source: "microplan",
+      microName: updatedName
+    });
+    history.push(`/${window.contextPath}/employee/campaign/setup-campaign?${params}`);
📝 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 updatedName = row.name.replace(/&/g, "and");
history.push(`/${window.contextPath}/employee/campaign/setup-campaign?id=${row.campaignId}&draft=true&fetchBoundary=true&draftBoundary=true&source=microplan&microName=${updatedName}`);
const updatedName = encodeURIComponent(row.name.replace(/&/g, "and"));
const params = new URLSearchParams({
id: row.campaignId,
draft: "true",
fetchBoundary: "true",
draftBoundary: "true",
source: "microplan",
microName: updatedName
});
history.push(`/${window.contextPath}/employee/campaign/setup-campaign?${params}`);

Comment on lines +25 to +26
const userId = Digit.UserService.getUser().info.uuid;
const microplanStatus = "RESOURCE_ESTIMATIONS_APPROVED"
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 improving variable management and error handling.

  1. The hardcoded microplanStatus should be moved to a constants file for better maintainability.
  2. Add error handling for the user service call.
+ import { MICROPLAN_STATUSES } from "../constants";
+
  const CampaignCard = () => {
-   const userId = Digit.UserService.getUser().info.uuid;
-   const microplanStatus = "RESOURCE_ESTIMATIONS_APPROVED"
+   const userId = Digit.UserService.getUser()?.info?.uuid;
+   if (!userId) {
+     throw new Error("User information not available");
+   }
+   const microplanStatus = MICROPLAN_STATUSES.RESOURCE_ESTIMATIONS_APPROVED;

Committable suggestion skipped: line range outside the PR's diff.



const tenantId = Digit.ULBService.getCurrentTenantId();
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

Remove unused variable declaration

The mdms_context_path variable is declared but never used in the configuration.

-  const mdms_context_path = window?.globalConfigs?.getConfig("MDMS_V2_CONTEXT_PATH") || "mdms-v2";
📝 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";

Comment on lines +117 to +119
//if user comes from set up microplan
} else if (source === "microplan") {
setCurrentKey(2);
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 microplan source condition.

The condition for source === "microplan" lacks proper documentation explaining when and why this flow is triggered. Add comments to clarify the business logic.

+        // When campaign is initiated from microplan setup,
+        // skip to step 2 to maintain workflow continuity
         } else if (source === "microplan") {
             setCurrentKey(2);
📝 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 user comes from set up microplan
} else if (source === "microplan") {
setCurrentKey(2);
// When campaign is initiated from microplan setup,
// skip to step 2 to maintain workflow continuity
} else if (source === "microplan") {
setCurrentKey(2);

Comment on lines +52 to +53
const source = searchParams.get("source");
const microplanName = searchParams.get("microName");
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 unused variable declaration.

The microplanName variable is declared but never used in the code. Either remove it if not needed or document its intended purpose.

  const source = searchParams.get("source");
-  const microplanName = searchParams.get("microName");
📝 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 source = searchParams.get("source");
const microplanName = searchParams.get("microName");
const source = searchParams.get("source");

Comment on lines +117 to +124
//if user comes from set up microplan
} else if (source === "microplan") {
setCurrentKey(2);
//if the campaign is in draft and the start date is passed
}else if (isDateRestricted === "true") {
setCurrentKey(3);
}
else {
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)

Improve code readability and fix indentation.

The else-if chain has inconsistent indentation and could be simplified for better readability. Consider using early returns or consistent indentation.

-            //if user comes from set up microplan
-        } else if (source === "microplan") {
-            setCurrentKey(2);
-            //if the campaign is in draft and the start date is passed
-        }else if (isDateRestricted === "true") {
-          setCurrentKey(3);
-      }
+        // Handle microplan setup flow
+        } else if (source === "microplan") {
+          setCurrentKey(2);
+        // Handle date restricted campaigns
+        } else if (isDateRestricted === "true") {
+          setCurrentKey(3);
+        }

Also, consider adding JSDoc comments to explain the purpose of different conditions and their impact on the campaign setup flow.

📝 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 user comes from set up microplan
} else if (source === "microplan") {
setCurrentKey(2);
//if the campaign is in draft and the start date is passed
}else if (isDateRestricted === "true") {
setCurrentKey(3);
}
else {
// Handle microplan setup flow
} else if (source === "microplan") {
setCurrentKey(2);
// Handle date restricted campaigns
} else if (isDateRestricted === "true") {
setCurrentKey(3);
} else {

Comment on lines +1030 to +1031
retryCampaign(row, searchResult);
break;
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

'searchResult' May Be Undefined in 'onActionSelect'

At lines 1030-1031, retryCampaign(row, searchResult); is called within the onActionSelect function, but searchResult is not defined in this scope. This could lead to a ReferenceError when onActionSelect is executed.

Consider passing searchResult as a parameter to onActionSelect or retrieving it within the function. Here's a possible fix:

- const onActionSelect = (value, row) => {
+ const onActionSelect = (value, row, searchResult) => {
    switch (value?.code) {
      case "ACTION_LABEL_VIEW_TIMELINE":
        setTimeline(true);
        break;
      case "ACTION_LABEL_RETRY":
        retryCampaign(row, searchResult);
        break;

Ensure that when onActionSelect is called, searchResult is passed appropriately.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +1060 to +1063
options={[
{ key: 1, code: "ACTION_LABEL_VIEW_TIMELINE", i18nKey: t("ACTION_LABEL_VIEW_TIMELINE") },
{ key: 2, code: "ACTION_LABEL_RETRY", i18nKey: t("ACTION_LABEL_RETRY") },
].filter((obj) => Digit.Utils.didEmployeeHasAtleastOneRole(["SYSTEM_ADMINISTRATOR"] || obj?.key != 2))} //added retry for system adminstrator for failed campaign
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

Correct Logical Error in Filtering Action Options

The filter function in lines 1060-1063 may not work as intended due to incorrect use of the logical || operator. The condition should ensure that the 'Retry' option is only available to users with the SYSTEM_ADMINISTRATOR role.

Adjust the filter logic as follows:

- ].filter((obj) => Digit.Utils.didEmployeeHasAtleastOneRole(["SYSTEM_ADMINISTRATOR"] || obj?.key != 2))
+ ].filter((obj) => obj?.key !== 2 || Digit.Utils.didEmployeeHasAtleastOneRole(["SYSTEM_ADMINISTRATOR"]))

This change ensures that:

  • If the option's key is not 2 (not 'Retry'), it is included.
  • If the option's key is 2 (the 'Retry' action), it is included only if the user has the SYSTEM_ADMINISTRATOR role.
📝 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
options={[
{ key: 1, code: "ACTION_LABEL_VIEW_TIMELINE", i18nKey: t("ACTION_LABEL_VIEW_TIMELINE") },
{ key: 2, code: "ACTION_LABEL_RETRY", i18nKey: t("ACTION_LABEL_RETRY") },
].filter((obj) => Digit.Utils.didEmployeeHasAtleastOneRole(["SYSTEM_ADMINISTRATOR"] || obj?.key != 2))} //added retry for system adminstrator for failed campaign
options={[
{ key: 1, code: "ACTION_LABEL_VIEW_TIMELINE", i18nKey: t("ACTION_LABEL_VIEW_TIMELINE") },
{ key: 2, code: "ACTION_LABEL_RETRY", i18nKey: t("ACTION_LABEL_RETRY") },
].filter((obj) => obj?.key !== 2 || Digit.Utils.didEmployeeHasAtleastOneRole(["SYSTEM_ADMINISTRATOR"]))} //added retry for system adminstrator for failed campaign

@@ -92,6 +93,8 @@ const CampaignBreadCrumb = ({ location, defaultPath }) => {
*/
const App = ({ path, BOUNDARY_HIERARCHY_TYPE, hierarchyData }) => {
const location = useLocation();
const userId = Digit.UserService.getUser().info.uuid;
Copy link
Collaborator

Choose a reason for hiding this comment

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

remove them from here, it is just query params from the link.
keep it similar to update campaign URL

Also URL say setup-from-microplan

},
},
masterName: "commonUiConfig",
moduleName: "MicroplanCampaignSearchConfig",
Copy link
Collaborator

Choose a reason for hiding this comment

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

just config, moduleName is differnt for microplan UI and here ?

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 (2)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignType.js (1)

Line range hint 122-126: Extract complex condition into a readable function

The popup display condition is becoming complex. Consider extracting it into a descriptive function for better readability and maintainability.

const shouldShowPopup = () => {
  return props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType 
    && !canUpdate 
    && source !== "microplan";
};

// Usage
if (shouldShowPopup()) {
  setShowPopUp(true);
  return;
}
🧰 Tools
🪛 Biome

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

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

Line range hint 31-89: Add breadcrumb entry for setup-from-microplan route

To maintain navigation consistency, add a breadcrumb entry for the new route in the crumbs array:

 const crumbs = [
   // ... existing crumbs
+  {
+    path: pathVar === "setup-from-microplan" ? "" : `/${window?.contextPath}/employee/campaign/setup-from-microplan`,
+    content: t("SETUP_FROM_MICROPLAN"),
+    show: pathVar === "setup-from-microplan" ? true : false,
+  },
   // ... remaining crumbs
 ];

Also ensure to add the translation key "SETUP_FROM_MICROPLAN" to your localization files.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between f076ed0 and 978884b.

📒 Files selected for processing (4)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignCard.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignType.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/MyMicroplans.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/index.js (3 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignCard.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

[error] 33-40: 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 (5)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/MyMicroplans.js (2)

28-42: Component structure looks good!

The component follows React best practices with proper use of fragments and clear separation of concerns. The search configuration is properly passed to the InboxSearchComposer.

🧰 Tools
🪛 Biome

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


18-23: 🧹 Nitpick (assertive)

Clarify the status of user-specific filtering.

The commented code suggests that user-specific filtering was intended but not implemented. This could affect the functionality of the microplans list.

Let me check if this functionality is implemented elsewhere:

Would you like me to help implement the user-specific filtering functionality?

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

17-17: LGTM!

The import statement follows the existing pattern and is correctly placed with other page component imports.


96-96: LGTM!

The user ID retrieval follows the standard practice using Digit.UserService.


154-154: LGTM!

The route configuration:

  • Uses the correct path format as suggested
  • Follows the existing routing pattern
  • Is properly placed within the AppContainer

Comment on lines +7 to +13
// export const updateUrlParams=(params) =>{
// const url = new URL(window.location.href);
// Object.entries(params).forEach(([key, value]) => {
// url.searchParams.set(key, value);
// });
// window.history.replaceState({}, "", url);
// }
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 utility function.

The updateUrlParams function is commented out and unused. If this functionality is needed in the future, it can be retrieved from version control history.

Comment on lines +41 to +43
{
label: t("ACTION_TEST_SETUP_CAMPAIGN_FROM_MICROPLAN"),
link: `/${window?.contextPath}/employee/campaign/setup-campaign`,
link: `/${window?.contextPath}/employee/campaign/setup-from-microplan&userId=${userId}&status=${microplanStatus}`,
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Fix URL query parameter syntax and ensure route consistency

The search results confirm two issues:

  • The URL uses incorrect query parameter syntax (& instead of ? for first parameter)
  • Other similar links in the codebase consistently use the correct ? syntax for query parameters

Apply this fix:

-      link: `/${window?.contextPath}/employee/campaign/setup-from-microplan&userId=${userId}&status=${microplanStatus}`,
+      link: `/${window?.contextPath}/employee/campaign/setup-from-microplan?userId=${encodeURIComponent(userId)}&status=${encodeURIComponent(microplanStatus)}`,
🔗 Analysis chain

Fix URL query parameter syntax and add URL encoding

The link URL has incorrect query parameter syntax and missing URL encoding:

Apply this fix:

-      link: `/${window?.contextPath}/employee/campaign/setup-from-microplan&userId=${userId}&status=${microplanStatus}`,
+      link: `/${window?.contextPath}/employee/campaign/setup-from-microplan?userId=${encodeURIComponent(userId)}&status=${encodeURIComponent(microplanStatus)}`,

Let's verify the URL format consistency across the codebase:


The search results confirm that there's a mismatch between the route definition and the link URL. Let me verify the complete routing structure to ensure we provide accurate guidance.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check URL patterns in campaign setup routes
rg "setup-from-microplan" --type js -A 2

Length of output: 962


Script:

#!/bin/bash
# Check the campaign routes and URL patterns
rg "campaign.*Route" --type js -A 3

# Also check other similar link constructions
rg "link:.*campaign" --type js -A 1

Length of output: 3616

@@ -19,6 +19,7 @@ const CampaignSelection = ({ onSelect, formData, formState, ...props }) => {
const searchParams = new URLSearchParams(location.search);
const [currentStep , setCurrentStep] = useState(1);
const currentKey = searchParams.get("key");
const source = searchParams.get("source");
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

Consolidate URL parameter handling into a custom hook

Following up on previous review feedback, the URL parameter handling should be extracted into a custom hook for better maintainability and reusability.

Create a new hook useCampaignParams:

const useCampaignParams = () => {
  const validSources = ["microplan"];
  const searchParams = new URLSearchParams(location.search);
  const rawSource = searchParams.get("source");
  
  return {
    source: validSources.includes(rawSource) ? rawSource : null,
    key: searchParams.get("key") ? parseInt(searchParams.get("key")) : 1,
    isMicroplan: () => rawSource === "microplan",
    updateParams: (params) => {
      const url = new URL(window.location.href);
      Object.entries(params).forEach(([key, value]) => {
        url.searchParams.set(key, value);
      });
      window.history.replaceState({}, "", url);
    }
  };
};

Comment on lines +147 to +148
disabled = {source === "microplan"}

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 whitespace and extract condition into a function

  1. Remove the unnecessary whitespace after the disabled prop
  2. Extract the condition into a descriptive function as suggested in previous review
-  disabled = {source === "microplan"}
-  
+  disabled={checkIfMicroplan()}

Add this function at the component level:

const checkIfMicroplan = () => {
  return source === "microplan";
};

@jagankumar-egov jagankumar-egov merged commit d297c75 into console Nov 15, 2024
3 checks passed
@jagankumar-egov jagankumar-egov deleted the HCMPRE-1290 branch November 15, 2024 09:30
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