Skip to content

Conversation

@aimensahnoun
Copy link
Member

@aimensahnoun aimensahnoun commented Feb 20, 2025

Resolves #64

Updates:

  • Use npm package instead of loading cdn everytime
  • Use same HTML format as the web-components
  • Add retries and proper cleanup

Example:

CleanShot 2025-02-20 at 13 24 19

Summary by CodeRabbit

  • New Features

    • Enhanced PDF export functionality with robust error handling and a retry system, ensuring a smoother invoice generation process.
    • Updated PDF layout with refined styling, including a refreshed design and sanitized invoice identifiers for improved presentation.
  • Chores

    • Integrated an additional dependency to support the advanced PDF export enhancements.

@aimensahnoun aimensahnoun self-assigned this Feb 20, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 20, 2025

Walkthrough

This pull request introduces a new dependency (html2pdf.js) in package.json and significantly updates the PDF export functionality in the useExportPDF hook. The modifications include removing dynamic script loading in favor of direct import, enhancing the PDF generation process with error handling and a retry mechanism, and using BigInt for precise financial calculations. Additionally, the HTML structure for the generated PDF is refined with style changes, a new logo, and filename sanitization.

Changes

File(s) Change Summary
package.json Added new dependency "html2pdf.js": "^0.10.2" in the dependencies section.
src/lib/hooks/use-export-pdf.tsx Removed dynamic loading of html2pdf.js and imported it directly. Added error handling, a retry mechanism (using TIMEOUT_MS and MAX_RETRIES), used BigInt in calculations, restructured PDF generation into a nested generatePDF function, and updated the HTML structure (including logo and sanitized invoice number).

Sequence Diagram(s)

sequenceDiagram
    participant UI as User/UI
    participant Hook as useExportPDF
    participant Generator as generatePDF
    participant Library as html2pdf.js

    UI->>Hook: Call exportPDF
    Hook->>Generator: Initiate PDF generation
    Generator->>Library: Generate PDF from HTML content
    Library-->>Generator: Return PDF (or error)
    alt Success
        Generator->>Hook: Deliver generated PDF
        Hook->>UI: Return PDF file
    else Error
        Generator->>Hook: Report error
        Hook->>Hook: Log error and check retry count
        loop Retry Attempts (if < MAX_RETRIES)
            Hook->>Library: Retry PDF generation
        end
        Hook->>UI: Return final PDF or error after retries
    end
Loading

Possibly related PRs

Suggested reviewers

  • MantisClone
  • sstefdev

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
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 (5)
src/lib/hooks/use-export-pdf.tsx (5)

4-8: Prefer using import type for type-only imports.

Static analysis indicates that some imported symbols (e.g., Invoice, InvoiceItem, PaymentData) are used exclusively as types. Converting these imports to import type can help reduce bundle size and enhance clarity in type usage.

Here is a recommended diff:

-import { Invoice, InvoiceItem } from "@requestnetwork/data-format";
-import { PaymentData } from "../types";
+import type { Invoice, InvoiceItem } from "@requestnetwork/data-format";
+import type { PaymentData } from "../types";
🧰 Tools
🪛 Biome (1.9.4)

[error] 4-4: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)


[error] 8-8: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)


17-20: Adjust configuration constants for maintainability.

TIMEOUT_MS and MAX_RETRIES are magic numbers that might need fine-tuning across environments. Consider exposing them either via config files, environment variables, or top-level constants to make them more discoverable and consistent across the codebase.


21-23: Ensure locale consistency in date formatting.

new Date(date).toLocaleDateString() may behave differently across regions or servers. Consider specifying a locale or format string for more stable, predictable output (for example, 'en-GB', 'en-US', or a configuration-based approach).


34-52: Verify negative or zero price handling.

Using BigInt to compute item totals is robust, but caution is needed if:

  1. unitPrice < discount, making priceAfterDiscount negative.
  2. quantity is 0.
    Handle these edge cases explicitly to avoid surprises in final invoice totals.

68-320: Review robust error handling and confirm cross-browser PDF rendering.

  1. Potential SSR usage: Since this is a Next.js codebase, ensure use client suffices and calls to window.location.origin won't unexpectedly break in SSR contexts.
  2. Error-handling logic: You have a retry mechanism; ensure that repeated await sleep(1000) plus a final throw meets user experience requirements under ephemeral or network-limited conditions.
  3. DOM cleanup: The finally block ensures containers are removed—good practice. Make sure there's no concurrency scenario where multiple exports overlap in the DOM.
  4. Large intangible overhead: The entire HTML string is kept in memory. Consider streaming or partial rendering if the invoice is extremely large.

Overall, the approach is sound; just confirm these advanced scenarios are tested and validated.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 43f48fb and 7e65e19.

⛔ Files ignored due to path filters (2)
  • package-lock.json is excluded by !**/package-lock.json
  • public/logo-1.png is excluded by !**/*.png
📒 Files selected for processing (2)
  • package.json (1 hunks)
  • src/lib/hooks/use-export-pdf.tsx (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/lib/hooks/use-export-pdf.tsx

[error] 4-4: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)


[error] 8-8: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

🔇 Additional comments (3)
src/lib/hooks/use-export-pdf.tsx (2)

25-32: Validate currency details fallback.

When isAddress(currency) or currencyManager.fromSymbol(currency) returns undefined, this function currently returns undefined. Downstream consumers may not handle undefined gracefully. Consider providing fallback behavior or throwing an error if the currency is unknown.


54-66: Log formatBigIntAmount fallback usage.

When an error occurs, you return "0" and suppress the exception, which might mask data issues. Consider more detailed logging or surfacing warnings to ensure that unexpected failures in large numeric conversions are not silently dismissed.

package.json (1)

31-31: Confirm html2pdf.js version and check for known vulnerabilities.

Adding "html2pdf.js": "^0.10.2" improves the flow by removing dynamic script loading, but confirm that this version is stable and has no reported security flaws. Reviewing release notes or security advisories is advisable before finalizing.

@aimensahnoun aimensahnoun merged commit 86ee305 into main Feb 20, 2025
2 checks passed
@aimensahnoun aimensahnoun deleted the 64-update-request-scan-to-use-the-same-html-for-pdf-as-web-components-currently-pdf-is-cut-off-only-top-half-rendered branch February 20, 2025 12:32
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.

Update Request Scan to use the same html for PDF as web components. Currently, PDF is "cut off", only top half rendered

3 participants