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

Vertical stepper implemenetation #1441

Merged
merged 22 commits into from
Oct 7, 2024

Conversation

ashish-egov
Copy link
Contributor

@ashish-egov ashish-egov commented Sep 30, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced UploadDataCustom component for handling data file uploads with validation and feedback mechanisms.
    • Implemented XlsPreview component for displaying Excel file previews in a user-friendly popup.
    • New configuration step for data uploading in the MicroplanConfig, enhancing user workflow.
  • Improvements

    • Enhanced download functionality to allow custom file naming during Excel downloads.
    • Integrated event listener in SetupMicroplan for dynamic URL parameter handling.
    • Improved code readability and consistency across various components, including formatting adjustments.
  • Bug Fixes

    • Adjusted component registration and step numbering in the Microplan module for better clarity and functionality.

Copy link
Contributor

coderabbitai bot commented Sep 30, 2024

Warning

Rate limit exceeded

@ashish-egov has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 26 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between 22e3bc4 and 941ea96.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes introduce several modifications within the campaign manager and microplan modules of the application. Key updates include the addition of the XlsPreview and UploadDataCustom components, enhancements to the BulkUpload component for dynamic file handling, and adjustments to the MicroplanConfig to incorporate new steps for data uploads. The Utils object has been expanded with a new campaign property, and the export structure of utility functions has been refined. Overall, these updates improve component management and code readability without altering existing functionalities.

Changes

File Path Change Summary
.../campaign-manager/src/Module.js Added import for XlsPreview, reformatted CreateChecklist import, updated componentsToRegister to include XlsPreview, and reformatted CreateQuestion entry for consistency.
.../campaign-manager/src/components/BulkUpload.js Removed static import of XlsPreview, now dynamically retrieved from Digit.ComponentRegistryService, updated state management for fileUrl, modified renderFileCards for click handling, and adjusted JSX structure for previews.
.../campaign-manager/src/components/UploadData.js Adjusted formatting for state declarations, updated useEffect hooks for readability, and streamlined JSX structure for error messages and info cards.
.../campaign-manager/src/hooks/index.js Added new property campaign to Utils object, enhancing utility functions related to campaigns.
.../campaign-manager/src/utils/index.js Updated default export to include downloadExcelWithCustomName function instead of an empty object.
.../microplan/src/components/UploadDataCustom.js Introduced UploadDataCustom component for uploading, validating, and managing data files, integrating various libraries and hooks for enhanced functionality.
.../microplan/src/configs/SetupMicroplanConfig.js Modified configuration to include new upload step with UploadDataCustom, adjusted existing step counts and names for consistency.
.../microplan/src/pages/employee/SetupMicroplan.js Added event listener for custom "checking" event to update currentKey state based on URL parameters, with cleanup on component unmount.

Possibly related PRs

  • Application Management Updated #1359: The changes in the main PR involve the addition of the XlsPreview component, which is also referenced in the BulkUpload component of this PR, indicating a direct relationship in terms of component usage.
  • Assumptions #1457: The introduction of the AssumptionsForm component and its registration in the Module.js file directly relates to the changes made in the main PR regarding component management.

Suggested reviewers

  • jagankumar-egov

🐇 In the meadow, changes bloom,
New components chase away the gloom.
Uploads, previews, all in sight,
File management feels just right!
With each click, a joyful cheer,
Our app grows better, year by year! 🌼


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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between e7821da and 70aab30.

⛔ Files ignored due to path filters (1)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/package.json is excluded by !**/*.json
📒 Files selected for processing (9)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/downloadExcel.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/Module.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/BulkUpload.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UploadDataCustom.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/XlsPreview.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/configs/SetupMicroplanConfig.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/useGenerateIdCampaign.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/SetupMicroplan.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/utils/downloadExcel.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/downloadExcel.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

📓 Learnings (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UploadDataCustom.js (1)
Learnt from: siddhant-nawale-egov
PR: egovernments/DIGIT-Frontend#845
File: micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Upload.js:460-461
Timestamp: 2024-06-12T08:18:44.708Z
Learning: Error handling for Shapefile parsing in `Upload.js` is managed commonly and is handled elsewhere in the codebase, as clarified by the user.
🪛 Biome
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/BulkUpload.js

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


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

Unsafe fix: Use a SelfClosingElement instead

(lint/style/useSelfClosingElements)


[error] 183-183: Avoid passing children using a prop

The canonical way to pass children in React is to use JSX elements

(lint/correctness/noChildrenProp)

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UploadDataCustom.js

[error] 126-126: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 176-176: Unsafe usage of optional chaining.

If it short-circuits with 'undefined' the evaluation will throw TypeError here:

(lint/correctness/noUnsafeOptionalChaining)


[error] 193-193: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/XlsPreview.js

[error] 9-9: Alternative text title element cannot be empty

For accessibility purposes, SVGs should have an alternative text, provided via title element. If the svg element has role="img", you should add the aria-label or aria-labelledby attribute.

(lint/a11y/noSvgWithoutTitle)

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

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

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

(lint/style/useNumberNamespace)

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/utils/downloadExcel.js

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

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

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

Line range hint 1-24: Summary: Good implementation of the source parameter

The changes to add the source parameter to the useGenerateIdCampaign function are well-implemented and maintain backward compatibility. The new parameter allows for more flexibility in the API request criteria without altering the existing functionality.

To ensure the changes are used correctly throughout the codebase, consider the following:

Run the following script to check for any usage of useGenerateIdCampaign that might need updating:

Review the results to ensure that any calls to useGenerateIdCampaign are updated if they need to use the new source parameter.

✅ Verification successful

All usages of useGenerateIdCampaign include the new source parameter.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of useGenerateIdCampaign and check if they need to be updated with the new 'source' parameter.

# Search for useGenerateIdCampaign usage
rg --type js 'useGenerateIdCampaign\s*\(' -A 5

Length of output: 885

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

1-13: LGTM: Import and documentation are well-structured.

The import statement is correct, and the comment block provides a clear explanation of the function's purpose and usage. This is good practice for maintaining readable and maintainable code.

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

1-5: LGTM: Imports and constants are well-organized.

The necessary imports are present, and the use of a constant for the primary color promotes consistency throughout the component.


1-69: Overall assessment: Well-implemented component with room for minor improvements

The XlsPreview component is a solid implementation for previewing Excel files. It demonstrates good use of React practices, internationalization, and third-party libraries. The suggestions provided earlier will further enhance its accessibility, error handling, and maintainability.

Key strengths:

  1. Clear component structure
  2. Proper use of internationalization
  3. Effective integration of DocViewer for file preview

Areas for improvement:

  1. SVG accessibility
  2. Error handling for missing file prop
  3. Extraction of inline styles

Implementing these suggestions will result in a more robust and maintainable component.

🧰 Tools
🪛 Biome

[error] 9-9: Alternative text title element cannot be empty

For accessibility purposes, SVGs should have an alternative text, provided via title element. If the svg element has role="img", you should add the aria-label or aria-labelledby attribute.

(lint/a11y/noSvgWithoutTitle)

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/Module.js (3)

12-12: LGTM: Import statement for UploadDataCustom

The import statement for the new UploadDataCustom component follows best practices and naming conventions.


59-59: LGTM: UploadDataCustom added to componentsToRegister

The UploadDataCustom component is correctly added to the componentsToRegister object, following the existing pattern.


12-12: Verify the usage of UploadDataCustom component

The UploadDataCustom component has been imported and registered correctly. However, it's important to ensure that this new component is being used appropriately within the application.

Could you please provide information on where and how the UploadDataCustom component is being used? This will help ensure that the addition is serving its intended purpose.

To assist in verifying the component's usage, you can run the following script:

Also applies to: 59-59

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

101-102: Verify consistency between key and populators.name

In this step, key is set to "uploadData", but populators.name is set to "hypothesis".

Typically, key and populators.name should be consistent to ensure proper data mapping and handling.

Please confirm whether this discrepancy is intentional. If not, consider updating populators.name to "uploadData" to match the key.

Also applies to: 117-119


110-111: Potential redundancy between type and types in customProps

Within customProps, both type and types are defined:

  • type: "facilityWithBoundary"
  • types: ["boundary", "facilityWithBoundary"]

Unless both properties are required for different purposes, having both may be redundant and could cause confusion.

Please verify if both type and types are necessary. If only one is needed, consider removing the redundant property to simplify the configuration.

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

155-155: Verify correct file is being downloaded

In the handleFileDownload function call, fileUrl is being passed, which may not correspond to the current file in the loop. Ensure that the correct file is being downloaded for each item.

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

817-837: ⚠️ Potential issue

Prevent potential infinite re-rendering

The useEffect hook depends on errorsType, and inside the effect, you update state variables that could trigger errorsType changes, potentially causing infinite re-renders.

Ensure that state updates within useEffect do not cause unintended loops:

817
useEffect(() => {
  const fetchData = async () => {
    if (!errorsType[type] && uploadedFile?.length > 0 && !isSuccess) {
      // existing code...
+     // Add a condition to prevent unnecessary state updates
+     if (!isError) {
        setIsError(true);
+     }
      // existing code...
    }
  };
  fetchData();
}, [errorsType]);

Likely invalid or redundant comment.

}
}
} catch (error) {
console.log(error);
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 console.error instead of console.log for error logging

Using console.error provides better visibility for errors in the console and differentiates error messages from regular logs.

Apply this change to improve error logging:

759
- console.log(error);
+ console.error("Error while validating Excel file:", error);
📝 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(error);
console.error("Error while validating Excel file:", error);

ashish-egov and others added 2 commits September 30, 2024 11:11
…lan/src/hooks/useGenerateIdCampaign.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
…lan/src/utils/downloadExcel.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@@ -94,6 +94,22 @@ const SetupMicroplan = ({ hierarchyType, hierarchyData }) => {
setMicroplanConfig(MicroplanConfig(params, null, isSubmitting, null, hierarchyData));
}, [totalFormData, isSubmitting]);

useEffect(() => {
const handleCheckingEvent = () => {
console.log("Checking event triggered");
Copy link
Contributor

Choose a reason for hiding this comment

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

remove logs

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 70aab30 and bcce31b.

⛔ Files ignored due to path filters (3)
  • micro-ui/web/micro-ui-internals/packages/react-components/package.json is excluded by !**/*.json
  • micro-ui/web/workbench/package-lock.json is excluded by !**/package-lock.json, !**/*.json
  • micro-ui/web/workbench/package.json is excluded by !**/*.json
📒 Files selected for processing (6)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/Module.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UploadDataCustom.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/configs/SetupMicroplanConfig.js (7 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/useGenerateIdCampaign.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/SetupMicroplan.js (4 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/utils/downloadExcel.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/Module.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

📓 Learnings (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/useGenerateIdCampaign.js (1)
Learnt from: ashish-egov
PR: egovernments/DIGIT-Frontend#1441
File: health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/useGenerateIdCampaign.js:1-1
Timestamp: 2024-09-30T05:45:14.549Z
Learning: In the `useGenerateIdCampaign` function, auto assignment of default parameter values is needed in parameter destructuring.
🪛 Biome
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UploadDataCustom.js

[error] 138-138: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 188-188: Unsafe usage of optional chaining.

If it short-circuits with 'undefined' the evaluation will throw TypeError here:

(lint/correctness/noUnsafeOptionalChaining)


[error] 205-205: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

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

[error] 156-156: This property value named key is later overwritten by an object member with the same name.

Overwritten with this value.

If an object property with the same name is defined multiple times (except when combining a getter with a setter), only the last definition makes it into the object and previous definitions are ignored.
Unsafe fix: Remove this property value named key

(lint/suspicious/noDuplicateObjectKeys)


[error] 181-184: This property value named populators is later overwritten by an object member with the same name.

Overwritten with this value.

If an object property with the same name is defined multiple times (except when combining a getter with a setter), only the last definition makes it into the object and previous definitions are ignored.
Unsafe fix: Remove this property value named populators

(lint/suspicious/noDuplicateObjectKeys)

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

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

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

(lint/style/useNumberNamespace)

🔇 Additional comments (5)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/useGenerateIdCampaign.js (1)

Line range hint 1-26: Overall, the changes look good with minor suggestions for improvement.

The implementation of the source parameter is correct and maintains backward compatibility. The suggestions provided are mainly for consistency with coding preferences and improved readability. Great job on extending the functionality of the useGenerateIdCampaign hook!

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/Module.js (2)

13-13: LGTM: Import statement for UploadDataCustom is correct.

The import statement for the new UploadDataCustom component is syntactically correct and follows the expected project structure.


13-13: Summary: UploadDataCustom component successfully integrated.

The changes in this file successfully integrate the new UploadDataCustom component into the Microplan module. The component is properly imported and registered, allowing it to be used within the Digit framework. These changes enhance the module's functionality by introducing custom upload capabilities.

To ensure a smooth integration:

  1. Verify that the UploadDataCustom component is fully implemented and tested.
  2. Update any relevant documentation to reflect the new upload functionality.
  3. Consider adding unit tests for the new component if not already present.

Also applies to: 63-63

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

17-17: LGTM: New import statement added.

The new import statement for additional UI components from "@egovernments/digit-ui-components" is correctly formatted and likely supports the updated component functionality.

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

97-125: Previous comment about 'stepCount' and 'key' inconsistencies still applies

The issues regarding inconsistent stepCount and key values, as mentioned in the previous review comment, are still present. Please refer to the prior feedback to resolve these inconsistencies.

Comment on lines 97 to 109
useEffect(() => {
const handleCheckingEvent = () => {
console.log("Checking event triggered");
const newKey = parseInt(new URLSearchParams(window.location.search).get("key")) || 1;
setCurrentKey(newKey);
};

window.addEventListener("checking", handleCheckingEvent);

return () => {
window.removeEventListener("checking", handleCheckingEvent);
};
}, []);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring the custom event handling

The new effect adds a custom "checking" event listener to update the currentKey state based on URL changes. While this approach works, there are a few points to consider:

  1. The use of a custom "checking" event is unconventional. Consider using a more standard approach, such as the useLocation hook from react-router-dom to listen for URL changes.

  2. Remove the console.log statement before deploying to production.

  3. When using parseInt, it's best practice to provide a radix parameter to ensure consistent behavior across different environments.

Consider refactoring the effect as follows:

import { useLocation } from 'react-router-dom';

// ... other imports and code

const location = useLocation();

useEffect(() => {
  const searchParams = new URLSearchParams(location.search);
  const newKey = Number.parseInt(searchParams.get("key"), 10) || 1;
  setCurrentKey(newKey);
}, [location]);

This approach eliminates the need for a custom event, removes the console.log, and uses Number.parseInt with a radix for better consistency.

🧰 Tools
🪛 Biome

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

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

(lint/style/useNumberNamespace)

{ schemaCode: "HCM-ADMIN-CONSOLE.adminSchema" }
);

console.log(Schemas, " ssssssssssssssssssssssssssssss")
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)

Avoid using console.log statements in production code

The console.log statement on line 53 appears to be leftover from debugging. It's recommended to remove it to clean up the code.

Apply this diff to remove the console.log statement:

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

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

🧹 Outside diff range comments (3)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js (3)

Line range hint 54-97: LGTM! Improved variable declaration and error handling.

The changes in the CreateResource function look good. The campaignObject is now correctly defined without redeclaration, and the error handling has been improved to provide more specific error messages.

A minor suggestion for further improvement:

Consider using optional chaining for nested object properties to make the code more robust. For example:

if (campaignRes?.CampaignDetails?.id && planRes?.PlanConfiguration?.[0]?.id) {
  // ...
}

Line range hint 160-179: LGTM! Improved flow control and error handling.

The changes in the CAMPAIGN_DETAILS and MICROPLAN_DETAILS cases of the createUpdatePlanProject function look good. The flow control has been improved, and error handling with user feedback has been added using setShowToast.

A minor suggestion for improvement:

Consider adding more specific error messages for different failure scenarios. For example:

if (!isResourceNameValid) {
  setShowToast({ key: "error", label: "ERROR_MICROPLAN_NAME_ALREADY_EXISTS" });
  return;
}

const isResourceCreated = await CreateResource(req);
if (!isResourceCreated) {
  setShowToast({ key: "error", label: "ERROR_CREATING_MICROPLAN" });
  return;
}

This will provide more informative feedback to the user about what went wrong.

🧰 Tools
🪛 Biome

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

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


Line range hint 179-205: LGTM with suggestions for improvement.

The changes in the BOUNDARY case of the createUpdatePlanProject function look good overall. The plan update logic has been improved with proper error handling and user feedback.

However, there are a couple of points that need attention:

  1. The startDate is hardcoded to 100 days from now. This might not be the intended behavior and could lead to unexpected results. Consider making this configurable or using a value from the totalFormData.

  2. The error handling for the plan update could be more specific. Instead of a generic "ERR_BOUNDARY_UPDATE" message, consider providing more detailed error information.

Suggested improvements:

const updatedCampaignObject = {
  ...campaignObject,
  boundaries: totalFormData?.BOUNDARY?.boundarySelection?.selectedData,
  startDate: totalFormData?.CAMPAIGN_DETAILS?.startDate || Math.floor(new Date().setDate(new Date().getDate() + 100))
};

const planRes = await updatePlan(updatedCampaignObject);
if (planRes?.CampaignDetails?.id) {
  setCurrentKey((prev) => prev + 1);
  setCurrentStep((prev) => prev + 1);
  return { triggeredFrom };
} else {
  setShowToast({ key: "error", label: `ERR_BOUNDARY_UPDATE: ${planRes?.error || 'Unknown error'}` });
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between bcce31b and b720036.

📒 Files selected for processing (4)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UploadDataCustom.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/configs/SetupMicroplanConfig.js (7 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/hooks/services/createUpdatePlanProject.js (6 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/SetupMicroplan.js (5 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UploadDataCustom.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

🪛 Biome
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UploadDataCustom.js

[error] 134-134: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 182-182: Unsafe usage of optional chaining.

If it short-circuits with 'undefined' the evaluation will throw TypeError here:

(lint/correctness/noUnsafeOptionalChaining)


[error] 199-199: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

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

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

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

(lint/style/useNumberNamespace)


[error] 249-254: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'const' instead.

(lint/style/noVar)

🔇 Additional comments (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/configs/SetupMicroplanConfig.js (1)

151-177: Inconsistent stepCount and key values may affect navigation flow

The stepCount and key values in the steps starting at lines 151 and 179 are inconsistent:

  • The stepCount "5" is used for both steps at lines 151 and 179.
  • The key values are not sequential: "6" and "7" for the same stepCount.
  • Both steps have the name "UPLOADDATA".

This inconsistency can lead to issues in the navigation flow and rendering of the steps in the UI. Please review and ensure that stepCount and key values are sequential and unique.

Also applies to: 179-199

ashish-egov and others added 3 commits October 7, 2024 14:19
…lan/src/components/UploadDataCustom.js

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 14

🧹 Outside diff range comments (5)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/UploadData.js (3)

Line range hint 82-86: Ensure proper dependency array for useEffect.

The useEffect hook correctly updates key and currentStep based on currentKey. However, the dependency array is missing setKey and setCurrentStep. While React guarantees the stability of setState functions, it's a good practice to include all variables used within the effect in the dependency array.

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

This change ensures that the effect runs when any of its dependencies change, preventing potential stale closure issues.


Line range hint 240-244: Good addition of inactive facility filtering.

The new filterByUpdateFlag function is a good addition that filters out properties marked for update. This is applied to the headers for boundary, facility, and user data. This change improves the data processing by ensuring only relevant fields are considered.

However, consider adding a comment explaining the purpose of this filtering, as it might not be immediately clear to other developers why certain properties are being excluded.

// Filter out properties marked for update to prevent unintended modifications
const filterByUpdateFlag = (schemaProperties) => {
  return Object.keys(schemaProperties).filter(
    (key) => schemaProperties[key].isUpdate !== true
  );
};

This addition will help maintain code clarity and assist future developers in understanding the purpose of this filtering.


Line range hint 1-1193: Overall, good improvements with some refactoring opportunities.

The changes to the UploadData component generally improve its functionality and structure. Key improvements include better handling of different data types, enhanced UI with the addition of a Stepper component, and more robust error handling.

However, there are several opportunities for further refactoring to enhance readability and maintainability:

  1. Consider combining related state variables into objects.
  2. Ensure all useEffect hooks have proper dependency arrays.
  3. Simplify complex conditional logic using lookup objects or separate functions.
  4. Address the empty catch block in the error handling section.
  5. Extract complex JSX structures into separate components or functions.

These refactoring suggestions will make the code more maintainable and easier to understand for future developers working on this component.

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

Line range hint 31-36: Fix the destructuring assignment in the fetch function

The destructuring assignment in the fetch function may not correctly retrieve the fileStoreIds from the response. The line:

const { data: { fileStoreIds: fileUrl } = {} } = await Digit.UploadServices.Filefetch([fileData?.[0]?.filestoreId], tenantId);

is attempting to rename fileStoreIds to fileUrl, which can lead to fileUrl being undefined and cause issues in the subsequent code.

Please adjust the code to correctly extract the file URL from the response. For example:

const response = await Digit.UploadServices.Filefetch([fileData?.[0]?.filestoreId], tenantId);
const fileStoreIds = response?.data?.fileStoreIds;
const temp = fileData?.map((i) => ({
  ...i,
  url: fileStoreIds?.[i.filestoreId]?.url,
}));
setFileUrl(temp?.[0]);

Line range hint 69-72: Reinstate Excel file validation in the handleChange function

In the handleChange function, the call to validateExcel is commented out:

// await validateExcel(newFiles[0]);

As a result, Excel files are no longer being validated before submission. This might lead to invalid or incorrect files being processed, which could cause downstream issues.

Please consider enabling the Excel validation or ensure that file validation is handled appropriately elsewhere. If the validation is intentionally skipped, please confirm that it's safe to proceed without it.

To re-enable validation, uncomment the line:

await validateExcel(newFiles[0]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between b720036 and b30cc19.

📒 Files selected for processing (8)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js (5 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/BulkUpload.js (2 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/UploadData.js (9 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/index.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/index.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UploadDataCustom.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/configs/SetupMicroplanConfig.js (5 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/SetupMicroplan.js (4 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

🪛 Biome
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/UploadDataCustom.js

[error] 132-132: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 180-180: Unsafe usage of optional chaining.

If it short-circuits with 'undefined' the evaluation will throw TypeError here:

(lint/correctness/noUnsafeOptionalChaining)


[error] 197-197: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

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

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

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

(lint/style/useNumberNamespace)

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

4-4: LGTM: Default export updated to include downloadExcelWithCustomName

The change to include downloadExcelWithCustomName in the default export is a good improvement. It consolidates the exports and makes it easier for other modules to import and use this function.

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

49-49: LGTM: Minor formatting improvement

The added space before the closing curly brace in the sample method improves code readability by following a consistent formatting style.


54-56: Clarify the purpose of the new campaign property in Utils

The addition of the campaign property to the Utils object, which spreads the properties of the existing utils object, raises a few concerns:

  1. Potential naming conflicts: If there are overlapping property names between utils and other properties of Utils, this could lead to unexpected behavior.
  2. Redundancy: The workbench property already includes the same spread of utils. What's the specific need for a separate campaign property?
  3. Scope and intention: It's unclear why campaign-related utilities are being added to the general Utils object rather than being kept separate in the campaign object defined earlier in the file.

Could you please clarify the reasoning behind this addition and confirm that it doesn't introduce any conflicts or redundancies?

To check for potential naming conflicts, you can run the following script:

This script will help identify any overlapping property names between the Utils object and the imported utils object.

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

36-36: LGTM: Import statement formatting improved

The formatting change in the import statement for CreateChecklist improves code readability and consistency with other import statements in the file. This is a good practice for maintaining clean and uniform code.


Line range hint 1-185: Overall assessment: Changes improve code quality and introduce new functionality

The modifications in this file primarily focus on:

  1. Improving code formatting and consistency
  2. Introducing a new XlsPreview component

These changes enhance the module's functionality and maintain good coding practices. The new XlsPreview component adds Excel preview capabilities, which could be a valuable feature for the campaign manager module.

To ensure the changes are fully integrated:

  1. Verify that the XlsPreview component is properly implemented and tested in its source file.
  2. Check if any documentation needs to be updated to reflect the new XlsPreview functionality.
  3. Confirm that the XlsPreview component is used correctly in other parts of the codebase where Excel preview functionality is required.

119-119: Component registration updates look good

  1. The formatting change for CreateQuestion improves consistency with other entries in the componentsToRegister object.
  2. The addition of XlsPreview to componentsToRegister is consistent with the new import and ensures the component is properly registered for use within the module.

These changes enhance code readability and correctly integrate the new XlsPreview component.

Let's verify the XlsPreview component's registration:

#!/bin/bash
# Search for XlsPreview in the componentsToRegister object
rg --type js 'componentsToRegister\s*=\s*\{[\s\S]*XlsPreview' health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js

Also applies to: 129-129


48-48: New XlsPreview component imported

The addition of the XlsPreview import suggests a new feature for Excel preview functionality. This is a good addition that likely enhances the module's capabilities.

To ensure proper integration, let's verify the usage of this new component:

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

27-27: Verify that XlsPreview is correctly registered in the Component Registry

The dynamic retrieval of XlsPreview using Digit?.ComponentRegistryService?.getComponent("XlsPreview") assumes that XlsPreview has been registered in the Component Registry. Please verify that XlsPreview is properly registered to avoid runtime errors.

Run the following script to confirm the registration of XlsPreview:

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

97-109: Consider refactoring the custom event handling

As previously noted, the use of the custom "checking" event listener is unconventional. Consider using the useLocation hook from react-router-dom to listen for URL changes. This approach promotes better integration with React Router and avoids the need for custom events.

🧰 Tools
🪛 Biome

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

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

(lint/style/useNumberNamespace)


135-135: 🧹 Nitpick (assertive)

Unnecessary parentheses in setShowToast call

The setShowToast function is invoked with extra parentheses around the object argument. This is unnecessary and may cause confusion. Consider removing the outer parentheses for clarity.

Apply this diff to fix the issue:

-setShowToast(({ key: "error", label: error?.message ? error.message : t("FAILED_TO_UPDATE_RESOURCE") }))
+setShowToast({ key: "error", label: error?.message ? error.message : t("FAILED_TO_UPDATE_RESOURCE") })

Likely invalid or redundant comment.

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