Skip to content

[TASK-7762] fix: fee calculation after promo code is applied#585

Merged
Hugo0 merged 3 commits intodevelopfrom
fix/promo-checker
Dec 22, 2024
Merged

[TASK-7762] fix: fee calculation after promo code is applied#585
Hugo0 merged 3 commits intodevelopfrom
fix/promo-checker

Conversation

@kushagrasarathe
Copy link
Copy Markdown
Contributor

@kushagrasarathe kushagrasarathe commented Dec 20, 2024

Summary by CodeRabbit

  • New Features

    • Introduced promo code handling in the cashout and off-ramp components.
    • Added functionality to display and manage applied promo codes.
  • Bug Fixes

    • Improved error handling and state management for promo codes.
  • Documentation

    • Updated interfaces to reflect new properties related to promo codes.
  • Refactor

    • Streamlined promo code logic and calculations for better readability and maintainability.

@vercel
Copy link
Copy Markdown

vercel bot commented Dec 20, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
peanut-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 20, 2024 4:52pm

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Dec 20, 2024

Walkthrough

This pull request introduces changes to manage promotional codes across various components in the cashout and offramp processes. Modifications include the addition of new properties to interfaces, state management for promo codes, and updates to components to support external handling of promo codes. The changes aim to create a more cohesive and centralized approach to promo code management throughout the user transaction experience.

Changes

File Change Summary
src/components/Cashout/Cashout.consts.ts Added onPromoCodeApplied method to ICashoutScreenProps interface.
src/components/Cashout/Cashout.tsx Introduced appliedPromoCode state and related props for promo code management.
src/components/Offramp/Confirm.view.tsx Updated component to accept appliedPromoCode and onPromoCodeApplied props.
src/components/Offramp/Offramp.consts.ts Modified IOfframpConfirmScreenProps and IOfframpSuccessScreenProps to include promo code properties.
src/components/Offramp/PromoCodeChecker.tsx Added appliedPromoCode prop and updated state initialization logic.
src/components/Offramp/Success.view.tsx Added calculateFee method and updated rendering logic for fee display.

Possibly related PRs

Suggested reviewers

  • jjramirezn
  • Hugo0

Poem

🐰 In the cashout, codes do play,
With each hop, they find their way!
Promo magic, bright and clear,
Bringing joy, spreading cheer! 🎉
A rabbit's wish, for codes to thrive,
In every transaction, they come alive! 🌈


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/components/Offramp/Offramp.consts.ts (1)

Line range hint 82-117: Consider improving promo code management

The current implementation of VALID_PROMO_CODES has several limitations:

  • Hardcoded values make it difficult to manage expiration dates
  • No validation rules or restrictions
  • Updates require code changes and deployment

Consider moving this to a configuration service or database for easier management and to support features like:

  • Expiration dates
  • Usage limits
  • Discount amounts
  • Dynamic validation rules
src/components/Offramp/PromoCodeChecker.tsx (2)

Line range hint 31-67: Consider UX improvements for promo code validation

The current implementation could benefit from:

  1. Debouncing input changes to prevent rapid state updates
  2. Adding loading state for future async validation
  3. Case-insensitive comparison during typing

Example implementation:

+ import { debounce } from 'lodash'
+
+ const [isValidating, setIsValidating] = useState(false)
+
+ const debouncedValidation = debounce((code: string) => {
+     setIsValidating(true)
+     // Future async validation logic here
+     const normalizedCode = code.trim().toUpperCase()
+     // ... rest of validation logic
+     setIsValidating(false)
+ }, 300)
+
  const handlePromoCodeSubmit = () => {
+     setIsValidating(true)
      const normalizedCode = promoCheckerState.code.trim().toUpperCase()
      // ... rest of the function
+     setIsValidating(false)
  }

Line range hint 79-134: Consider accessibility improvements

The current implementation could benefit from:

  1. Adding ARIA labels for screen readers
  2. Keyboard navigation support
  3. Focus management after successful application

Example improvements:

- <div className="w-full">
+ <div className="w-full" role="region" aria-label="Promo code section">
     <div
         onClick={handleExpandToggle}
+        onKeyPress={(e) => e.key === 'Enter' && handleExpandToggle()}
+        role="button"
+        tabIndex={0}
         className="flex w-full cursor-pointer flex-row items-center"
     >
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c8cd19c and 03a3739.

📒 Files selected for processing (6)
  • src/components/Cashout/Cashout.consts.ts (1 hunks)
  • src/components/Cashout/Cashout.tsx (2 hunks)
  • src/components/Offramp/Confirm.view.tsx (3 hunks)
  • src/components/Offramp/Offramp.consts.ts (1 hunks)
  • src/components/Offramp/PromoCodeChecker.tsx (3 hunks)
  • src/components/Offramp/Success.view.tsx (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Offramp/Success.view.tsx

[error] 38-38: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 44-44: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 44-44: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (10)
src/components/Cashout/Cashout.consts.ts (1)

70-70: LGTM! Consistent type definition for promo code handling

The callback signature matches the pattern used across components and properly handles both application and removal of promo codes.

src/components/Offramp/Offramp.consts.ts (1)

64-65: LGTM! Consistent interface updates

The promo code related props are consistently defined across interfaces.

src/components/Offramp/PromoCodeChecker.tsx (3)

19-22: LGTM! Well-defined props interface

Clean and type-safe props definition with proper nullability handling.


24-29: LGTM! Clean state initialization

Good practice initializing state with the external promo code while maintaining local state structure.


68-77: LGTM! Proper external state sync

The useEffect hook correctly synchronizes the component's state with external changes.

src/components/Cashout/Cashout.tsx (1)

12-12: LGTM: Clean implementation of promo code state management.

The changes follow React best practices by:

  • Managing promo code state at the parent level
  • Passing state and callback props to child components
  • Following unidirectional data flow pattern

Also applies to: 179-180

src/components/Offramp/Success.view.tsx (1)

66-66: LGTM: Fee display logic correctly handles promo codes.

The fee display logic properly:

  • Shows $0 when promo code is applied
  • Maintains existing fee structure when no promo code
  • Provides clear user feedback through MoreInfo component

Also applies to: 70-74

src/components/Offramp/Confirm.view.tsx (3)

98-100: LGTM: Clean implementation of promo code handling.

The handlePromoCodeApplied function correctly delegates to the parent's callback.


860-863: LGTM: PromoCodeChecker component integration.

The PromoCodeChecker component is properly integrated with:

  • Callback for handling promo code application
  • Current promo code state

99-99: Verify promo code handling in parent components.

Let's ensure the promo code state management is properly implemented in parent components.

✅ Verification successful

Promo code handling is properly implemented

The promo code implementation is well-structured with proper state management:

  • PromoCodeChecker component handles validation against VALID_PROMO_CODES
  • Parent components receive updates via onPromoCodeApplied callback
  • Two-way binding is maintained with appliedPromoCode prop
  • Error handling and UI states are properly managed
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for promo code state management in parent components

# Search for promo code state management
rg -A 5 'const \[appliedPromoCode'

# Search for promo code prop types
ast-grep --pattern 'interface $_ {
  $$$
  appliedPromoCode: $_
  $$$
}'

Length of output: 967


Script:

#!/bin/bash
# Let's verify how the promo code is being handled in the Cashout component
ast-grep --pattern 'function Cashout($_) {
  $$$
  setAppliedPromoCode($_)
  $$$
}'

# Check for promo code usage in the component
rg -A 5 'setAppliedPromoCode\(' src/components/Cashout/Cashout.tsx

# Check how PromoCodeChecker is used
rg -A 5 '<PromoCodeChecker'

Length of output: 680


Script:

#!/bin/bash
# Let's check the implementation of Confirm.view.tsx to understand the promo code handling
ast-grep --pattern 'function $_ {
  $$$
  handlePromoCodeApplied($_) {
    $$$
  }
  $$$
}'

# Check for promo code state in Confirm.view.tsx
rg -B 5 'handlePromoCodeApplied' src/components/Offramp/Confirm.view.tsx

# Check the PromoCodeChecker component implementation
cat src/components/Offramp/PromoCodeChecker.tsx

Length of output: 5661

Comment on lines +35 to +49
const calculateAmount = () => {
if (offrampType === _consts.OfframpType.CASHOUT) {
// add safeguards for usd value
if (!usdValue || isNaN(parseFloat(usdValue))) {
return '0.00'
}
return utils.formatTokenAmount(parseFloat(usdValue))
} else {
// for CLAIM type
if (!tokenPrice || !claimLinkData || isNaN(tokenPrice) || isNaN(parseFloat(claimLinkData.tokenAmount))) {
return '0.00'
}
return utils.formatTokenAmount(tokenPrice * parseFloat(claimLinkData.tokenAmount))
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace global isNaN with Number.isNaN for safer type checking.

The calculateAmount function implementation is good, but uses the global isNaN which can lead to unexpected type coercion.

Apply this diff to fix the type checking:

 const calculateAmount = () => {
     if (offrampType === _consts.OfframpType.CASHOUT) {
         // add safeguards for usd value
-        if (!usdValue || isNaN(parseFloat(usdValue))) {
+        if (!usdValue || Number.isNaN(parseFloat(usdValue))) {
             return '0.00'
         }
         return utils.formatTokenAmount(parseFloat(usdValue))
     } else {
         // for CLAIM type
-        if (!tokenPrice || !claimLinkData || isNaN(tokenPrice) || isNaN(parseFloat(claimLinkData.tokenAmount))) {
+        if (!tokenPrice || !claimLinkData || Number.isNaN(tokenPrice) || Number.isNaN(parseFloat(claimLinkData.tokenAmount))) {
             return '0.00'
         }
         return utils.formatTokenAmount(tokenPrice * parseFloat(claimLinkData.tokenAmount))
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const calculateAmount = () => {
if (offrampType === _consts.OfframpType.CASHOUT) {
// add safeguards for usd value
if (!usdValue || isNaN(parseFloat(usdValue))) {
return '0.00'
}
return utils.formatTokenAmount(parseFloat(usdValue))
} else {
// for CLAIM type
if (!tokenPrice || !claimLinkData || isNaN(tokenPrice) || isNaN(parseFloat(claimLinkData.tokenAmount))) {
return '0.00'
}
return utils.formatTokenAmount(tokenPrice * parseFloat(claimLinkData.tokenAmount))
}
}
const calculateAmount = () => {
if (offrampType === _consts.OfframpType.CASHOUT) {
// add safeguards for usd value
if (!usdValue || Number.isNaN(parseFloat(usdValue))) {
return '0.00'
}
return utils.formatTokenAmount(parseFloat(usdValue))
} else {
// for CLAIM type
if (!tokenPrice || !claimLinkData || Number.isNaN(tokenPrice) || Number.isNaN(parseFloat(claimLinkData.tokenAmount))) {
return '0.00'
}
return utils.formatTokenAmount(tokenPrice * parseFloat(claimLinkData.tokenAmount))
}
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 38-38: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 44-44: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 44-44: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@kushagrasarathe kushagrasarathe changed the title fix: fee calculation after promo code is applied [TASK-7762] fix: fee calculation after promo code is applied Dec 20, 2024
@notion-workspace
Copy link
Copy Markdown

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/components/Offramp/Success.view.tsx (1)

Line range hint 59-67: Extract repeated promo code messages into a reusable function.

The promo code and fee explanation messages are duplicated in multiple places. Consider extracting these into a reusable function for better maintainability.

+ const getFeeMessage = (appliedPromoCode: string | undefined, accountType: string) => {
+   if (appliedPromoCode) {
+     return `Fees waived with promo code ${appliedPromoCode}`;
+   }
+   return `For ${accountType === 'iban' ? 'SEPA' : 'ACH'} transactions a fee of ${
+     accountType === 'iban' ? '$1' : '$0.50'
+   } is charged.`;
+ };

  <MoreInfo
-   text={
-     appliedPromoCode
-       ? `Fees waived with promo code ${appliedPromoCode}`
-       : `For ${accountType === 'iban' ? 'SEPA' : 'ACH'} transactions a fee of ${
-           accountType === 'iban' ? '$1' : '$0.50'
-         } is charged.`
-   }
+   text={getFeeMessage(appliedPromoCode, accountType)}
  />
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 03a3739 and 17279cb.

📒 Files selected for processing (1)
  • src/components/Offramp/Success.view.tsx (3 hunks)
🔇 Additional comments (1)
src/components/Offramp/Success.view.tsx (1)

Line range hint 1-150: Verify financial calculations and edge cases.

Since this component handles financial calculations and fee processing, please ensure:

  1. All monetary values are handled with proper precision
  2. Edge cases like zero amounts, missing values, and invalid inputs are handled correctly
  3. Fee calculations are consistent with business requirements
✅ Verification successful

Based on the gathered information, I can now generate the final response:

Financial calculations and edge cases have been verified.

The implementation shows proper handling of financial calculations with several safety measures in place:

  • Fees are correctly calculated based on account type (SEPA: $1.00, ACH: $0.50) with promo code support
  • Token amounts are properly formatted using utils.formatTokenAmount which handles decimal precision
  • Edge cases are handled:
    • Promo codes zeroing out fees
    • Null/undefined checks for usdValue and tokenAmount
    • Proper decimal handling through parseFloat and formatting utilities
  • Fee calculations are consistent across both the success and confirmation views
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other financial calculation implementations to verify consistency
rg -A 5 "formatTokenAmount|parseFloat|calculateFee" --type typescript

# Look for test files covering these calculations
fd -e test.tsx -e spec.tsx -e test.ts -e spec.ts | xargs rg "OfframpSuccessView|calculateFee"

Length of output: 202


Script:

#!/bin/bash
# Search for financial calculations with proper file extensions
rg -A 5 "formatTokenAmount|parseFloat|calculateFee" --type ts --type tsx

# Look for test files and their contents
fd -e .test.tsx -e .spec.tsx -e .test.ts -e .spec.ts | xargs cat

# Search for utils.formatTokenAmount usage
rg "utils\.formatTokenAmount" --type ts --type tsx -A 2

# Search for similar fee calculation patterns
rg "fee.*iban|SEPA.*fee|ACH.*fee" --type ts --type tsx -A 2

Length of output: 10398


Script:

#!/bin/bash
# Try searching without file type specifications
rg "utils\.formatTokenAmount" -A 2

# Search for the utils file that contains formatTokenAmount
fd formatTokenAmount

# Look for fee-related calculations
rg "calculateFee|fee.*iban|SEPA.*fee|ACH.*fee" -A 3

# Search for the utils file
fd "utils.(ts|js)" --type f

Length of output: 11981


Script:

#!/bin/bash
# Check the implementation of formatTokenAmount in utils
cat src/utils/format.utils.ts

# Look for any other fee-related calculations in utils files
cat src/utils/cashout.utils.ts

# Check for any validation or error handling related to amounts
rg "parseFloat|Number|\.toFixed" src/utils/

Length of output: 25893

@Hugo0 Hugo0 merged commit c2f2feb into develop Dec 22, 2024
@coderabbitai coderabbitai bot mentioned this pull request Feb 6, 2025
@Hugo0 Hugo0 deleted the fix/promo-checker branch July 3, 2025 18:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants