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

Feature/bo val #1995

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open

Feature/bo val #1995

wants to merge 6 commits into from

Conversation

suryansh-egov
Copy link
Contributor

@suryansh-egov suryansh-egov commented Dec 9, 2024

Choose the appropriate template for your PR:

Feature PR

Feature Request

JIRA ID

Module

Description

Related Issues


Bugfix PR

Bugfix Request

JIRA ID

Module

Description

Root Cause

Related Issues


Release PR

Summary by CodeRabbit

  • New Features

    • Introduced buttons for navigating back and downloading files in the XlsPreviewNew component.
    • Added an InfoCard for displaying validation error messages in the ViewHierarchy component.
    • Implemented a new utility function for validating uploaded Excel files.
  • Bug Fixes

    • Enhanced button state logic in the BoundaryHome component to improve responsiveness based on boundary data.
  • Improvements

    • Streamlined file upload logic and validation handling in the ViewHierarchy component.

* validation from ui

* empty top rows considered

* info card added for error in place of toast

* review changes
@suryansh-egov suryansh-egov requested a review from a team as a code owner December 9, 2024 13:29
Copy link
Contributor

coderabbitai bot commented Dec 9, 2024

📝 Walkthrough

Walkthrough

The pull request includes modifications across several components related to boundary management and file handling. Key changes involve the XlsPreviewNew component, which now includes commented-out buttons for user actions and adjustments to the layout. The BoundaryHome component has updated logic for button state management based on boundary data. The ViewHierarchy component has enhanced file upload and validation functionalities, introducing new state variables and a validation utility. A new utility function for validating Excel content has also been added, streamlining data processing and error handling.

Changes

File Change Summary
.../XlsPreviewNew.js Added commented-out Button components for back navigation and downloading, modified campaign-popup-module styling, and retained the DocViewer component.
.../BoundaryHome.js Expanded the logic for disabling the "EDIT_BOUNDARY_DATA" button based on boundaryData and "CREATE_NEW_BOUNDARY_DATA" action states.
.../ViewHierarchy.js Introduced InfoCard and DustbinIcon, added state variables for file handling, modified file upload logic, and enhanced error handling and UI rendering.
.../validateBoundaryExcel.js Added validateBoundaryExcelContent function for validating Excel file content, including checks for headers and hierarchical dependencies.

Possibly related PRs

  • validation from ui #1981: This PR introduces the validateBoundaryExcelContent function, which is directly related to the changes made in the XlsPreviewNew component in the main PR, as both involve handling file uploads and validation processes.

Suggested reviewers

  • nipunarora-eGov

Poem

In the garden of code, changes bloom bright,
Buttons for actions, a delightful sight.
With validation in place, errors take flight,
A hop and a skip, everything feels right!
So let’s celebrate, with joy and cheer,
For the code is now better, let’s give a big cheer! 🐇✨


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @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: 6

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between b3c48dc and ac3a7bb.

⛔ Files ignored due to path filters (2)
  • health/micro-ui/web/micro-ui-internals/package.json is excluded by !**/*.json
  • health/micro-ui/web/workbench/package.json is excluded by !**/*.json
📒 Files selected for processing (4)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/XlsPreviewNew.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/BoundaryHome.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/ViewHierarchy.js (7 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/validateBoundaryExcel.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/validateBoundaryExcel.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

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

Pattern **/*.js: check

🪛 Biome (1.9.4)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/ViewHierarchy.js

[error] 586-586: 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] 592-592: 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] 600-600: 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 (2)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/validateBoundaryExcel.js (1)

4-69: Validation function is well implemented

The validateBoundaryExcelContent function correctly reads and validates the Excel file content, handling various edge cases effectively.

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

152-152: 🧹 Nitpick (assertive)

Remove commented-out code

The commented-out line on 152 is unnecessary and can be removed to keep the codebase clean.

Apply this diff to remove the redundant code:

- // setShowToast({ label: isValid.error, isError: "error" });

Likely invalid or redundant comment.

} catch (error) {
setShowToast({ label: error?.response?.data?.Errors?.[0]?.message ? error?.response?.data?.Errors?.[0]?.message : t("FILE_UPLOAD_FAILED") , isError:"error" });
const file = event.target.files[0]; // Get the selected file
setFileName(file.name)
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

Ensure file is defined before accessing file.name

To prevent potential runtime errors, check if file is defined before calling setFileName(file.name). This ensures that your code doesn't attempt to access properties of an undefined object.

Apply this diff to add the null check:

-   setFileName(file.name)
    if (file) {
+     setFileName(file.name);
      // rest of the code

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

jagankumar-egov and others added 3 commits December 10, 2024 09:36
…gn-manager/src/pages/employee/BoundaryHome.js

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

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
…gn-manager/src/pages/employee/ViewHierarchy.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: 1

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

Line range hint 43-43: Clean up unused state variables.

The authorized and geoPodeData states are declared but never used effectively. Consider removing them if they're not needed, or implement their intended functionality.

Also applies to: 45-45

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between ac3a7bb and f0a6c91.

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

Pattern **/*.js: check

🔇 Additional comments (1)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/BoundaryHome.js (1)

Line range hint 41-41: Implement proper error handling.

The error handling using Toast component is commented out, but the component receives an error from the useBoundaryHome hook. Consider implementing proper error handling to improve user experience.

Let's verify the error handling implementation in other boundary-related components:

Also applies to: 52-52

✅ Verification successful

Based on the search results, I can now provide a final response regarding the error handling implementation:

The error handling implementation is already properly handled in the codebase

The BoundaryHome component and its associated hook (useBoundaryHome) have proper error handling:

  1. The component receives error state from useBoundaryHome hook:
const {isLoading, data, error} = Digit.Hooks.campaign.useBoundaryHome(...)
  1. The useBoundaryHome hook properly handles and propagates errors:
  • Catches and logs errors during API calls
  • Returns error objects to the component
  • Uses React Query's error handling capabilities
  1. While there is a commented out Toast component, this is intentional as the error handling has been moved to the hook layer for better separation of concerns.

The current implementation follows React best practices by:

  • Separating data fetching and error handling logic into a custom hook
  • Using React Query for automatic error handling and retries
  • Propagating errors up to the component level for flexible error UI handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Toast usage in boundary-related components
rg -l 'Toast.*USER_NOT_AUTHORISED' packages/modules/campaign-manager/src/

Length of output: 154


Script:

#!/bin/bash
# Search for Toast usage in boundary-related files
rg -l "Toast" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/

# Search for error handling patterns in boundary-related files
rg "catch|error|Toast" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/ -A 2

# Check the implementation of useBoundaryHome hook
ast-grep --pattern 'const useBoundaryHome = () => {
  $$$
}'

Length of output: 107647


Script:

#!/bin/bash
# Search for error handling in BoundaryHome.js
rg -A 5 "error|Toast" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/BoundaryHome.js

# Check the implementation of useBoundaryHome hook
rg -A 10 "useBoundaryHome" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/

# Look for any error handling patterns in hooks directory
rg -A 5 "error|catch|throw" health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/

Length of output: 38637

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between f0a6c91 and 83f9ed5.

📒 Files selected for processing (1)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/ViewHierarchy.js (7 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/ViewHierarchy.js (1)

Pattern **/*.js: check

🪛 Biome (1.9.4)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/ViewHierarchy.js

[error] 590-591: The elements with the following roles can be changed to the following elements:

For examples and more information, see WAI-ARIA Roles

(lint/a11y/useSemanticElements)


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

133-134: ⚠️ Potential issue

Ensure file is defined before accessing file.name

There is a potential runtime error if file is undefined when accessing file.name at line 134. Please check if file is defined before accessing its properties.

Apply this diff:

-   setFileName(file.name)
    if (file) {
+     setFileName(file.name);
      // rest of the code

600-600: 🧹 Nitpick (assertive)

Use self-closing tag for JSX element without children

The <div> element on line 600 has no children and can be self-closed for brevity and consistency.

Apply this diff:

- <div style={{height:"2rem"}}></div>
+ <div style={{height:"2rem"}} />

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 83f9ed5 and 256e95f.

📒 Files selected for processing (1)
  • health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/ViewHierarchy.js (7 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/ViewHierarchy.js (1)

Pattern **/*.js: check

🪛 Biome (1.9.4)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/ViewHierarchy.js

[error] 590-591: The elements with the following roles can be changed to the following elements:

For examples and more information, see WAI-ARIA Roles

(lint/a11y/useSemanticElements)


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

586-595: 🛠️ Refactor suggestion

Use <button> element instead of <div> with role="button" for better accessibility

Using a <button> element improves semantics and accessibility over a <div> with role="button". This enhances support for assistive technologies and keyboard navigation.

Apply this diff:

       <div
         className="dustbin-icon"
         onClick={() => removeFile()}
         onKeyDown={(e) => { if (e.key === 'Enter') removeFile(); }}
         tabIndex="0"
         role="button"
         style={{ cursor: "pointer", marginTop:"1.15rem" }}
       >
+      <button
+        className="dustbin-icon"
+        onClick={() => removeFile()}
+        style={{ cursor: "pointer", marginTop:"1.15rem", background: "none", border: "none", padding: 0 }}
+      >
         <DustbinIcon />
-      </div>
+      </button>
🧰 Tools
🪛 Biome (1.9.4)

[error] 590-591: The elements with the following roles can be changed to the following elements:

For examples and more information, see WAI-ARIA Roles

(lint/a11y/useSemanticElements)


600-600: 🧹 Nitpick (assertive)

Use self-closing tag for JSX element without children

The <div> element on line 600 has no children and can be self-closed for cleaner code.

Apply this diff:

-<div style={{height:"2rem"}}></div>
+<div style={{height:"2rem"}} />

// Parse the file and validate its content
const isValid = await validateBoundaryExcelContent(file, t);
if (!isValid.success) {
// setShowToast({ label: isValid.error, isError: "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)

Remove commented-out code to maintain code cleanliness

The line // setShowToast({ label: isValid.error, isError: "error" }); is commented out. Consider removing it to keep the code clean and avoid confusion.

Comment on lines +137 to +145
const validExtensions = ['xls', 'xlsx'];
const fileExtension = file.name.split('.').pop().toLowerCase(); // Get the file extension

if (!validExtensions.includes(fileExtension)) {
setShowToast({ label: t("INVALID_FILE_FORMAT"), isError: "error" });
setDisableFile(true);
event.target.value = "";
return; // Exit the function if the file is not valid
}
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

Enhance file validation to prevent security issues

Relying solely on file extensions for validation can be insecure, as file extensions can be manipulated. It's recommended to validate the file's MIME type to ensure that the uploaded file is indeed an Excel file.

Apply this diff to improve file validation:

 const validExtensions = ['xls', 'xlsx'];
 const fileExtension = file.name.split('.').pop().toLowerCase(); // Get the file extension

+ const validMimeTypes = [
+   'application/vnd.ms-excel',
+   'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
+ ];
+ if (!validMimeTypes.includes(file.type)) {
+   setShowToast({ label: t("INVALID_FILE_TYPE"), isError: "error" });
+   setDisableFile(true);
+   event.target.value = "";
+   return; // Exit the function if the file is not valid
+ } else

 if (!validExtensions.includes(fileExtension)) {
   setShowToast({ label: t("INVALID_FILE_FORMAT"), isError: "error" });
   setDisableFile(true);
   event.target.value = "";
   return; // Exit the function if the file is not valid
 }
📝 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 validExtensions = ['xls', 'xlsx'];
const fileExtension = file.name.split('.').pop().toLowerCase(); // Get the file extension
if (!validExtensions.includes(fileExtension)) {
setShowToast({ label: t("INVALID_FILE_FORMAT"), isError: "error" });
setDisableFile(true);
event.target.value = "";
return; // Exit the function if the file is not valid
}
const validExtensions = ['xls', 'xlsx'];
const fileExtension = file.name.split('.').pop().toLowerCase(); // Get the file extension
const validMimeTypes = [
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
];
if (!validMimeTypes.includes(file.type)) {
setShowToast({ label: t("INVALID_FILE_TYPE"), isError: "error" });
setDisableFile(true);
event.target.value = "";
return; // Exit the function if the file is not valid
} else
if (!validExtensions.includes(fileExtension)) {
setShowToast({ label: t("INVALID_FILE_FORMAT"), isError: "error" });
setDisableFile(true);
event.target.value = "";
return; // Exit the function if the file is not valid
}

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