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

Added Clear Image functionality #9157

Open
wants to merge 13 commits into
base: develop
Choose a base branch
from

Conversation

nithish1018
Copy link
Contributor

@nithish1018 nithish1018 commented Nov 19, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Introduced a file removal option, allowing users to clear selected files easily.
    • Added a new label for report uploads, enhancing clarity in the upload process.
  • Improvements

    • Simplified the upload button logic to enable/disable based solely on file presence, enhancing user experience during file uploads.
    • Replaced the previous file upload method with a more efficient custom hook for better file management and user feedback during uploads.

@nithish1018 nithish1018 requested a review from a team as a code owner November 19, 2024 09:23
Copy link
Contributor

coderabbitai bot commented Nov 19, 2024

Walkthrough

The changes in the UpdateStatusDialog component involve the removal of several state variables related to file upload management. These have been replaced with a custom hook, useFileUpload, which handles file uploads and state management. The handleUpload function has been updated to use this hook, and the rendering logic has been adjusted accordingly. Additionally, a new option to clear selected files has been introduced, enhancing user interaction with the file upload process.

Changes

Files Change Summary
src/components/Patient/UpdateStatusDialog.tsx Removed several state variables related to file upload; integrated useFileUpload hook; updated handleUpload function; added functionality to clear selected files.
public/locale/en.json Added new key-value pair "upload_report": "Upload Report" to enhance labeling for report uploads.

Assessment against linked issues

Objective Addressed Explanation
Provide an option to clear the selected image (9153)

Possibly related PRs

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

In the meadow, where the files do play,
A button now shines, come clear it away!
With a hop and a skip, the choice is so bright,
Uploads are easy, and the future is light! 🐇✨


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

netlify bot commented Nov 19, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit ceba9fb
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6746b3f105bf5200081b9cf3
😎 Deploy Preview https://deploy-preview-9157--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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 and nitpick comments (2)
src/components/Patient/UpdateStatusDialog.tsx (2)

239-245: Enhance accessibility of the clear file button

While the implementation works, consider improving accessibility by:

  1. Adding an aria-label
  2. Including a tooltip to clarify the action
 {file && (
   <CareIcon
     icon="l-times"
     className="text-lg cursor-pointer mt-2 mr-4"
     onClick={removeFile}
+    aria-label="Clear selected file"
+    title="Clear selected file"
   />
 )}

Missing test coverage for file upload functionality

Based on the verification attempts, there appears to be no existing test coverage for the UpdateStatusDialog component. The component handles critical functionality including:

  • File upload state management
  • API integration with routes.createUpload
  • Status updates for sample tests
  • Multiple user interactions (file selection, removal, upload)

Action items:

  • Create test suite for UpdateStatusDialog component
  • Cover core scenarios:
    • File selection and removal workflow
    • Upload state transitions
    • API integration with proper mocking
    • Status update validations
    • Edge cases (upload cancellation, invalid files)
🔗 Analysis chain

Line range hint 157-249: Verify test coverage for the new functionality

Please ensure test coverage for:

  1. File selection and clearing workflow
  2. Upload button state transitions
  3. Edge cases (clearing during upload, multiple clear attempts)

Would you like help creating test cases for the new functionality?

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for existing test files and their coverage
fd -e test.tsx -e spec.tsx UpdateStatusDialog

Length of output: 47


Script:

#!/bin/bash
# Let's try a broader search for test files related to Patient components
fd -e test.tsx -e spec.tsx -e test.ts -e spec.ts . src/components/Patient/

# Also search for any test files containing UpdateStatusDialog
rg -l "UpdateStatusDialog" -g "*.test.*" -g "*.spec.*"

# Check the implementation details to understand testable scenarios
ast-grep --pattern 'const handleUpload = async () => { $$$ }'

Length of output: 1994


Script:

#!/bin/bash
# Let's check for any existing test setup patterns in the Patient directory
rg -l "render|describe|test|it\(" --type ts --type tsx src/components/Patient/

# Look for any mocks or test utilities that might be relevant
fd -e mock.ts -e mock.tsx -e test-utils.ts -e test-utils.tsx . src/

# Check for any existing dialog component tests as reference
rg -l "ConfirmDialog.*test" --type ts --type tsx

Length of output: 257

🧰 Tools
🪛 Biome

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 570ed1e and 662f437.

📒 Files selected for processing (1)
  • src/components/Patient/UpdateStatusDialog.tsx (2 hunks)
🧰 Additional context used
🪛 Biome
src/components/Patient/UpdateStatusDialog.tsx

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

🔇 Additional comments (1)
src/components/Patient/UpdateStatusDialog.tsx (1)

157-159: LGTM: Clear implementation of file removal functionality

The removeFile function provides a clean way to clear the selected file, directly addressing the issue #9153.

<Submit
type="submit"
onClick={handleUpload}
disabled={uploadDone}
disabled={file ? false : true}
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 19, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify the disabled prop logic

The current boolean expression can be simplified.

-  disabled={file ? false : true}
+  disabled={!file}
📝 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
disabled={file ? false : true}
disabled={!file}
🧰 Tools
🪛 Biome

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

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

Copy link
Contributor

Choose a reason for hiding this comment

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

@nithish1018 Great! Thanks for making the change.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

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

🧹 Outside diff range and nitpick comments (1)
src/components/Patient/UpdateStatusDialog.tsx (1)

157-159: Reset contentType state when clearing file

The removeFile function should also reset the contentType state to maintain consistency with the file selection logic.

 const removeFile = () => {
   setfile(undefined);
+  setcontentType("");
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 662f437 and cef5438.

📒 Files selected for processing (1)
  • src/components/Patient/UpdateStatusDialog.tsx (2 hunks)
🔇 Additional comments (1)
src/components/Patient/UpdateStatusDialog.tsx (1)

246-246: LGTM! Clean boolean expression

The simplified disabled prop logic is more readable and maintainable.

Comment on lines 239 to 245
{file && (
<CareIcon
icon="l-times"
className="text-lg cursor-pointer mt-2 mr-4"
onClick={removeFile}
/>
)}
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

Enhance accessibility for the clear file button

The clear file icon button needs accessibility improvements to help screen reader users understand its purpose.

 {file && (
   <CareIcon
     icon="l-times"
     className="text-lg cursor-pointer mt-2 mr-4"
     onClick={removeFile}
+    role="button"
+    aria-label={t("clear_file")}
+    title={t("clear_file")}
   />
 )}

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

Comment on lines 157 to 159
const removeFile = () => {
setfile(undefined);
};
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

🛠️ Refactor suggestion

Add upload state check to prevent file removal during upload

The verification reveals that uploadStarted state is properly managed in the component and is used during file uploads. However, the removeFile function currently lacks this check, which could lead to inconsistent state if a file is removed during upload.

  • Add upload state check in removeFile function to prevent file removal during active uploads
  • Consider adding proper ARIA attributes and visual feedback for better accessibility

The suggested changes in the review comment are valid and necessary:

  1. Prevent file removal during upload with the upload state check
  2. Add proper visual and accessibility attributes to the clear button
🔗 Analysis chain

Verify clear file behavior during upload

Please ensure that the clear file functionality is properly disabled when a file upload is in progress to prevent potential issues.

Consider adding an upload state check:

 const removeFile = () => {
+  if (uploadStarted) return;
   setfile(undefined);
   setcontentType("");
 };
 {file && (
   <CareIcon
     icon="l-times"
     className="text-lg cursor-pointer mt-2 mr-4"
     onClick={removeFile}
+    style={{ opacity: uploadStarted ? 0.5 : 1 }}
+    role="button"
+    aria-disabled={uploadStarted}
   />
 )}

Also applies to: 239-246

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any upload state checks before allowing file removal
rg -A 5 "uploadStarted.*removeFile|removeFile.*uploadStarted" .

Length of output: 65


Script:

#!/bin/bash
# Let's first check if uploadStarted state exists in the file
rg -A 5 "uploadStarted|setUploadStarted" src/components/Patient/UpdateStatusDialog.tsx

# Also check the component's state management
ast-grep --pattern 'const [$_] = useState<$_>($$$)'  src/components/Patient/UpdateStatusDialog.tsx

Length of output: 1590

Copy link
Member

@shivankacker shivankacker left a comment

Choose a reason for hiding this comment

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

@nithish1018 we need to migrate the entire flow to use the new useFileUpload and useFileManager hooks. Look at consent and file upload component for reference.

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 and nitpick comments (1)
src/components/Patient/UpdateStatusDialog.tsx (1)

102-110: Enhance error handling with specific messages

While the error handling is good, consider providing more specific error messages to help users understand and resolve issues.

-        Notification.Error({ msg: `Upload failed: ${fileUpload.error}` });
+        Notification.Error({
+          msg: fileUpload.error === 'FILE_SIZE_ERROR'
+            ? t('file_size_exceeded_error')
+            : fileUpload.error === 'FILE_TYPE_ERROR'
+              ? t('invalid_file_type_error')
+              : t('upload_failed_try_again')
+        });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cef5438 and 9d3de71.

📒 Files selected for processing (1)
  • src/components/Patient/UpdateStatusDialog.tsx (5 hunks)
🔇 Additional comments (3)
src/components/Patient/UpdateStatusDialog.tsx (3)

166-172: **** Previous review comment about enhancing accessibility for the clear file button is still valid.


174-179: LGTM! Upload button implementation is solid

The button's disabled state and internationalization implementation look good.


62-66: Verify allowed file extensions match requirements

The file upload configuration looks good, but please verify that the allowed file extensions match the business requirements for sample test reports.

✅ Verification successful

Let me search for more context about the file upload configurations and their requirements.


Let me check the file extension constants defined in the codebase.


File upload configuration aligns with system standards

The allowed file extensions in UpdateStatusDialog.tsx (pdf, jpg, jpeg, png) are consistent with the system's previewable file extensions defined in constants and match the configuration used in other patient-related components. These formats are suitable for sample test reports as they cover both document (PDF) and image formats commonly used in medical documentation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any other file upload configurations in the codebase
rg -A 3 "allowedExtensions.*pdf|allowedExtensions.*jpg|allowedExtensions.*jpeg|allowedExtensions.*png" .

Length of output: 686


Script:

#!/bin/bash
# Search for any documentation or comments about file upload requirements
rg -i "file.*upload.*requirement|document.*upload.*requirement|upload.*extension|file.*extension" .

# Search for any constants or configurations related to file uploads
ast-grep --pattern 'const $_ = {
  $$$
  allowedExtensions: $$$
  $$$
}'

Length of output: 3977


Script:

#!/bin/bash
# Check the file extension constants
cat src/common/constants.tsx | grep -A 10 "FILE_EXTENSIONS"

Length of output: 419

Comment on lines 25 to 26
sample: any;
handleOk: (sample: any, status: number, result: number) => void;
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 22, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace 'any' type with proper interface

Using 'any' type reduces type safety. Consider defining a proper interface for the sample parameter to maintain type safety and improve code maintainability.

-  sample: any;
-  handleOk: (sample: any, status: number, result: number) => void;
+  sample: SampleTestModel;
+  handleOk: (sample: SampleTestModel, status: number, result: number) => void;

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

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added, thank you for the suggestion

Copy link
Contributor

Choose a reason for hiding this comment

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

@nithish1018, glad to hear that the issue has been addressed!

(_/)
(^^)
(")
(")🎉


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

@nihal467
Copy link
Member

check the code rabbit suggestion

@nithish1018
Copy link
Contributor Author

check the code rabbit suggestion

Done

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

🧹 Outside diff range and nitpick comments (2)
src/components/Patient/UpdateStatusDialog.tsx (2)

64-68: Consider extracting configuration values to constants

The file upload configuration contains magic values that could be moved to constants for better maintainability.

+const ALLOWED_FILE_EXTENSIONS = ["pdf", "jpg", "jpeg", "png"] as const;
+const UPLOAD_TYPE = "SAMPLE_MANAGEMENT" as const;

 const fileUpload = useFileUpload({
-  type: "SAMPLE_MANAGEMENT",
-  allowedExtensions: ["pdf", "jpg", "jpeg", "png"],
+  type: UPLOAD_TYPE,
+  allowedExtensions: ALLOWED_FILE_EXTENSIONS,
   allowNameFallback: true,
 });

104-117: Enhance error messages for better user experience

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

 if (fileUpload.files.length > 0) {
   if (sample.id) {
     await fileUpload.handleFileUpload(sample.id);
   } else {
-    Notification.Error({ msg: "Sample ID is missing" });
+    Notification.Error({ msg: t("error_missing_sample_id") });
   }
   if (!fileUpload.error) {
-    Notification.Success({ msg: "File Uploaded Successfully" });
+    Notification.Success({ msg: t("success_file_upload") });
   } else {
     Notification.Error({ msg: `Upload failed: ${fileUpload.error}` });
   }
 } else {
-  Notification.Error({ msg: "No file selected for upload" });
+  Notification.Error({ msg: t("error_no_file_selected") });
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9d3de71 and 18ad9b5.

📒 Files selected for processing (2)
  • public/locale/en.json (1 hunks)
  • src/components/Patient/UpdateStatusDialog.tsx (5 hunks)
✅ Files skipped from review due to trivial changes (1)
  • public/locale/en.json
🔇 Additional comments (2)
src/components/Patient/UpdateStatusDialog.tsx (2)

180-185: LGTM! Upload button implementation is well done

The button implementation follows best practices with proper:

  • Disabled state management
  • Internationalization
  • Visual feedback with icon

172-178: Verify clear file functionality implementation

The implementation aligns with the PR objectives to add clear image functionality. Let's verify its usage across the codebase.

✅ Verification successful

Clear file functionality is consistently implemented across the codebase

The implementation in UpdateStatusDialog.tsx follows the established pattern used in other components:

  • FileUpload.tsx - Uses clearFiles with both button and icon variants
  • PatientConsentRecords.tsx - Implements clear functionality with a trash icon
  • All components properly utilize the useFileUpload hook and its clearFiles method
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the clear file functionality implementation
# Check for other instances where clearFiles might be used
rg -A 5 "clearFiles|useFileUpload" .

# Check for similar file upload implementations that might benefit from this pattern
ast-grep --pattern 'useFileUpload({
  $$$
})'

Length of output: 8058

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

No Option to Clear The Selected Image On Sample Test Page
3 participants