Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@ColeGN
Copy link
Collaborator

@ColeGN ColeGN commented Jul 18, 2025

ISSUE

Context

Your context here. Additionally, any screenshots. Delete this line.

// Delete the below section once completed

PR Checklist

  • Description is clearly stated under Context section
  • Screenshots and the additional verifications are attached

Summary by Sourcery

Implement printing of a payment supplement by collecting user information in a modal form and generating a styled print document from the checkout payment type component.

New Features:

  • Add a "Нэхэмжлэх" button to SelectPaymentTypeMain that opens a user info form modal before printing.
  • Introduce UserInfoForm component to capture account type, name, company registration (if applicable), and bank address.
  • Create PrintableSupplement and UserInfo components to render a formatted invoice-like document for printing.

Enhancements:

  • Add Jotai atoms (userNameAtom, userBankAddressAtom, accountTypeAtom, companyRegisterAtom, printModalOpenAtom) to store and manage user details and print state.
  • Integrate print logic in SelectPaymentTypeMain to open a new window, inject styled HTML with user data, and trigger the browser print dialog.

Important

Add functionality to print payment supplements by collecting user information and generating a styled document.

  • New Features:
    • Add UserInfoForm component to collect user details for invoice printing.
    • Add PrintableSupplement component to render invoice information for printing.
    • Add InvoiceInfo component to display formatted invoice details.
    • Add useInvoicePrintSupplement hook to manage print operations.
    • Add usePaymentStates hook to manage payment state transitions.
  • Enhancements:
    • Update SelectPaymentTypeMain to include a "Нэхэмжлэх" button for printing invoices.
    • Add Jotai atoms (userNameAtom, userBankAddressAtom, etc.) to store user information.
    • Add print styles in useInvoicePrintStyles for consistent document formatting.
  • Misc:
    • Remove catProdMappings prop from ConfigStep and Pos components.
    • Update PaymentsStep to include printInvoice configuration option.

This description was created by Ellipsis for 94b67ca. You can customize this summary. It will automatically update as commits are pushed.


Summary by CodeRabbit

  • New Features

    • Added the ability to print invoice supplements directly from the payment selection screen.
    • Introduced a user information form for invoice payments, supporting both personal and company accounts.
    • Enhanced invoice details display, including payment deadlines and itemized order summaries.
    • Provided customizable print styles for invoices and supplements.
    • Implemented a print workflow with modal prompts and error handling for invoice printing.
  • Improvements

    • Streamlined the payment type selection interface, integrating print options where applicable.
    • Persisted user and company information for invoices for a smoother checkout experience.
  • Bug Fixes

    • Improved error handling and feedback during the printing process.

@sourcery-ai
Copy link

sourcery-ai bot commented Jul 18, 2025

Reviewer's Guide

Implements a payment supplement print flow by refactoring the checkout component to include a user info modal, print preview, and new global atoms for state management.

Entity relationship diagram for new global atoms in store

erDiagram
    userNameAtom ||--o{ UserInfoForm : "used by"
    userBankAddressAtom ||--o{ UserInfoForm : "used by"
    accountTypeAtom ||--o{ UserInfoForm : "used by"
    companyRegisterAtom ||--o{ UserInfoForm : "used by"
    printModalOpenAtom ||--o{ SelectPaymentTypeMain : "used by"
    UserInfoForm {
      string userName
      string userBankAddress
      string accountType
      string companyRegister
    }
    SelectPaymentTypeMain {
      boolean printModalOpen
    }
Loading

Class diagram for new and updated types in supplement print flow

classDiagram
    class SelectPaymentTypeMain {
      - showUserForm: boolean
      - printRef: Ref<HTMLDivElement>
      - userName: string
      - userBankAddress: string
      - setPrintOpen: function
      + handlePrint()
      + handlePrintClick()
    }
    class UserInfoForm {
      + onSubmit: () => void
      + onCancel: () => void
      - userName: string
      - userBankAddress: string
      - accountType: 'person' | 'company'
      - companyRegister: string
      + isFormValid(): boolean
    }
    class PrintableSupplement {
      + userName?: string
      + userBankAddress?: string
    }
    class UserInfo {
      - userName: string
      - userBankAddress: string
      - company: string
      - accountType: 'person' | 'company'
      - total: number
    }
    SelectPaymentTypeMain --> UserInfoForm : shows
    SelectPaymentTypeMain --> PrintableSupplement : renders
    PrintableSupplement --> UserInfo : includes
Loading

File-Level Changes

Change Details Files
Integrate print workflow into SelectPaymentTypeMain
  • Add useState and useRef hooks for modal and print control
  • Implement handlePrint to generate and print HTML in a new window
  • Provide handlePrintClick to open the user info modal
  • Embed PrintableSupplement component in a hidden container for printing
pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx
Introduce UserInfoForm modal component
  • Create form with account type selector, name, bank address, and optional company register number
  • Implement validation, onSubmit and onCancel handlers
  • Manage showUserForm state in main component to toggle visibility
pos/modules/checkout/components/paymentType/userInfoFrom.tsx
pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx
Create print layout components
  • Add PrintableSupplement with print-specific styling and document structure
  • Implement UserInfo to render user and transaction details dynamically
pos/modules/checkout/components/paymentType/supplement.tsx
pos/modules/checkout/components/paymentType/userInfo.tsx
Extend global Jotai store with new atoms
  • Define userNameAtom, userBankAddressAtom, accountTypeAtom, and companyRegisterAtom
  • Add printModalOpenAtom to track print modal visibility
pos/store/index.tsx

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link

coderabbitai bot commented Jul 18, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

This change introduces a new invoice supplement printing workflow to the checkout payment module. It adds new React components, hooks, and Jotai atoms to manage user information, print state, and invoice presentation. The update includes utility functions for print styling and template processing, and integrates the print workflow into the payment type selection UI.

Changes

Cohort / File(s) Change Summary
Payment Type UI & Print Integration
pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx, pos/modules/checkout/components/paymentType/invoiceInfo.tsx, pos/modules/checkout/components/paymentType/invoiceInfoForm.tsx, pos/modules/checkout/components/paymentType/supplement.tsx
Enhanced payment type selection to support invoice supplement printing. Added InvoiceInfo, UserInfoForm, and PrintableSupplement components for user data collection and invoice display. Integrated print logic and UI updates for the new workflow, including print lifecycle handlers and conditional rendering.
State Management (Jotai Atoms)
pos/store/index.tsx
Added new atoms for user name, bank address, account type, company registration, invoice expiry days, and print modal state to persist and manage user and invoice data.
Payment & Print State Hooks
pos/modules/checkout/hooks/usePaymentStates.tsx, pos/modules/checkout/hooks/useInvoicePrintSupplement.tsx, pos/modules/checkout/hooks/useInvoicePrintStyles.tsx
Introduced hooks to manage payment print states, handle print supplement logic including print window lifecycle, and provide print-oriented styles for invoice rendering.
Print Utility Functions
pos/modules/checkout/utils/printUtils.ts
Added utility functions for print document creation and template variable replacement, along with print-specific CSS styles for invoice formatting.
POS UI Cleanup
packages/plugin-pos-ui/src/pos/components/Pos.tsx, packages/plugin-pos-ui/src/pos/components/step/ConfigStep.tsx, packages/plugin-pos-ui/src/pos/components/productGroup/CatProdItem.tsx, packages/plugin-pos-ui/src/pos/components/step/PaymentsStep.tsx
Removed unused catProdMappings prop from ConfigStep and Pos components. Adjusted argument order in editMapping calls to ensure _id is first. Updated descriptive text in PaymentsStep to include new printInvoice flag explanation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PaymentTypeUI
    participant UserInfoForm
    participant PrintableSupplement
    participant PrintUtils

    User->>PaymentTypeUI: Selects "Invoice" payment type
    PaymentTypeUI->>UserInfoForm: Opens modal for user info
    User->>UserInfoForm: Enters info and submits
    UserInfoForm->>PaymentTypeUI: onSubmit triggers print
    PaymentTypeUI->>PrintableSupplement: Renders hidden invoice content
    PaymentTypeUI->>PrintUtils: Calls printDocument(printRef)
    PrintUtils->>User: Opens print dialog with invoice
    PrintUtils->>PaymentTypeUI: Returns print status
    PaymentTypeUI->>User: Shows success or error message
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • munkhsaikhan

Poem

A rabbit hopped into the code,
With invoices ready to print and load.
New atoms and hooks, UI so neat,
User info and supplements—what a treat!
Now checkout’s smarter, printing with flair,
Hooray for invoices—see you there!
🐇🧾✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 6608dac and 94b67ca.

📒 Files selected for processing (4)
  • packages/plugin-pos-ui/src/pos/components/Pos.tsx (0 hunks)
  • packages/plugin-pos-ui/src/pos/components/productGroup/CatProdItem.tsx (1 hunks)
  • packages/plugin-pos-ui/src/pos/components/step/ConfigStep.tsx (1 hunks)
  • packages/plugin-pos-ui/src/pos/components/step/PaymentsStep.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/plugin-pos-ui/src/pos/components/Pos.tsx
✅ Files skipped from review due to trivial changes (2)
  • packages/plugin-pos-ui/src/pos/components/step/ConfigStep.tsx
  • packages/plugin-pos-ui/src/pos/components/step/PaymentsStep.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: runtest
  • GitHub Check: pos-ui
  • GitHub Check: ui
🔇 Additional comments (2)
packages/plugin-pos-ui/src/pos/components/productGroup/CatProdItem.tsx (2)

37-37: LGTM! Property ordering ensures _id integrity.

The reordering ensures _id is explicitly set from item._id and provides more predictable object structure, even though the current state doesn't include _id.


45-45: LGTM! Consistent property ordering applied.

Same beneficial change as line 37 - ensures consistent object structure with _id explicitly positioned first.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch pos-change

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @ColeGN - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:53` </location>
<code_context>
+      if (printWindow) {
+        let printContent = printRef.current.innerHTML;
+        
+        printContent = printContent.replace(/{{userName}}/g, userName || "N/A");
+        printContent = printContent.replace(/{{userBankAddress}}/g, userBankAddress || "N/A");
+        
+        printWindow.document.write(`
</code_context>

<issue_to_address>
Template variable replacement may be redundant.

If these placeholders are not present in the HTML output, consider removing this replacement logic for clarity.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        let printContent = printRef.current.innerHTML;

        printContent = printContent.replace(/{{userName}}/g, userName || "N/A");
        printContent = printContent.replace(/{{userBankAddress}}/g, userBankAddress || "N/A");

        printWindow.document.write(`
=======
        let printContent = printRef.current.innerHTML;

        printWindow.document.write(`
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:239` </location>
<code_context>
+          />
+        ))}
+
+        <div style={{ display: "none" }}>
+          <PrintableSupplement ref={printRef} />
+        </div>
+        
</code_context>

<issue_to_address>
Hidden DOM nodes may impact accessibility and performance.

Consider rendering PrintableSupplement only when printing is required, or explore using a portal or offscreen rendering to avoid unnecessary DOM nodes.

Suggested implementation:

```typescript
        {mappedPts.map((payment) => (
          <Term
            Icon={CoinsIcon}
            title={payment.title}
            type={payment.type}
            key={payment.type}
            disabled={payment.disabled || disabledTerms}
          />
        ))}

        {showPrintableSupplement && (
          <PrintableSupplement ref={printRef} />
        )}

```

```typescript
const SelectPaymentTypeMain = () => {
  const [showUserForm, setShowUserForm] = useState(false);
  const [showPrintableSupplement, setShowPrintableSupplement] = useState(false);
  const printRef = useRef(null);

  const {
    loadingKhan,
    disabledTerms,
  } = usePossiblePaymentTerms()

  const { getLabel } = usePaymentLabel()

  // Example function to trigger printing
  const handlePrint = () => {
    setShowPrintableSupplement(true);
  };

  useEffect(() => {
    if (showPrintableSupplement && printRef.current) {
      // Wait for the component to render, then print
      setTimeout(() => {
        window.print();
        setShowPrintableSupplement(false);
      }, 0);
    }
  }, [showPrintableSupplement]);


```

- You will need to trigger `handlePrint` when you want to print the supplement (e.g., from a button or other event).
- Make sure to import `useRef` and `useEffect` from React if not already imported.
- Adjust the logic in `handlePrint` and the effect as needed to fit your actual print workflow.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Caution

Changes requested ❌

Reviewed everything up to 1444624 in 2 minutes and 15 seconds. Click for details.
  • Reviewed 570 lines of code in 5 files
  • Skipped 0 files when reviewing.
  • Skipped posting 5 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:53
  • Draft comment:
    The regex replacement for placeholders ({{userName}}, {{userBankAddress}}) in printContent is ineffective since the PrintableSupplement component doesn't include these tokens. Consider removing or updating this logic.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 10% vs. threshold = 50% The code clearly shows placeholder replacement logic being used. However, without seeing the PrintableSupplement component's contents, we can't definitively say whether these placeholders exist or not. The comment makes an assumption about code we can't see. Following our rules, we should not keep comments that require more context to verify. The placeholders could very well exist in the PrintableSupplement component that we can't see. Making assumptions about unseen code could lead to incorrect suggestions. Since we can't verify the presence or absence of these placeholders without seeing the PrintableSupplement component, we should err on the side of assuming the code is correct. Delete the comment since we don't have enough context to verify if the placeholders exist in the PrintableSupplement component.
2. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:173
  • Draft comment:
    The state update 'setPrintOpen(true)' is ambiguous given the naming 'printModalOpenAtom'. Clarify its purpose or consider renaming the atom to reflect its usage post-printing.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 10% vs. threshold = 50% The atom name printModalOpenAtom clearly indicates it controls a modal's open state related to printing. The usage in setPrintOpen(true) after printing makes logical sense - likely showing a confirmation or follow-up modal after print completes. There's no real ambiguity here. The naming follows common React patterns for modal control states. I could be missing some broader context about what this modal actually does. Maybe there's a reason the reviewer found it confusing that isn't apparent in this file. Even without full context, the naming and usage pattern is standard and clear enough. The comment doesn't provide any concrete alternative that would be better. The comment should be deleted. The atom naming is clear and follows conventions, and the usage is logical given the printing context.
3. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:51
  • Draft comment:
    Using innerHTML to capture and print component content can expose XSS risks if any user input is not properly sanitized. Ensure that content rendered via innerHTML is safe.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% The values being inserted (userName and userBankAddress) come from Jotai atoms, not direct user input. The PrintableSupplement component is a controlled internal component. The string replacements are using template literals {{userName}} which suggests this is a designed template system. While innerHTML use can be risky, this seems to be a controlled printing scenario. I could be underestimating the security risk - the atom values could potentially contain malicious content if they're populated from user input elsewhere in the app. The template system could have other injection points I'm not seeing. Without seeing how the atom values are populated or the full template system, I can't be certain there's a real security risk. The comment is speculative without more context. The comment raises a valid concern but is speculative without more context about how the data is populated. Following our rules about speculative comments, it should be removed.
4. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:250
  • Draft comment:
    Typo alert: The button label "Nehemjleh" might be a misspelling or inconsistent with the other Mongolian texts (e.g., "Бэлнээр", "Цахимаар"). If it’s meant to be in Mongolian, consider checking if the intended text should be corrected (for example, to "Нэхэмжлэх").
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 0% vs. threshold = 50% While the comment appears technically correct about the script inconsistency, this is a UI text change. According to the rules, we should "NOT comment on any pure frontend UI or styling changes, only logic. Assume that if the author changed the UI, they did it correctly." The choice of script for UI text is a UI decision that should be left to the author. The text inconsistency could cause confusion for users if some labels are in Latin script while others are in Cyrillic. This might be a UX issue rather than just a UI styling issue. Even if it affects UX, the rules explicitly state to trust the author on UI decisions. We don't have enough context to know if there's a valid reason for using different scripts in different places. The comment should be deleted as it relates to UI text choices, which according to the rules should be left to the author's discretion.
5. pos/modules/checkout/components/paymentType/userInfoFrom.tsx:103
  • Draft comment:
    There appears to be a typographical error in the button label 'Nehemjlel uusgeh'. Please verify the intended text.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 50% <= threshold 50% The comment points out a potential typographical error in a button label. It asks the author to verify the intended text, which is not allowed according to the rules. However, it does suggest that there might be a mistake, which could be useful for the author to know. The comment could be rephrased to suggest a correction instead of asking for verification.

Workflow ID: wflow_bdzpqzUGb2ea9Mwc

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link

@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: 5

🧹 Nitpick comments (3)
pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx (1)

239-241: Consider moving the hidden component outside the grid layout.

The hidden PrintableSupplement component is placed inside the grid layout, which is semantically incorrect since it's not part of the visible UI.

Move it outside the grid:

      </div>

+      <div style={{ display: "none" }}>
+        <PrintableSupplement ref={printRef} />
+      </div>
+      
      <div className="grid grid-cols-2 gap-2">
        {/* ... payment options ... */}
-        <div style={{ display: "none" }}>
-          <PrintableSupplement ref={printRef} />
-        </div>
pos/modules/checkout/components/paymentType/userInfoFrom.tsx (2)

27-33: Enhance form validation for better user experience.

The current validation only checks for non-empty trimmed strings. Consider adding more robust validation for better UX.

Add more comprehensive validation:

  const isFormValid = () => {
-    const baseValid = userName.trim() && userBankAddress.trim();
+    const baseValid = userName.trim().length >= 2 && userBankAddress.trim().length >= 5;
    if (accountType === "company") {
-      return baseValid && companyRegister.trim();
+      return baseValid && companyRegister.trim().length >= 3;
    }
    return baseValid;
  };

85-95: Consider adding input validation for bank address format.

The bank address field accepts any text, but bank addresses typically have specific formats. Consider adding pattern validation or input formatting.

Add pattern validation:

  <Input
    id="bankAddress"
    type="text"
    value={userBankAddress}
    onChange={(e) => setUserBankAddress(e.target.value)}
    placeholder="Enter your bank address"
    className="mt-1 text-black"
+    pattern="[0-9]{8,20}"
+    title="Bank address should be 8-20 digits"
    required
  />
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 18c248e and 1444624.

📒 Files selected for processing (5)
  • pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx (3 hunks)
  • pos/modules/checkout/components/paymentType/supplement.tsx (1 hunks)
  • pos/modules/checkout/components/paymentType/userInfo.tsx (1 hunks)
  • pos/modules/checkout/components/paymentType/userInfoFrom.tsx (1 hunks)
  • pos/store/index.tsx (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx (1)
pos/store/index.tsx (3)
  • userNameAtom (54-54)
  • userBankAddressAtom (55-55)
  • printModalOpenAtom (59-59)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: pos-ui
  • GitHub Check: runtest
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
pos/modules/checkout/components/paymentType/userInfo.tsx (1)

35-37: Verify “MN” Prefix and Clarify Field Label
The UI always prepends “MN” to the value stored in userBankAddress. Please confirm with your requirements that all Mongolian bank account numbers must include the “MN” country code and that users will only enter the raw digits (otherwise you may end up with doubled prefixes).

Additionally, the input in userInfoFrom.tsx is labeled and ID’d as “Bank Address” (id=“bankAddress”), but it actually captures the account number. Consider renaming this to “Account Number” (and updating its id) to avoid confusion.

Locations to review:

  • pos/modules/checkout/components/paymentType/userInfo.tsx (lines 33–37)
  • pos/modules/checkout/components/paymentType/userInfoFrom.tsx (the bankAddress field)

Copy link

@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)
pos/modules/checkout/components/paymentType/userInfoForm.tsx (1)

97-114: Consider internationalization for hardcoded text.

The button text "Nehemjlel uusgeh" appears to be hardcoded in what looks like Mongolian. Consider using an internationalization system for better maintainability and multi-language support.

-              Nehemjlel uusgeh
+              {t('userInfoForm.submit') || 'Nehemjlel uusgeh'}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1444624 and 2b24759.

📒 Files selected for processing (5)
  • pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx (3 hunks)
  • pos/modules/checkout/components/paymentType/supplement.tsx (1 hunks)
  • pos/modules/checkout/components/paymentType/userInfo.tsx (1 hunks)
  • pos/modules/checkout/components/paymentType/userInfoForm.tsx (1 hunks)
  • pos/store/index.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • pos/modules/checkout/components/paymentType/supplement.tsx
  • pos/modules/checkout/components/paymentType/userInfo.tsx
  • pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx
  • pos/store/index.tsx
🔇 Additional comments (7)
pos/modules/checkout/components/paymentType/userInfoForm.tsx (7)

1-15: LGTM! Clean imports and type definitions.

The imports are well-organized and the TypeScript interface and type definitions are clear and appropriate.


16-21: LGTM! Proper state management with Jotai.

The state management using Jotai atoms is implemented correctly and follows the established pattern in the codebase.


22-25: LGTM! Clean form submission handler.

The form submission handler correctly prevents default behavior and delegates to the parent component.


27-33: LGTM! Solid validation logic.

The validation correctly handles different account types and uses trim() to prevent whitespace-only submissions.


35-52: LGTM! Well-structured modal with good accessibility.

The modal structure is well-implemented with proper backdrop, centering, and semantic HTML. The form controls have appropriate labels for accessibility.


54-82: LGTM! Good conditional rendering and dynamic labels.

The conditional rendering for company-specific fields is well-implemented, and the dynamic labels based on account type enhance user experience.


119-120: LGTM! Standard export.

Clean default export following React conventions.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Caution

Changes requested ❌

Reviewed 2b24759 in 1 minute and 48 seconds. Click for details.
  • Reviewed 506 lines of code in 5 files
  • Skipped 0 files when reviewing.
  • Skipped posting 4 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:288
  • Draft comment:
    A comment explaining why PrintableSupplement is conditionally rendered (using shouldShowPrintable) would help maintainability.
  • Reason this comment was not posted:
    Confidence changes required: 50% <= threshold 50% None
2. pos/modules/checkout/components/paymentType/userInfo.tsx:38
  • Draft comment:
    Ensure the 'MN' prefix for the bank account is handled consistently; the display prepends 'MN' but the form input does not.
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.
3. pos/modules/checkout/components/paymentType/userInfo.tsx:19
  • Draft comment:
    Memoizing transactionDate ensures consistency, but consider if the transaction time should update if there's a delay in printing.
  • Reason this comment was not posted:
    Confidence changes required: 50% <= threshold 50% None
4. pos/modules/checkout/components/paymentType/supplement.tsx:14
  • Draft comment:
    There appears to be an extra whitespace character in the className attribute (" gap-4"). Consider removing the extra leading space to ensure consistent styling.
  • Reason this comment was not posted:
    Comment was on unchanged code.

Workflow ID: wflow_lKRKxQJSj4IsLcFO

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Caution

Changes requested ❌

Reviewed 782934e in 2 minutes and 37 seconds. Click for details.
  • Reviewed 188 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 6 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:151
  • Draft comment:
    Using alert() here can be disruptive. Consider using non‐blocking notifications (e.g. toast messages) for error feedback.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% Alert() is blocking and forces user acknowledgment, which can be appropriate for critical errors that prevent core functionality. However, toast notifications are more modern and less disruptive. In this case, since the user needs to know why their print attempt failed and potentially take action (try again), a non-blocking toast might actually be less effective than an alert. The comment assumes toast notifications are always better, but blocking alerts can be appropriate for critical errors where user acknowledgment is important. The current alert ensures the user knows why printing failed. While toast notifications are generally more modern, in this specific case the blocking nature of alert() serves a valid purpose by ensuring the user understands why their print attempt failed. The current alert() implementation is actually appropriate for this use case since it's a critical error that requires user attention and potential action. The comment should be deleted.
2. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:161
  • Draft comment:
    Using alert() to notify that the print window was blocked may not be ideal. Consider a less intrusive UI notification.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% While alerts are somewhat outdated and intrusive, in this case it's being used for a critical error that requires user action (enabling popups). A modal or toast might be more modern but wouldn't necessarily improve the user experience significantly since the user needs to take action anyway. The current implementation is functional and clear. The comment has merit from a modern UI perspective. Alerts are considered outdated and can be jarring to users. However, this is an error case that requires immediate user attention and action. The alert() is a simple, universally understood way to communicate this critical information. The comment should be deleted. While using a more modern notification system could be nice, the current solution is functional and appropriate for this error case. The suggested change isn't important enough to warrant a comment.
3. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:193
  • Draft comment:
    The fallback logic using a 2000ms timeout to trigger print and close the window might conflict with the printWindow 'load' event handler. Verify that duplicate print calls do not occur on slower devices.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% The fallback print is actually a safety mechanism that only executes if the window is still open after 2 seconds, suggesting the first print failed. The check for !printWindow.closed prevents duplicate prints if the first one succeeded. This is a reasonable pattern for handling print reliability issues across different browsers and devices. I could be wrong about the race conditions - there might be edge cases where both prints trigger nearly simultaneously before the window closes. Even if both print dialogs appeared, this would be better than the print failing entirely. The code has proper error handling and cleanup in both cases. The comment raises a speculative concern about an edge case, but the code appears to handle print reliability appropriately with proper guards against duplicates.
4. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:271
  • Draft comment:
    A 50ms delay in handlePrintClick before showing the user form is used. Please document why this delay is necessary, as arbitrary timeouts can lead to unpredictable behavior on slower devices.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% While documenting timeouts can be helpful, this seems like a minor implementation detail for UI state management. The timeout is very short (50ms) and appears to be just giving React a chance to process the state reset before showing new UI. This is a common pattern in React for handling state transitions. The comment is asking for documentation of something that's likely just an implementation detail. The timeout could potentially cause issues on very slow devices. Having documentation could help future maintainers understand the purpose. The timeout is so short (50ms) that it's clearly just for UI state management. If it was a longer timeout or had complex business logic implications, documentation would be more important. This comment should be deleted as it's asking for documentation of a minor implementation detail that's using a common React pattern for state transitions.
5. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:164
  • Draft comment:
    Using innerHTML along with replaceTemplateVariables without sanitizing user inputs might expose you to XSS risks. Ensure proper HTML escaping or sanitization for user-provided data.
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.
6. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:185
  • Draft comment:
    Event listeners for 'beforeprint' and 'afterprint' are added to the print window but never removed. While the window is closed soon, consider cleaning up these listeners to avoid potential memory issues.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 10% vs. threshold = 50% The window is closed in multiple ways: 1) handleAfterPrint closes it after printing 2) fallback timeout closes it after 2 seconds 3) resetPrintStates is called in multiple places. When the window is closed, the event listeners are automatically cleaned up by the browser. Adding explicit cleanup would be unnecessary since the window's lifetime is very short and well-controlled. The comment raises a valid general programming practice about cleaning up event listeners. In some cases, not removing listeners could cause memory leaks. In this specific case, the window is temporary and gets closed quickly, either through normal printing flow or fallback timeouts. The browser will clean up the listeners automatically when the window closes. The comment should be deleted as it suggests fixing a non-issue. The current implementation is correct since the print window's lifecycle is well-managed and browser handles cleanup automatically.

Workflow ID: wflow_rXwEl0T7xaqY1vZh

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Caution

Changes requested ❌

Reviewed 48064c3 in 1 minute and 52 seconds. Click for details.
  • Reviewed 601 lines of code in 4 files
  • Skipped 0 files when reviewing.
  • Skipped posting 3 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:54
  • Draft comment:
    Review print handling: ensure that event listeners and setTimeouts do not lead to duplicate print triggers.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
2. pos/modules/checkout/hooks/usePrintSupplement.tsx:43
  • Draft comment:
    Review duplicate print calls: the printWindow.print() is invoked both in the load event listener and via a fallback timeout, which may trigger duplicate dialogs.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% The second print() call appears to be an intentional fallback mechanism in case the first one fails. The 2000ms delay and window.closed check suggests this is a deliberate design pattern. The try-catch and error logging around the fallback also indicates this is intentional error handling rather than a mistake. The comment raises a valid concern about potential duplicate print dialogs. There could be race conditions where both print calls execute. The code appears to have safeguards (checking if window is closed, error handling) and the timing differences (200ms vs 2000ms) make this an intentional fallback pattern rather than a bug. This appears to be an intentional fallback mechanism rather than a bug. The comment should be removed as it misinterprets a deliberate design pattern as an issue.
3. pos/modules/checkout/utils/printUtils.ts:103
  • Draft comment:
    Consider sanitizing user-supplied data in replaceTemplateVariables to mitigate potential XSS risks.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None

Workflow ID: wflow_qKi15uX7X7ECKJKo

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link

@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 (3)
pos/modules/checkout/utils/printUtils.ts (1)

1-97: Consider using TailwindCSS print utilities or CSS modules to avoid class name conflicts.

The hard-coded CSS utility classes may conflict with existing TailwindCSS classes in your application. Consider using TailwindCSS's built-in print utilities or CSS modules for better maintainability.

Alternative approach using TailwindCSS print utilities:

-const PRINT_STYLES = `
-  body {
-    font-family: Arial, sans-serif;
-    margin: 20px;
-    color: black;
-    line-height: 1.6;
-  }
-  .bg-gray-50 {
-    background-color: #f9f9f9;
-    padding: 16px;
-    border-radius: 8px;
-    margin-bottom: 16px;
-  }
-  // ... rest of styles
-`
+const PRINT_STYLES = `
+  @media print {
+    body {
+      font-family: Arial, sans-serif;
+      margin: 20px;
+      color: black;
+      line-height: 1.6;
+    }
+    .print-bg-gray {
+      background-color: #f5f5f5 !important;
+      padding: 16px;
+      border-radius: 8px;
+      margin-bottom: 16px;
+    }
+    // ... use unique print-specific class names
+  }
+`
pos/modules/checkout/hooks/usePrintSupplement.tsx (1)

53-68: Consider simplifying the fallback timeout logic.

The nested setTimeout structure is complex and may create race conditions. The 2-second delay might negatively impact user experience.

Consider a cleaner approach:

-      setTimeout(() => {
-        if (printWindow && !printWindow.closed) {
-          try {
-            printWindow.print()
-          } catch (e) {
-            console.error('Fallback print failed:', e)
-          }
-          setTimeout(() => {
-            try {
-              printWindow.close()
-            } catch (e) {
-              console.error('Failed to close print window:', e)
-            }
-          }, 500)
-        }
-      }, 2000)
+      // Fallback cleanup after shorter timeout
+      setTimeout(() => {
+        if (printWindow && !printWindow.closed) {
+          try {
+            printWindow.close()
+          } catch (e) {
+            console.error('Failed to close print window:', e)
+          }
+        }
+      }, 1000)
pos/modules/checkout/hooks/usePaymentStates.tsx (1)

16-22: Consider adding a comment for the 50ms timeout.

The implementation is sound, but the 50ms delay could benefit from a comment explaining its purpose (likely for DOM/state settling).

  const startPrint = useCallback(() => {
    resetStates()
+   // Short delay to ensure state reset is processed before showing UI
    setTimeout(() => {
      setShouldShowPrintable(true)
      setShowUserForm(true)
    }, 50)
  }, [resetStates])
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 782934e and 48064c3.

📒 Files selected for processing (4)
  • pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx (3 hunks)
  • pos/modules/checkout/hooks/usePaymentStates.tsx (1 hunks)
  • pos/modules/checkout/hooks/usePrintSupplement.tsx (1 hunks)
  • pos/modules/checkout/utils/printUtils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx
🧰 Additional context used
🧬 Code Graph Analysis (1)
pos/modules/checkout/hooks/usePrintSupplement.tsx (2)
pos/store/index.tsx (3)
  • userNameAtom (54-54)
  • userBankAddressAtom (55-55)
  • printModalOpenAtom (59-59)
pos/modules/checkout/utils/printUtils.ts (2)
  • replaceTemplateVariables (99-107)
  • createPrintDocument (109-122)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: runtest
  • GitHub Check: pos-ui
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (13)
pos/modules/checkout/utils/printUtils.ts (2)

99-107: Function implementation looks correct.

The template variable replacement logic is sound and handles falsy values appropriately with the "N/A" fallback.


109-122: LGTM! Clean HTML document generation.

The function properly wraps content in a complete HTML document structure with embedded styles, perfect for printing use cases.

pos/modules/checkout/hooks/usePrintSupplement.tsx (5)

1-8: LGTM! Clean imports and state setup.

The hook properly imports required dependencies and sets up Jotai atom values and setters for state management.


10-14: Good validation and error handling.

Proper null check for the print reference with clear error messaging and logging.


16-33: Excellent popup handling and content processing.

The code properly handles popup blocking scenarios and processes template variables before writing to the print window. Good use of document.open/write/close pattern.


35-51: Well-structured event handling for print lifecycle.

The beforeprint/afterprint event listeners with proper state management and the 200ms delay for content loading are well thought out.


70-79: Solid error handling with proper cleanup.

Good exception handling with state cleanup and consistent return format for both success and error cases.

pos/modules/checkout/hooks/usePaymentStates.tsx (6)

1-7: Clean state management setup.

Well-defined state variables with clear naming and appropriate types for managing the payment printing workflow.


9-14: LGTM! Proper state reset implementation.

Good use of useCallback with appropriate empty dependency array for the reset function.


24-38: Well-designed print lifecycle handlers.

The state transitions are logical and the 500ms delay in handlePrintSuccess allows for proper user feedback before resetting states.


40-42: LGTM! Clean cancellation implementation.

Simple and effective cancel function that immediately resets all states.


44-48: Good cleanup pattern.

Proper useEffect cleanup to reset states on unmount, preventing potential state leaks.


50-64: Excellent hook API design.

Well-organized return object with clear separation between states and actions, making it easy for consuming components to use.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed 73a1433 in 1 minute and 59 seconds. Click for details.
  • Reviewed 79 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 4 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/hooks/usePrintSupplement.tsx:11
  • Draft comment:
    Consider using 'ReturnType' instead of 'NodeJS.Timeout' for timersRef to match the browser environment’s setTimeout return type.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% While technically correct that ReturnType is more precise for browser environments, NodeJS.Timeout is also commonly used and works fine. The code functions correctly either way. This seems like a minor typing preference rather than a significant issue requiring change. The suggestion could improve type precision and maintainability. Browser-specific types might be preferable in a frontend codebase. However, the current type works correctly and the change would be purely cosmetic with no functional impact. The comment doesn't highlight a real problem that needs fixing. This comment should be removed as it suggests a minor typing preference change rather than fixing a real issue.
2. pos/modules/checkout/hooks/usePrintSupplement.tsx:69
  • Draft comment:
    Event listeners are attached anonymously to printWindow on 'load'. It might be beneficial to store and remove them explicitly to prevent potential memory leaks, especially if the print window persists unexpectedly.
  • Reason this comment was not posted:
    Confidence changes required: 50% <= threshold 50% None
3. pos/modules/checkout/hooks/usePrintSupplement.tsx:78
  • Draft comment:
    The fallback logic calls printWindow.print() a second time. Confirm that this redundancy is intentional; you may add a guard to prevent multiple print invocations if not.
  • Reason this comment was not posted:
    Comment was on unchanged code.
4. pos/modules/checkout/hooks/usePrintSupplement.tsx:108
  • Draft comment:
    Please add a newline at the end of the file to adhere to best practices.
  • Reason this comment was not posted:
    Confidence changes required: 30% <= threshold 50% None

Workflow ID: wflow_rGXLZwUJodwrVyQY

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed 47135a7 in 1 minute and 17 seconds. Click for details.
  • Reviewed 448 lines of code in 5 files
  • Skipped 0 files when reviewing.
  • Skipped posting 5 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:141
  • Draft comment:
    The button text update to 'Complete Payment & Print' and 'Processing Payment...' improves feedback. Ensure the onClick (startPrint) properly aligns with opening the user modal before printing.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
2. pos/modules/checkout/components/paymentType/supplement.tsx:8
  • Draft comment:
    The PrintableSupplement component now uses updated styling for a modern invoice look. Verify that these inline styles are consistent with other printed documents.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
3. pos/modules/checkout/components/paymentType/userInfo.tsx:24
  • Draft comment:
    The UserInfo component now features a detailed invoice layout with an order details table. Consider consolidating inline styles into CSS classes for improved maintainability, and ensure using static dates via useMemo aligns with user expectations.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
4. pos/modules/checkout/hooks/usePaymentStates.tsx:25
  • Draft comment:
    State transitions in startPrint and handlePrintSuccess use setTimeout which may be brittle if printing delays occur. Consider basing state changes on actual print event callbacks if available.
  • Reason this comment was not posted:
    Confidence changes required: 50% <= threshold 50% None
5. pos/modules/checkout/utils/printUtils.ts:104
  • Draft comment:
    The print styles have been expanded with new rules for blue and green themes. Confirm that these styles integrate well with the overall printed document and do not conflict with global styles.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None

Workflow ID: wflow_HxGSykjpxrOTEQo6

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link

@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 (2)
pos/modules/checkout/components/paymentType/userInfo.tsx (2)

28-51: Consider styling consistency and data validation improvements.

While the conditional rendering logic is sound, consider these improvements:

  1. Styling inconsistency: Mixing inline styles with Tailwind classes reduces maintainability.
  2. Data validation: Add null checks for user data to prevent rendering issues.
  3. Hardcoded prefix: The "MN" prefix for bank addresses may not be flexible for future requirements.

Consider this refactor for better consistency:

-    <div style={{ 
-      padding: '8px', 
-      backgroundColor: 'white',
-      color: '#111827',
-    }}>
+    <div className="p-2 bg-white text-gray-900">
      <h2 className="text-lg font-semibold text-gray-800">Нэхэмжлэл гаргах мэдээлэл</h2>
      
      <div className="space-y-2 text-sm">
        <p>
-          <strong>{isCompany ? "Байгууллагын нэр:" : "Овог, нэр:"}</strong> {userName}
+          <strong>{isCompany ? "Байгууллагын нэр:" : "Овог, нэр:"}</strong> {userName || 'Тодорхойгүй'}
        </p>

226-240: Clean up redundant signature lines.

The signature section has both a styled border-bottom div and an underscore line, which is redundant.

        <p style={{ fontWeight: 'bold', marginBottom: '8px' }}>Гарын үсэг:</p>
        <div style={{ 
          width: '192px', 
          height: '24px', 
          borderBottom: '1px solid #9ca3af',
        }}></div>
        <p style={{ fontSize: '12px', color: '#6b7280' }}>Нэхэмжлэл гаргасан</p>
-        <p>_________________________</p>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 73a1433 and 47135a7.

📒 Files selected for processing (5)
  • pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx (3 hunks)
  • pos/modules/checkout/components/paymentType/supplement.tsx (1 hunks)
  • pos/modules/checkout/components/paymentType/userInfo.tsx (1 hunks)
  • pos/modules/checkout/hooks/usePaymentStates.tsx (1 hunks)
  • pos/modules/checkout/utils/printUtils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • pos/modules/checkout/hooks/usePaymentStates.tsx
  • pos/modules/checkout/utils/printUtils.ts
  • pos/modules/checkout/components/paymentType/supplement.tsx
  • pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx
🔇 Additional comments (4)
pos/modules/checkout/components/paymentType/userInfo.tsx (4)

1-15: LGTM! Well-organized imports.

The imports are properly structured with client directive, necessary hooks, state management, and utility functions all appropriately imported.


16-26: Excellent implementation of previous feedback!

The transaction date is now properly memoized, addressing the previous review comment. The deadline calculation using addDays is clean and the derived isCompany boolean improves code readability.


180-192: Payment summary logic is sound.

The conditional text rendering based on account type is well implemented, and the dynamic content insertion is appropriate for the invoice context.


194-224: Well-implemented date handling with proper memoization.

The transaction date and deadline calculations are correctly memoized and formatted. The 14-day payment term is clearly communicated with appropriate visual emphasis.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed fb9cff5 in 1 minute and 25 seconds. Click for details.
  • Reviewed 716 lines of code in 3 files
  • Skipped 0 files when reviewing.
  • Skipped posting 3 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/userInfo.tsx:15
  • Draft comment:
    Good use of usePrintStyles to centralize styling. Ensure all required style properties are present.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
2. pos/modules/checkout/hooks/usePrintStyles.tsx:30
  • Draft comment:
    Well-structured style definitions using useMemo; clear separation of theme, typography, and spacing.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
3. pos/modules/checkout/hooks/usePrintSupplement.tsx:69
  • Draft comment:
    The safeWindowOperation wrapper efficiently handles window errors. Verify that the fallback timers (200ms and 2000ms) do not trigger duplicate print calls in some browsers.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None

Workflow ID: wflow_Wcm1nqHG44vBby9c

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Caution

Changes requested ❌

Reviewed 87de95d in 1 minute and 33 seconds. Click for details.
  • Reviewed 264 lines of code in 3 files
  • Skipped 0 files when reviewing.
  • Skipped posting 4 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/userInfo.tsx:64
  • Draft comment:
    New column header 'НӨАТ-гүй үнэ' added; ensure the VAT-free price calculation (total/1.1, rounded) meets business requirements.
  • Reason this comment was not posted:
    Confidence changes required: 50% <= threshold 50% None
2. pos/modules/checkout/components/paymentType/userInfo.tsx:127
  • Draft comment:
    Review rounding strategy for currency values; Math.round may not be adequate for financial precision. Consider a more robust currency formatting approach if needed.
  • Reason this comment was not posted:
    Confidence changes required: 50% <= threshold 50% None
3. pos/modules/checkout/hooks/usePrintStyles.tsx:259
  • Draft comment:
    Removal of commented labels cleans up the code; consider keeping minimal inline documentation for complex style objects for future maintainability.
  • Reason this comment was not posted:
    Confidence changes required: 30% <= threshold 50% None
4. pos/modules/checkout/hooks/usePrintSupplement.tsx:64
  • Draft comment:
    The schedulePrintActions function triggers two print commands using timers. Consider adding a flag or check to avoid duplicate print dialogs in browsers where one print might already have been initiated.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 10% vs. threshold = 50% The code appears to be intentionally designed with a fallback print mechanism, likely to handle cases where the first print attempt fails. The safeWindowOperation and event listeners already provide protection against issues. The suggestion to add a flag might actually break the fallback functionality. The current implementation seems robust and intentional. I might be overlooking browser-specific edge cases where both print attempts could trigger simultaneously. The 2000ms timeout might be too short for some scenarios. The existing code already has safeguards, and the fallback mechanism is likely necessary for reliability. Adding a flag could make the system less robust by preventing the fallback from working when needed. The comment should be deleted as it suggests a change that could break the intentional fallback mechanism, and the code already has appropriate safeguards in place.

Workflow ID: wflow_CPzDUzhAzkNQcAz1

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed 14c63c5 in 1 minute and 25 seconds. Click for details.
  • Reviewed 137 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 3 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/hooks/usePrintSupplement.tsx:18
  • Draft comment:
    Consider wrapping the cleanup function in a block (e.g. useEffect(() => { return clearAllTimers; }, [])) for clarity. While useEffect(() => clearAllTimers, []) works, the explicit return makes the intent clearer.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
2. pos/modules/checkout/hooks/usePrintSupplement.tsx:68
  • Draft comment:
    The print action (doPrint) is scheduled twice (lines 69 and 72) as part of a fallback mechanism. Consider adding a comment to clarify this design decision.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% The comment suggests adding a comment to clarify a design decision, which is not allowed by the rules. It doesn't provide a specific code suggestion or ask for a test to be written. It also doesn't point out a potential issue or ask for confirmation of an intentional design choice. Therefore, it should be removed.
3. pos/modules/checkout/hooks/usePrintSupplement.tsx:82
  • Draft comment:
    The 'load' event listener added in setupLoadHandler is never removed. While this might not be an issue due to the window closing soon, consider removing the listener after it fires to avoid potential unintended multiple invocations.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None

Workflow ID: wflow_EjqJhOX15XW46RpH

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link

@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

♻️ Duplicate comments (1)
pos/modules/checkout/hooks/usePrintSupplement.tsx (1)

39-44: Using deprecated document.write API.

The document.write method is deprecated. However, for print windows, this is still a common pattern as alternatives are limited.

🧹 Nitpick comments (2)
pos/modules/checkout/hooks/usePrintSupplement.tsx (2)

68-75: Multiple print attempts may indicate browser compatibility issues.

The code schedules print operations at 200ms and 2000ms. Consider documenting why these specific delays and multiple attempts are necessary, as this suggests workarounds for browser-specific behaviors.


6-130: Consider making print delays configurable and adding unit tests.

The hardcoded delays (200ms, 500ms, 2000ms) could be made configurable through hook parameters or constants to allow tuning for different environments. Additionally, this complex hook would benefit from unit tests to ensure reliability across different scenarios.

Would you like me to help create unit tests for this hook or refactor it to accept configuration options?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 87de95d and 14c63c5.

📒 Files selected for processing (1)
  • pos/modules/checkout/hooks/usePrintSupplement.tsx (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
pos/modules/checkout/hooks/usePrintSupplement.tsx (2)
pos/store/index.tsx (3)
  • userNameAtom (54-54)
  • userBankAddressAtom (55-55)
  • printModalOpenAtom (59-59)
pos/modules/checkout/utils/printUtils.ts (2)
  • replaceTemplateVariables (120-128)
  • createPrintDocument (130-143)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: pos-ui
  • GitHub Check: runtest
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
pos/modules/checkout/hooks/usePrintSupplement.tsx (5)

1-11: Imports and hook setup look good.

The imports are well-organized and the use of a Set to track timers is a good choice for managing multiple timeouts.


13-27: Timer management implementation is solid.

The timer cleanup pattern prevents memory leaks and the self-removing timer logic is well implemented.


82-89: Good implementation of load event handling.

The readyState check before adding the load listener properly addresses potential race conditions, as suggested in previous reviews.


91-124: Well-structured print function with comprehensive error handling.

The function properly validates inputs, handles popup blockers, and provides clear error messages. The consistent return format with success/error is good for consumer code.


126-130: Clean hook interface.

Exposing both the print function and timer cleanup provides good control to consumers.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed 7f3d8df in 35 seconds. Click for details.
  • Reviewed 13 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 1 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:142
  • Draft comment:
    The button label has been changed to a hardcoded Mongolian text ('Нэхэмжлэл'). Consider using a localization approach to dynamically handle different languages.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None

Workflow ID: wflow_1211t773vQRuY2xc

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

@ColeGN ColeGN requested a review from munkhsaikhan July 29, 2025 19:49
Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed d079e2d in 43 seconds. Click for details.
  • Reviewed 31 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 3 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/userInfoForm.tsx:42
  • Draft comment:
    The label 'Type' might be too ambiguous – consider reverting to 'Account Type' for clarity.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
2. pos/modules/checkout/components/paymentType/userInfoForm.tsx:85
  • Draft comment:
    Verify if 'Bank Account' correctly reflects the intended input, as it was 'Bank Address' previously.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
3. pos/modules/checkout/components/paymentType/userInfoForm.tsx:103
  • Draft comment:
    Ensure the new button text 'Create invoice' aligns with the application's localization and UX guidelines.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None

Workflow ID: wflow_UgfhrbtoNWRZscHc

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed f921388 in 1 minute and 54 seconds. Click for details.
  • Reviewed 345 lines of code in 7 files
  • Skipped 0 files when reviewing.
  • Skipped posting 7 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/invoiceInfo.tsx:189
  • Draft comment:
    Ensure the file ends with a newline for consistency.
  • Reason this comment was not posted:
    Comment was on unchanged code.
2. pos/modules/checkout/components/paymentType/invoiceInfoForm.tsx:39
  • Draft comment:
    Localize the modal header text; 'User Information' is in English while other texts use Mongolian.
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.
3. pos/modules/checkout/components/paymentType/invoiceInfoForm.tsx:127
  • Draft comment:
    Consider localizing the 'Cancel' button label to match the Mongolian text used elsewhere.
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.
4. pos/modules/checkout/components/paymentType/invoiceInfoForm.tsx:135
  • Draft comment:
    For consistency, rename the default export from 'UserInfoForm' to 'InvoiceInfoForm' to match the file name.
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.
5. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:169
  • Draft comment:
    Consider unifying naming: 'startPrint' (used to trigger the invoice flow) versus 'handlePrint' (for printing) may be confusing.
  • Reason this comment was not posted:
    Comment was on unchanged code.
6. pos/modules/checkout/hooks/useInvoicePrintSupplement.tsx:69
  • Draft comment:
    Double print invocation is scheduled (after 200ms and again after 2000ms); confirm if this behavior is intentional.
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.
7. pos/modules/checkout/components/paymentType/invoiceInfo.tsx:189
  • Draft comment:
    It appears that the component is defined as UserInfo (see the declaration above), but the default export is changed to InvoiceInfo. If this change is intended, please update the component’s name for consistency. Otherwise, it might be a typographical error.
  • Reason this comment was not posted:
    Comment looked like it was already resolved.

Workflow ID: wflow_Io86lrvcV5wapSdl

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link

@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)
pos/modules/checkout/components/paymentType/invoiceInfoForm.tsx (2)

14-14: Remove redundant type definition.

The AccountType type is already defined in the accountTypeAtom and is redundant here.

-type AccountType = "person" | "company";

The type can be inferred from the atom or imported if needed elsewhere.


98-111: Improve number input validation and user feedback.

The payment deadline input should handle invalid values better and provide clearer feedback to users.

Consider adding client-side validation feedback:

          <div>
            <Label htmlFor="expiryDays" className="text-black">Payment Deadline (Days)</Label>
            <Input
              id="expiryDays"
              type="number"
              min="1"
              max="365"
              value={expiryDays}
-             onChange={(e) => setExpiryDays(Number(e.target.value))}
+             onChange={(e) => {
+               const value = Number(e.target.value);
+               if (value >= 1 && value <= 365) {
+                 setExpiryDays(value);
+               }
+             }}
              placeholder="Enter payment deadline in days"
              className="mt-1 text-black"
              required
            />
+           {(expiryDays < 1 || expiryDays > 365) && (
+             <p className="text-red-500 text-xs mt-1">Please enter a value between 1 and 365 days</p>
+           )}
          </div>
pos/modules/checkout/components/paymentType/invoiceInfo.tsx (1)

102-105: Consider making VAT rate configurable.

The hardcoded VAT calculation (dividing by 1.1) assumes a fixed 10% VAT rate. This might need to be configurable for different regions or product types.

Consider extracting the VAT rate to a constant or configuration:

+const VAT_RATE = 0.1; // 10%
+const VAT_MULTIPLIER = 1 + VAT_RATE;

                {cartItems.map((item, index) => {
                  const totalItemPrice = item.count * item.unitPrice;
-                 const withoutVatPrice = totalItemPrice / 1.1;
+                 const withoutVatPrice = totalItemPrice / VAT_MULTIPLIER;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d079e2d and f921388.

📒 Files selected for processing (7)
  • pos/modules/checkout/components/paymentType/invoiceInfo.tsx (1 hunks)
  • pos/modules/checkout/components/paymentType/invoiceInfoForm.tsx (1 hunks)
  • pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx (5 hunks)
  • pos/modules/checkout/components/paymentType/supplement.tsx (1 hunks)
  • pos/modules/checkout/hooks/useInvoicePrintStyles.tsx (1 hunks)
  • pos/modules/checkout/hooks/useInvoicePrintSupplement.tsx (1 hunks)
  • pos/store/index.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • pos/modules/checkout/hooks/useInvoicePrintStyles.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • pos/modules/checkout/components/paymentType/supplement.tsx
  • pos/store/index.tsx
🧰 Additional context used
🧬 Code Graph Analysis (3)
pos/modules/checkout/components/paymentType/invoiceInfoForm.tsx (3)
pos/store/index.tsx (5)
  • userNameAtom (54-54)
  • userBankAddressAtom (55-55)
  • accountTypeAtom (56-56)
  • companyRegisterAtom (57-57)
  • invoiceExpiryDaysAtom (58-58)
packages/erxes-ui/src/components/form/styles.tsx (2)
  • Select (374-374)
  • Input (372-372)
packages/ui-sales/src/boards/styles/popup.ts (1)
  • Button (31-51)
pos/modules/checkout/components/paymentType/invoiceInfo.tsx (4)
pos/store/index.tsx (5)
  • userNameAtom (54-54)
  • userBankAddressAtom (55-55)
  • companyRegisterAtom (57-57)
  • accountTypeAtom (56-56)
  • invoiceExpiryDaysAtom (58-58)
pos/store/cart.store.ts (2)
  • totalAmountAtom (123-125)
  • cartAtom (113-113)
pos/modules/checkout/hooks/useInvoicePrintStyles.tsx (1)
  • useInvoicePrintStyles (30-269)
pos/lib/utils.ts (1)
  • formatNum (147-162)
pos/modules/checkout/hooks/useInvoicePrintSupplement.tsx (2)
pos/store/index.tsx (3)
  • userNameAtom (54-54)
  • userBankAddressAtom (55-55)
  • printModalOpenAtom (60-60)
pos/modules/checkout/utils/printUtils.ts (2)
  • replaceTemplateVariables (120-128)
  • createPrintDocument (130-143)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: pos-ui
  • GitHub Check: runtest
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (12)
pos/modules/checkout/components/paymentType/invoiceInfoForm.tsx (2)

28-34: LGTM! Well-designed validation logic.

The form validation correctly handles conditional requirements based on account type and properly validates against empty/whitespace-only values.


36-40: LGTM! Well-implemented modal with proper form handling.

The modal implementation follows best practices with proper positioning, backdrop, and form submission handling. The button states are correctly managed based on form validation.

Also applies to: 113-132

pos/modules/checkout/hooks/useInvoicePrintSupplement.tsx (3)

6-18: Good timer management setup for preventing memory leaks.

The use of a Set to track timers and the cleanup on unmount is a solid pattern for preventing memory leaks in this complex printing workflow.


29-37: Solid error handling foundation with room for enhancement.

The safeWindowOperation wrapper and return value pattern provide good error handling structure. The popup blocker detection is particularly valuable for user experience.

Consider enhancing error specificity for better debugging:

    } catch (error) {
-     console.error('Print failed:', error)
+     console.error('Print failed:', error instanceof Error ? error.message : error)
      setPrintOpen(false)
      printWindow.close()
-     return { success: false, error: 'Print failed. Please try again.' }
+     return { success: false, error: `Print failed: ${error instanceof Error ? error.message : 'Unknown error'}. Please try again.` }
    }

Also applies to: 91-124


107-112: Confirm presence of {{userName}} & {{userBankAddress}} in your print template

I couldn’t locate these placeholders in the TS/TSX files via search— they may live in an external HTML/template file or be injected at runtime. Please manually verify that the DOM content referenced by printRef actually contains {{userName}} and {{userBankAddress}} before calling replaceTemplateVariables(). For example:

  • Inspect the source template file or component that populates printRef.
  • Log printRef.current.innerHTML just before replacement to confirm the placeholders are present.
pos/modules/checkout/components/paymentType/invoiceInfo.tsx (3)

29-31: LGTM! Proper date calculations with good memoization.

The use of useMemo for date calculations and addDays from date-fns is correct and efficient. The dependency array properly includes all relevant dependencies.


57-142: Well-structured table with good accessibility and UX.

The table implementation has proper HTML structure, consistent styling through the custom hook, and good user experience with empty state handling and clear product information display.


47-51: Consistent number formatting with appropriate localization.

The use of formatNum utility and the Mongolian tugrik (₮) symbol with "MN" bank prefix indicates proper localization for the Mongolian market. The formatting is consistent throughout the component.

Also applies to: 127-134

pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx (4)

57-71: Excellent refactoring of the print functionality!

This implementation successfully addresses the previous review concerns:

  • Complex print logic moved to dedicated hook
  • Proper error handling with try-catch
  • Clean separation of concerns
  • No more deprecated APIs in this component

The simplified handlePrint function is much more maintainable and follows good React patterns.


53-56: Good conditional rendering strategy for performance.

The hasPrintInvoice check and conditional rendering of the PrintableSupplement addresses the previous performance concerns about hidden DOM nodes. The component only renders the print content when actually needed.

Also applies to: 134-140


157-176: Clean conditional logic in Term component.

The addition of invoice and onPrint props with conditional handling in handleClick is well-implemented. The logic clearly separates print workflow from regular payment type selection.


21-21: Import path has been corrected.

The import path for UserInfoForm now correctly points to "./invoiceInfoForm", addressing the previous typo concern.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed b765a39 in 1 minute and 54 seconds. Click for details.
  • Reviewed 72 lines of code in 2 files
  • Skipped 0 files when reviewing.
  • Skipped posting 3 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/invoiceInfoForm.tsx:106
  • Draft comment:
    The onChange handler for expiryDays allows values >= 0, but the validation requires a minimum of 1. Consider changing the check to 'value >= 1' for consistency.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 30% vs. threshold = 50% The comment is technically correct - there is an inconsistency. However, the form handles invalid values gracefully: the submit button is disabled via isFormValid() and there's an error message shown to the user. The onChange handler being more permissive doesn't cause any problems since invalid values are caught elsewhere. The HTML min/max attributes also provide UI constraints. The inconsistency could be confusing to future maintainers. Having consistent validation boundaries across all checks would make the code more maintainable. While consistency would be nice, the current implementation is still robust and safe. The inconsistency doesn't introduce any bugs or user-facing issues. While technically correct, this comment points out a minor inconsistency that doesn't impact functionality. The form handles invalid values appropriately through other validation mechanisms.
2. pos/modules/checkout/components/paymentType/invoiceInfoForm.tsx:116
  • Draft comment:
    The error message for expiryDays is shown only when expiryDays > 0. This might hide errors when the value is 0; consider removing the 'expiryDays > 0' condition.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 10% vs. threshold = 50% The form validation in isFormValid() already ensures expiryDays is valid before submission. The input element has min="1" max="365". The error message is just UI feedback. Having no error message when value is 0 is actually fine - it's an empty/unset state. Showing an error for 0 could be confusing since it's a natural initial/empty state. The reviewer has a point that technically 0 is invalid and users should be informed. The current UX could be seen as inconsistent. However, 0 is a special case representing an empty/unset state, and it's common UX pattern to not show validation errors for empty required fields until the user has interacted with them. The current behavior is actually a reasonable UX choice. The comment suggests a change that could make the UX worse by showing errors too aggressively.
3. pos/modules/checkout/components/paymentType/selectPaymentType.main.tsx:26
  • Draft comment:
    Removal of the unused 'isPrinting' variable cleans up the code. Confirm that it isn’t needed elsewhere.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None

Workflow ID: wflow_G4YhJ0ktuW1iTzg5

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Caution

Changes requested ❌

Reviewed fa8ba92 in 1 minute and 51 seconds. Click for details.
  • Reviewed 299 lines of code in 2 files
  • Skipped 0 files when reviewing.
  • Skipped posting 4 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/invoiceInfo.tsx:27
  • Draft comment:
    Removed columnWidths from the destructured object. Confirm that the inline hard-coded widths in the table header are intentional for consistency.
  • Reason this comment was not posted:
    Comment looked like it was already resolved.
2. pos/modules/checkout/components/paymentType/invoiceInfo.tsx:128
  • Draft comment:
    The table header now has 5 columns, omitting the per‐item "НӨАТ-гүй үнэ" column. Confirm that this simplification meets the design requirements.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% The comment is asking the PR author to confirm that the change meets design requirements, which violates the rule against asking for confirmation of intention or ensuring behavior is intended. It does not provide a specific code suggestion or ask for a specific test to be written.
3. pos/modules/checkout/hooks/useInvoicePrintStyles.tsx:82
  • Draft comment:
    The dateSection style was modified by removing backgroundColor and padding. Verify that the new minimalist styling is intentional.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 30% <= threshold 50% The comment is asking the PR author to verify if the minimalist styling is intentional. This falls under the rule of not asking the author to confirm their intention. However, it does point out a specific change in styling which could be useful if it was unintentional. The comment could be rephrased to suggest checking the styling change, but as it stands, it violates the rules.
4. pos/modules/checkout/hooks/useInvoicePrintStyles.tsx:148
  • Draft comment:
    Border style was removed from table.container. Confirm that this removal aligns with the intended print design.
  • Reason this comment was not posted:
    Comment looked like it was already resolved.

Workflow ID: wflow_1dT2tQLdl2ck27E5

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed 6608dac in 1 minute and 26 seconds. Click for details.
  • Reviewed 269 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 5 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. pos/modules/checkout/components/paymentType/invoiceInfo.tsx:18
  • Draft comment:
    Good use of constants to avoid magic numbers. Consider adding a brief comment to explain VAT_RATE and VAT_MULTIPLIER.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
2. pos/modules/checkout/components/paymentType/invoiceInfo.tsx:39
  • Draft comment:
    Replacing the hard-coded 1.1 with VAT_MULTIPLIER is an improvement for maintainability.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
3. pos/modules/checkout/components/paymentType/invoiceInfo.tsx:43
  • Draft comment:
    Rounding the computed subtotal, VAT, and total can introduce minor discrepancies. Confirm that rounding after summing is the desired approach versus rounding per item when accuracy is critical.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 10% vs. threshold = 50% While the comment raises a valid mathematical point about rounding, this appears to be a deliberate design choice. The code is handling a VAT tax calculation which often has specific rules about rounding. The approach taken (rounding each component) is a common and acceptable practice in tax calculations. The comment is speculative ("can introduce") and asks for confirmation rather than pointing out a clear issue. I might be overlooking local tax regulations that require a specific rounding approach. There could be business requirements around tax calculation precision that I'm not aware of. Even if there are specific requirements, the comment doesn't demonstrate knowledge of them - it's just asking for confirmation. If there were specific rounding requirements, they should be stated directly rather than asking the author to verify. Delete the comment. It asks for confirmation rather than pointing out a clear issue, and the current implementation is a reasonable approach to tax calculations.
4. pos/modules/checkout/components/paymentType/invoiceInfo.tsx:183
  • Draft comment:
    The VAT percentage in the display text is hardcoded as '10%'. Consider computing this value from VAT_RATE (e.g. VAT_RATE * 100) to keep the display in sync with the logic.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
5. pos/modules/checkout/components/paymentType/invoiceInfo.tsx:103
  • Draft comment:
    The table markup and inline styles are quite verbose. Consider refactoring the table rendering into smaller subcomponents or external style definitions to improve maintainability.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None

Workflow ID: wflow_gZL425DAVscf7l9X

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Caution

Changes requested ❌

Reviewed 94b67ca in 1 minute and 29 seconds. Click for details.
  • Reviewed 73 lines of code in 4 files
  • Skipped 0 files when reviewing.
  • Skipped posting 4 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. packages/plugin-pos-ui/src/pos/components/Pos.tsx:272
  • Draft comment:
    Removed passing 'catProdMappings' prop. Ensure that ConfigStep now correctly accesses mappings from pos.catProdMappings; if mappings are needed separately, consider consolidating.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
2. packages/plugin-pos-ui/src/pos/components/step/ConfigStep.tsx:44
  • Draft comment:
    Removed the redundant 'catProdMappings' prop from ConfigStep's props. Now the component derives mappings directly from pos.catProdMappings—verify that this meets all use cases.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
3. packages/plugin-pos-ui/src/pos/components/step/PaymentsStep.tsx:262
  • Draft comment:
    Updated the payment description to include the 'printInvoice: true' flag. Ensure that documentation and logic elsewhere align with this new print functionality.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
4. packages/plugin-pos-ui/src/pos/components/step/PaymentsStep.tsx:258
  • Draft comment:
    There's a potential typographical error in the description text: “ебаримт”. Please check if this term is spelled as intended (e.g., should it be “ебаримт” or another variant?)
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% The comment is asking the PR author to confirm the spelling of a term, which violates the rule against asking for confirmation or verification of intention. It does not provide a specific code suggestion or improvement.

Workflow ID: wflow_2tj9Y06BEKjwJAta

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

const onSelectChange = (field: string, value: any) => {
setState((prevState) => ({ ...prevState, [field]: value }));
editMapping({ ...state, _id: item._id });
editMapping({ _id: item._id, ...state, [field]: value });
Copy link
Contributor

Choose a reason for hiding this comment

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

The updated spread order in onSelectChange (using { _id: item._id, ...state, [field]: value }) may risk using a stale state value since setState is async. Consider using a functional update to guarantee the latest state.


setState((prevState) => ({ ...prevState, [name]: value }));
editMapping({ ...state, _id: item._id });
editMapping({ _id: item._id, ...state, [name]: value });
Copy link
Contributor

Choose a reason for hiding this comment

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

Similarly, in onChangeInput the editMapping call uses the current 'state' immediately after setState, which might be stale. Refactor to use the updated state value or the setState callback result.

@munkhsaikhan munkhsaikhan merged commit 20f12a5 into master Aug 5, 2025
8 of 9 checks passed
@munkhsaikhan munkhsaikhan deleted the pos-change branch August 5, 2025 06:31
@sonarqubecloud
Copy link

sonarqubecloud bot commented Aug 5, 2025

@coderabbitai coderabbitai bot mentioned this pull request Aug 12, 2025
2 tasks
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.

3 participants