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

Implement multiple file to pdf support #9814

Conversation

DonXavierdev
Copy link
Contributor

@DonXavierdev DonXavierdev commented Jan 7, 2025

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Summary by CodeRabbit

  • New Features

    • Added ability to combine multiple image files into a single PDF during upload.
    • Introduced user feedback messages for file conversion progress and success.
    • Added a checkbox option for users to specify PDF generation when uploading multiple files.
    • Enhanced zoom functionality for viewing PDF files with adjustable scaling.
  • Bug Fixes

    • Enhanced error handling for PDF generation failures.
  • Documentation

    • Updated localization files with new keys for PDF functionality and error messages.
  • Chores

    • Added a new dependency for PDF generation.

@DonXavierdev DonXavierdev requested a review from a team as a code owner January 7, 2025 06:57
Copy link
Contributor

coderabbitai bot commented Jan 7, 2025

Walkthrough

The pull request introduces an enhancement to the file upload functionality by enabling multi-file support. A new generatePDF function is added to the useFileUpload hook, allowing multiple image files to be combined into a single PDF file during the upload process. This change simplifies the document upload workflow by automatically merging multiple files, addressing the current limitation of uploading individual pages separately.

Changes

File Change Summary
src/hooks/useFileUpload.tsx Added generatePDF method to convert multiple image files into a single PDF; updated handleFileUpload to include optional combineToPDF parameter.
package.json Added jspdf dependency (v^2.5.2) and adjusted input-otp version from ^1.4.2 to ^1.4.1.
public/locale/en.json Added new entries for "combine_files_pdf", "file_conversion_in_progress", "file_conversion_success", and error message for PDF generation failure.
src/components/Files/FilesTab.tsx Introduced isPdf state variable and modified file upload behavior to incorporate PDF generation option.
src/components/Common/FilePreviewDialog.tsx Added scale state variable for zoom functionality in file preview; updated zoom handling functions.
src/components/Common/PDFViewer.tsx Introduced scale prop to allow dynamic scaling of PDF pages.

Assessment against linked issues

Objective Addressed Explanation
Multi-file upload support [#7417]
Automatic PDF generation
Simplify document upload for non-tech-savvy users

Possibly related PRs

  • Handle overflow in File Preview #10133: The changes in the main PR, specifically the modifications to the FileUploadDialog component in src/components/Files/FilesTab.tsx, are related to the changes in the retrieved PR, which also modifies the same component but focuses on layout improvements.
  • Fix FileUploadDialog overflow | Use ShadCN component #10047: The changes in the main PR, specifically the updates to the FileUploadDialog component in FilesTab.tsx to handle PDF generation, are related to the modifications in the retrieved PR that also involve the FilesTab.tsx component, focusing on improving the file upload dialog's functionality and user interface.
  • Fix Camera Capture and Upload Workflow #10326: The changes in the main PR, specifically the modifications to the handleFileUpload function in the useFileUpload hook, are related to the updates made to the same function in the retrieved PR, which also involves changes to the useFileUpload hook.

Suggested labels

reviewed

Suggested reviewers

  • Jacobjeevan
  • rithviknishad

Poem

🐰 Hop, hop, upload with glee,
Images dance, now PDF-free!
No more pages scattered wide,
One file now, with rabbit pride! 📄✨
Merging docs has never been so neat! 🎉

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 744c10c and 0d14d62.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Test
  • GitHub Check: cypress-run (1)
  • GitHub Check: CodeQL-Build
  • GitHub Check: OSSAR-Scan

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. (Beta)
  • @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 Jan 7, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 0d14d62
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67a457dd3247ed0008db9b35
😎 Deploy Preview https://deploy-preview-9814--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.

@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Jan 7, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
src/hooks/useFileUpload.tsx (1)

Line range hint 132-146: Optimize image compression workflow

The current implementation compresses images after adding them to state, which could cause multiple re-renders. Consider compressing before updating state.

 const onFileChange = (e: ChangeEvent<HTMLInputElement>): any => {
   if (!e.target.files?.length) {
     return;
   }
   const selectedFiles = Array.from(e.target.files);
-  setFiles((prev) => [...prev, ...selectedFiles]);
+  
+  const processFiles = async () => {
+    const processedFiles = await Promise.all(
+      selectedFiles.map(async (file) => {
+        const ext = file.name.split(".")[1];
+        if (ExtImage.includes(ext)) {
+          const options = {
+            initialQuality: 0.6,
+            alwaysKeepResolution: true,
+          };
+          return imageCompression(file, options);
+        }
+        return file;
+      })
+    );
+    setFiles((prev) => [...prev, ...processedFiles]);
+  };
 
-  selectedFiles.forEach((file) => {
-    const ext: string = file.name.split(".")[1];
-    if (ExtImage.includes(ext)) {
-      const options = {
-        initialQuality: 0.6,
-        alwaysKeepResolution: true,
-      };
-      imageCompression(file, options).then((compressedFile: File) => {
-        setFiles((prev) =>
-          prev.map((f) => (f.name === file.name ? compressedFile : f)),
-        );
-      });
-    }
-  });
+  processFiles();
 };
🧰 Tools
🪛 GitHub Actions: Cypress Tests

[error] Failed to resolve import "jspdf". The module needs to be added to build.rollupOptions.external or properly installed.

🪛 GitHub Actions: Deploy Care Fe

[error] Failed to resolve import 'jspdf'. Module needs to be added to build.rollupOptions.external

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e6b2596 and fbbd353.

📒 Files selected for processing (2)
  • src/hooks/useFileUpload.tsx (3 hunks)
  • src/pages/Encounters/tabs/EncounterFilesTab.tsx (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: Cypress Tests
src/hooks/useFileUpload.tsx

[error] Failed to resolve import "jspdf". The module needs to be added to build.rollupOptions.external or properly installed.

🪛 GitHub Actions: Deploy Care Fe
src/hooks/useFileUpload.tsx

[error] Failed to resolve import 'jspdf'. Module needs to be added to build.rollupOptions.external

🔇 Additional comments (1)
src/pages/Encounters/tabs/EncounterFilesTab.tsx (1)

139-139: LGTM! Multiple file upload configuration is correctly implemented.

@@ -1,6 +1,7 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import imageCompression from "browser-image-compression";
import { t } from "i18next";
import jsPDF from "jspdf";
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

Add jspdf to build configuration

The jspdf import is causing pipeline failures. Add it to build.rollupOptions.external.

#!/bin/bash
# Verify if jspdf is properly configured in the build setup
fd -e js -e ts "vite.config" -x cat {} \; | grep -A 5 "rollupOptions"
🧰 Tools
🪛 GitHub Actions: Cypress Tests

[error] Failed to resolve import "jspdf". The module needs to be added to build.rollupOptions.external or properly installed.

🪛 GitHub Actions: Deploy Care Fe

[error] Failed to resolve import 'jspdf'. Module needs to be added to build.rollupOptions.external

Comment on lines 269 to 279
let filesToUpload = files;

if (files.length > 1) {
const pdfFile = await generatePDF(files);
if (pdfFile) {
filesToUpload = [pdfFile];
} else {
console.error("Failed to generate PDF from multiple files.");
return;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling and user feedback for multiple file uploads

The multiple file upload implementation needs better error handling and user feedback:

  1. No progress indication during PDF generation
  2. Silent failure if PDF generation fails
  3. Missing size limit checks for multiple files

Apply this enhancement:

 let filesToUpload = files;

 if (files.length > 1) {
+  const totalSize = files.reduce((sum, file) => sum + file.size, 0);
+  const MAX_TOTAL_SIZE = 50 * 1024 * 1024; // 50MB
+  if (totalSize > MAX_TOTAL_SIZE) {
+    setError(t("file_error__total_size"));
+    return;
+  }
+  setProgress(0);
   const pdfFile = await generatePDF(files);
   if (pdfFile) {
     filesToUpload = [pdfFile];
   } else {
-    console.error("Failed to generate PDF from multiple files.");
+    setError(t("file_error__pdf_generation"));
+    setProgress(null);
     return;
   }
 }

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

🧰 Tools
🪛 GitHub Actions: Cypress Tests

[error] Failed to resolve import "jspdf". The module needs to be added to build.rollupOptions.external or properly installed.

🪛 GitHub Actions: Deploy Care Fe

[error] Failed to resolve import 'jspdf'. Module needs to be added to build.rollupOptions.external

Comment on lines 547 to 552
{fileUpload.files?.map((file, index) => (
<div key={index} className="flex items-center mb-2">
<CareIcon icon="l-paperclip" className="mr-2" />
{file.name}
</div>
))}
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 multiple file upload UI/UX

The current UI for multiple files has several limitations:

  1. No file size information
  2. No way to remove individual files
  3. Single filename input is confusing for multiple files

Consider this enhanced implementation:

-{fileUpload.files?.map((file, index) => (
-  <div key={index} className="flex items-center mb-2">
-    <CareIcon icon="l-paperclip" className="mr-2" />
-    {file.name}
-  </div>
-))}
+{fileUpload.files?.map((file, index) => (
+  <div key={index} className="flex items-center justify-between mb-2 bg-white p-2 rounded">
+    <div className="flex items-center">
+      <CareIcon icon="l-paperclip" className="mr-2" />
+      <div className="flex flex-col">
+        <span className="text-sm font-medium">{file.name}</span>
+        <span className="text-xs text-gray-500">
+          {(file.size / 1024).toFixed(1)}KB
+        </span>
+      </div>
+    </div>
+    <button
+      onClick={() => fileUpload.removeFile(index)}
+      className="text-gray-500 hover:text-red-500"
+    >
+      <CareIcon icon="l-times" />
+    </button>
+  </div>
+))}

Also consider updating the filename input field to handle multiple files:

-<TextFormField
-  name="consultation_file"
-  type="text"
-  label={t("enter_file_name")}
-  id="upload-file-name"
-  required
-  value={fileUpload.fileNames[0] || ""}
-  disabled={fileUpload.uploading}
-  onChange={(e) => fileUpload.setFileName(e.value)}
-  error={fileUpload.error || undefined}
-/>
+{fileUpload.files.map((file, index) => (
+  <TextFormField
+    key={index}
+    name={`file_name_${index}`}
+    type="text"
+    label={t("enter_file_name_for", { name: file.name })}
+    id={`upload-file-name-${index}`}
+    required
+    value={fileUpload.fileNames[index] || ""}
+    disabled={fileUpload.uploading}
+    onChange={(e) => fileUpload.setFileName(e.value, index)}
+    error={fileUpload.error || undefined}
+  />
+))}

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

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

🧹 Nitpick comments (1)
package.json (1)

104-104: Consider browser-side PDF generation performance impact

Since PDF generation will happen in the browser, consider implementing the following optimizations:

  1. Add a loading state during PDF generation
  2. Use the existing browser-image-compression library to optimize images before PDF generation
  3. Consider implementing lazy loading if handling large numbers of images
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fbbd353 and f136465.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • package.json (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Test
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: CodeQL-Build
🔇 Additional comments (1)
package.json (1)

104-104: Verify jspdf version and security advisories

The addition of jspdf for PDF generation is appropriate. However, let's verify the version and check for any security advisories.

Run the following script to check the latest version and security advisories:

✅ Verification successful

✓ jspdf dependency version and security verified

The specified version ^2.5.2 is the latest available and is free from known security vulnerabilities. All previously reported issues were patched in earlier versions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for security advisories and latest versions of the jspdf library

# Check NPM for latest versions
curl -s https://registry.npmjs.org/jspdf | jq '.["dist-tags"].latest'

# Check for security advisories
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: NPM, package: "jspdf") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

Length of output: 1036

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 7, 2025
Copy link

github-actions bot commented Jan 7, 2025

👋 Hi, @DonXavierdev,
Conflicts have been detected against the base branch. Please rebase your branch against the base branch.


This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there.

@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Jan 7, 2025
Copy link
Contributor

@Jacobjeevan Jacobjeevan left a comment

Choose a reason for hiding this comment

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

Can't test this yet due to permissions being restricted with encounters (and patient files isn't merged yet), so will wait till then.

Copy link
Contributor

Choose a reason for hiding this comment

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

Should only be adding jspdf 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Even if i remove other dependencies like atob,canvg etc. When user installs using "npm install" jspdf automatically installs the necessary dependencies into the package-lock.json file. What should i do about it. @Jacobjeevan

Copy link
Contributor

@Jacobjeevan Jacobjeevan Jan 13, 2025

Choose a reason for hiding this comment

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

Even if i remove other dependencies like atob,canvg etc. When user installs using "npm install" jspdf automatically installs the necessary dependencies into the package-lock.json file. What should i do about it. @Jacobjeevan

Then it's fine (to include them) 👍 Make sure only those are affected though.

Copy link
Contributor

Choose a reason for hiding this comment

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

Not relevant to the issue 🤔

Copy link
Contributor

Choose a reason for hiding this comment

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

Same here.

@@ -238,8 +266,19 @@ export default function useFileUpload(
if (!validateFileUpload()) return;

setProgress(0);
let filesToUpload = files;

if (files.length > 1) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Hmm, right now it would combine any multi-uploads, let's not do that..instead let's add an option on FE (similar to "Upload From Device, Open Camera" etc) to trigger this.

@Jacobjeevan Jacobjeevan added the waiting for related PR a co-related detail PR is under construction label Jan 11, 2025
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

🧹 Nitpick comments (1)
package.json (1)

104-104: Consider performance implications of PDF generation

Since this library will be used for merging multiple images into a PDF:

  1. Consider implementing a maximum file size limit
  2. Add client-side image compression before PDF generation
  3. Consider showing a loading indicator during PDF generation
  4. Test with various image formats (JPEG, PNG, etc.) and sizes

The existing browser-image-compression dependency (line 40) could be utilized for image optimization before PDF generation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1c20535 and 5fe1f64.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • package.json (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules - care-ohc
  • GitHub Check: Header rules - care-ohc
  • GitHub Check: Pages changed - care-ohc
🔇 Additional comments (1)
package.json (1)

104-104: Verify jspdf version and compatibility

Please verify the jspdf version and any known issues:

✅ Verification successful

✅ jspdf version is appropriate and secure

The specified version (^2.5.2) is the latest available and has no known security vulnerabilities. All previously reported issues were patched in earlier versions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check latest version and security advisories for jspdf

# Get latest version from npm
echo "Latest version from npm:"
npm view jspdf version

# Check for security advisories
echo -e "\nSecurity advisories:"
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: NPM, package: "jspdf") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

Length of output: 1103

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

♻️ Duplicate comments (3)
src/hooks/useFileUpload.tsx (2)

4-4: ⚠️ Potential issue

Enhance PDF generation robustness and error handling

The PDF generation implementation needs improvements in several areas:

  1. No validation of file types before processing
  2. Hard-coded image dimensions (190, 0) may cause image distortion
  3. No progress indication during PDF generation
  4. Basic error handling without specific error messages

Previous review suggestions for improving the implementation are still valid. Additionally:

  1. Add file type validation before processing
  2. Consider memory usage for large files
  3. Add progress indication during PDF generation
  4. Improve error handling with specific error messages

Also applies to: 101-127


265-275: ⚠️ Potential issue

Improve error handling and user feedback for multiple file uploads

The multiple file upload implementation needs better error handling and user feedback:

  1. No size limit checks for multiple files
  2. Silent failure if PDF generation fails
  3. No progress indication during PDF generation

Previous review suggestions for improving error handling and user feedback are still valid.

src/pages/Encounters/tabs/EncounterFilesTab.tsx (1)

547-552: 🛠️ Refactor suggestion

Enhance multiple file upload UI/UX

The current UI for multiple files has several limitations:

  1. No file size information
  2. No way to remove individual files
  3. Single filename input is confusing for multiple files

Previous review suggestions for improving the UI/UX are still valid.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5fe1f64 and 5d65539.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • package.json (1 hunks)
  • src/hooks/useFileUpload.tsx (3 hunks)
  • src/pages/Encounters/tabs/EncounterFilesTab.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test
  • GitHub Check: cypress-run (1)

@@ -136,6 +136,7 @@ export const EncounterFilesTab = (props: EncounterTabProps) => {
],
allowNameFallback: false,
onUpload: () => refetch(),
multiple: true,
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

Revise the automatic PDF generation approach

As per previous feedback from Jacobjeevan, automatically combining all multi-uploads into a PDF is not the desired behavior. Instead, consider adding a separate UI option to trigger PDF generation.

Consider adding a new option in the file upload dropdown menu:

 <DropdownMenuContent
   align="end"
   className="w-[calc(100vw-2.5rem)] sm:w-full"
 >
+  <DropdownMenuItem className="flex flex-row items-center text-primary-900">
+    <button
+      onClick={() => handleCombineIntoPDF()}
+      className="flex flex-row items-center"
+    >
+      <CareIcon icon="l-file-pdf" className="mr-1" />
+      <span>{t("combine_as_pdf")}</span>
+    </button>
+  </DropdownMenuItem>

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

@nihal467
Copy link
Member

nihal467 commented Feb 4, 2025

image
Bug:

  • Some images remain unclear in the PDF preview after the merge. Consider enhancing the existing PDF preview pop-up by adding features like zoom controls to help users view the images more clearly as part of this PR.

@DonXavierdev discuss the above issue in the channel and find an optimal solution, to handle this issue

Patient URL : https://deploy-preview-9814--care-ohc.netlify.app/facility/2ac0c4a6-83fd-4b6b-8fdb-e257323fe87d/encounter/d6e50fcd-4171-45a5-ba57-98a96b1892b0/files

The issues listed below are unrelated and interconnected. we can solve them in separate PR once this PR is merged

  • Enable PDF file uploads in the file module.
  • Disable the upload button if a file name is not provided.
  • For multi-file uploads without merging, ensure all individual files have file names before enabling the upload button.

Copy link

github-actions bot commented Feb 4, 2025

Conflicts have been detected against the base branch. Please merge the base branch into your branch.
cc: @DonXavierdev

See: https://docs.ohc.network/docs/contributing#how-to-resolve-merge-conflicts

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Feb 4, 2025
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Feb 4, 2025
@DonXavierdev
Copy link
Contributor Author

@Jacobjeevan Had to remove existing compression to increase image quality. Would like to know your opinion on this.

        const options = {
          initialQuality: 0.6, // removed this 
          alwaysKeepResolution
           imageCompression(file, options).then((compressedFile: File) => {

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

🧹 Nitpick comments (3)
src/hooks/useFileUpload.tsx (1)

141-156: Add error handling for image compression.

The image compression implementation lacks error handling and progress indication.

 if (options.compress) {
+  setProgress(-1); // Show indeterminate progress
   selectedFiles.forEach((file) => {
     const ext: string = file.name.split(".")[1];
     if (ExtImage.includes(ext)) {
       const options = {
         initialQuality: 0.6,
         alwaysKeepResolution: true,
+        onProgress: (progress: number) => setProgress(progress),
       };
-      imageCompression(file, options).then((compressedFile: File) => {
+      imageCompression(file, options)
+      .then((compressedFile: File) => {
         setFiles((prev) =>
           prev.map((f) => (f.name === file.name ? compressedFile : f)),
         );
+      })
+      .catch((error) => {
+        toast.error(t("file_error__compression"));
+        setError(t("file_error__compression"));
+      })
+      .finally(() => {
+        setProgress(0);
+      });
     }
   });
 }
src/components/Files/FilesTab.tsx (2)

604-712: Improve file name input accessibility and validation.

The file name input implementation needs improvements:

  1. Missing aria-label for accessibility
  2. No validation for PDF file name format
  3. Duplicate error message display logic
 <Input
   name="file_name_0"
   type="text"
   id="upload-file-name-0"
   required
   value={fileUpload.fileNames[0] || ""}
   disabled={fileUpload.uploading}
+  aria-label={t("enter_file_name")}
+  pattern="^[a-zA-Z0-9-_\s]+\.pdf$"
   onChange={(e) => {
-    fileUpload.setFileName(e.target.value);
+    const value = e.target.value.replace(/[^a-zA-Z0-9-_\s]/g, '');
+    fileUpload.setFileName(
+      value.endsWith('.pdf') ? value : `${value}.pdf`
+    );
     fileUpload.setError(null);
   }}
   className="ml-0.5 mb-1"
 />

713-726: Add tooltip for PDF option.

The PDF checkbox needs a tooltip to explain the feature to users.

 {fileUpload.files.length > 1 && (
   <div className="flex items-center gap-2 mt-4">
-    <Checkbox
-      id="file_upload_patient"
-      checked={isPdf}
-      onCheckedChange={(checked: boolean) => setIsPdf(checked)}
-      disabled={fileUpload.uploading}
-      className="cursor-pointer"
-    />
-    <Label htmlFor="file_upload_patient" className="cursor-pointer">
-      {t("combine_files_pdf")}
-    </Label>
+    <TooltipProvider>
+      <Tooltip>
+        <TooltipTrigger>
+          <div className="flex items-center gap-2">
+            <Checkbox
+              id="file_upload_patient"
+              checked={isPdf}
+              onCheckedChange={(checked: boolean) => setIsPdf(checked)}
+              disabled={fileUpload.uploading}
+              className="cursor-pointer"
+            />
+            <Label htmlFor="file_upload_patient" className="cursor-pointer">
+              {t("combine_files_pdf")}
+            </Label>
+          </div>
+        </TooltipTrigger>
+        <TooltipContent>
+          {t("combine_files_pdf_tooltip")}
+        </TooltipContent>
+      </Tooltip>
+    </TooltipProvider>
   </div>
 )}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 73efe41 and 8ef1069.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • src/components/Files/FilesTab.tsx (5 hunks)
  • src/hooks/useFileUpload.tsx (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test
  • GitHub Check: cypress-run (1)
🔇 Additional comments (3)
src/hooks/useFileUpload.tsx (2)

4-4: Add jspdf to build configuration.

The jspdf import is causing pipeline failures. Add it to build.rollupOptions.external.


286-324: Improve PDF generation workflow.

Several issues with the current implementation:

  1. As per previous discussions, combining any multi-uploads is not the desired behavior. Add a specific UI option for PDF generation.
  2. Clearing all files on PDF generation failure is too aggressive. Consider preserving the original files.
  3. Missing progress indication during PDF generation.
src/components/Files/FilesTab.tsx (1)

580-585: LGTM! Proper cleanup of PDF state.

The handleDialogClose implementation correctly resets the PDF state when the dialog is closed.

Comment on lines +107 to +134
const generatePDF = async (files: File[]): Promise<File | null> => {
try {
toast.info(t("file_conversion_in_progress"));
const pdf = new jsPDF();
const totalFiles = files.length;

for (const [index, file] of files.entries()) {
const imgData = URL.createObjectURL(file);
pdf.addImage(imgData, "JPEG", 10, 10, 190, 0);
URL.revokeObjectURL(imgData);
if (index < files.length - 1) pdf.addPage();
const progress = Math.round(((index + 1) / totalFiles) * 100);
setProgress(progress);
}
const pdfBlob = pdf.output("blob");
const pdfFile = new File([pdfBlob], "combined.pdf", {
type: "application/pdf",
});
setProgress(0);
toast.success(t("file_conversion_success"));
return pdfFile;
} catch (error) {
toast.error(t("file_error__generate_pdf"));
setError(t("file_error__generate_pdf", { error: String(error) }));
setProgress(0);
return null;
}
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve PDF generation implementation.

The current implementation has several issues:

  1. No validation of file types before attempting PDF generation
  2. Hard-coded image dimensions may cause distortion
  3. Memory resources not properly managed
  4. Progress indication could be improved

Apply these improvements:

 const generatePDF = async (files: File[]): Promise<File | null> => {
   try {
+    if (!files.every(file => file.type.startsWith("image/"))) {
+      toast.error(t("file_error__file_type"));
+      setProgress(0);
+      return null;
+    }
     toast.info(t("file_conversion_in_progress"));
     const pdf = new jsPDF();
     const totalFiles = files.length;

     for (const [index, file] of files.entries()) {
-      const imgData = URL.createObjectURL(file);
+      const imgData = await new Promise<string>((resolve) => {
+        const reader = new FileReader();
+        reader.onload = () => resolve(reader.result as string);
+        reader.readAsDataURL(file);
+      });
+      const img = new Image();
+      await new Promise<void>((resolve) => {
+        img.onload = () => resolve();
+        img.src = imgData;
+      });
+      const aspectRatio = img.height / img.width;
+      const pageWidth = pdf.internal.pageSize.getWidth() - 20;
+      const pageHeight = pageWidth * aspectRatio;
-      pdf.addImage(imgData, "JPEG", 10, 10, 190, 0);
+      pdf.addImage(imgData, "JPEG", 10, 10, pageWidth, pageHeight);
-      URL.revokeObjectURL(imgData);
       if (index < files.length - 1) pdf.addPage();
       const progress = Math.round(((index + 1) / totalFiles) * 100);
       setProgress(progress);
     }
📝 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 generatePDF = async (files: File[]): Promise<File | null> => {
try {
toast.info(t("file_conversion_in_progress"));
const pdf = new jsPDF();
const totalFiles = files.length;
for (const [index, file] of files.entries()) {
const imgData = URL.createObjectURL(file);
pdf.addImage(imgData, "JPEG", 10, 10, 190, 0);
URL.revokeObjectURL(imgData);
if (index < files.length - 1) pdf.addPage();
const progress = Math.round(((index + 1) / totalFiles) * 100);
setProgress(progress);
}
const pdfBlob = pdf.output("blob");
const pdfFile = new File([pdfBlob], "combined.pdf", {
type: "application/pdf",
});
setProgress(0);
toast.success(t("file_conversion_success"));
return pdfFile;
} catch (error) {
toast.error(t("file_error__generate_pdf"));
setError(t("file_error__generate_pdf", { error: String(error) }));
setProgress(0);
return null;
}
};
const generatePDF = async (files: File[]): Promise<File | null> => {
try {
+ if (!files.every(file => file.type.startsWith("image/"))) {
+ toast.error(t("file_error__file_type"));
+ setProgress(0);
+ return null;
+ }
toast.info(t("file_conversion_in_progress"));
const pdf = new jsPDF();
const totalFiles = files.length;
for (const [index, file] of files.entries()) {
- const imgData = URL.createObjectURL(file);
+ const imgData = await new Promise<string>((resolve) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as string);
+ reader.readAsDataURL(file);
+ });
+ const img = new Image();
+ await new Promise<void>((resolve) => {
+ img.onload = () => resolve();
+ img.src = imgData;
+ });
+ const aspectRatio = img.height / img.width;
+ const pageWidth = pdf.internal.pageSize.getWidth() - 20;
+ const pageHeight = pageWidth * aspectRatio;
- pdf.addImage(imgData, "JPEG", 10, 10, 190, 0);
+ pdf.addImage(imgData, "JPEG", 10, 10, pageWidth, pageHeight);
- URL.revokeObjectURL(imgData);
if (index < files.length - 1) pdf.addPage();
const progress = Math.round(((index + 1) / totalFiles) * 100);
setProgress(progress);
}
const pdfBlob = pdf.output("blob");
const pdfFile = new File([pdfBlob], "combined.pdf", {
type: "application/pdf",
});
setProgress(0);
toast.success(t("file_conversion_success"));
return pdfFile;
} catch (error) {
toast.error(t("file_error__generate_pdf"));
setError(t("file_error__generate_pdf", { error: String(error) }));
setProgress(0);
return null;
}
};

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Feb 6, 2025
Copy link

github-actions bot commented Feb 6, 2025

Conflicts have been detected against the base branch. Please merge the base branch into your branch.
cc: @DonXavierdev

See: https://docs.ohc.network/docs/contributing#how-to-resolve-merge-conflicts

@nihal467
Copy link
Member

nihal467 commented Feb 6, 2025

LGTM , solve the rest of the issue earlier mention as a separate PR

@nihal467 nihal467 removed their assignment Feb 6, 2025
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Feb 6, 2025
@rithviknishad rithviknishad merged commit b928147 into ohcnetwork:develop Feb 6, 2025
14 of 15 checks passed
Copy link

github-actions bot commented Feb 6, 2025

@DonXavierdev Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

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.

File Upload enhancement- multi-file support
4 participants