Skip to content

✨ Add Japanese Yen (JPY) currency support #23151

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

mtane0412
Copy link

@mtane0412 mtane0412 commented May 2, 2025

This commit introduces support for the Japanese Yen (JPY) currency. The following changes were made:

  • Added JPY to the list of supported currencies in apps/admin-x-settings/src/utils/currency.ts and ghost/admin/app/utils/currency.js.
  • Updated currencyToDecimal and currencyFromDecimal functions to handle zero-decimal currencies correctly.
  • Updated getNonDecimal function to handle zero-decimal currencies correctly.
  • Updated getSubscriptionData function to use the updated getNonDecimal function.
  • Updated PaymentsService to handle zero-decimal currencies correctly when creating and retrieving prices from Stripe.
  • Added JPY to the milestones test data in ghost/core/test/unit/server/services/milestones/ MilestonesService.test.js.

These changes ensure that the application correctly handles JPY and other zero-decimal currencies, improving accuracy and functionality.

Got some code for us? Awesome 🎊!

Please take a minute to explain the change you're making:

  • Why are you making it?
    • I am running a Ghost media for Japanese and needed JPY as the currency, and since JPY is a Non-Decimal Currency on Stripe, I also needed to make sure that Stripe would process it correctly.
  • What does it do?
    • Add JPY to Ghost's settlement currency and divide the amount by 100 to determine Non Decimal Currency and ensure that it is processed correctly on Stripe.
  • Why is this something Ghost users or developers need?
    • There have been requests in past forums for JPY to be added, but it was not addressed for a long time. I also run a media outlet for Japanese people and needed the ability to settle payments in JPY.

Please check your PR against these items:

  • I've read and followed the Contributor Guide
  • I've explained my change
  • I've written an automated test to prove my change works
    • I added the test but I am not confident. I need help.

We appreciate your contribution! 🙏

mtane0412 added 2 commits May 2, 2025 20:57
This commit introduces support for the Japanese Yen (JPY)
currency.  The following changes were made:

- Added JPY to the list of supported currencies in
  `apps/admin-x-settings/src/utils/currency.ts` and
  `ghost/admin/app/utils/currency.js`.
- Updated `currencyToDecimal` and `currencyFromDecimal`
  functions to handle zero-decimal currencies correctly.
- Updated `getNonDecimal` function to handle zero-decimal
  currencies correctly.
- Updated `getSubscriptionData` function to use the
  updated `getNonDecimal` function.
- Updated `PaymentsService` to handle zero-decimal
  currencies correctly when creating and retrieving prices
  from Stripe.
- Added JPY to the milestones test data in
  `ghost/core/test/unit/server/services/milestones/
  MilestonesService.test.js`.

These changes ensure that the application correctly handles
JPY and other zero-decimal currencies, improving accuracy
and functionality.
Copy link
Contributor

coderabbitai bot commented May 2, 2025

Walkthrough

The changes implement support for zero-decimal currencies across multiple modules by introducing a constant array of zero-decimal currency codes and a helper function isZeroDecimalCurrency to identify such currencies. Currency conversion utilities are updated to accept an optional currency parameter and adjust their logic to avoid dividing or multiplying amounts by 100 for zero-decimal currencies. The Japanese Yen (JPY) is added to currency lists and milestone configurations. Payment service methods interacting with Stripe are modified to correctly handle zero-decimal currency amounts when comparing prices and creating Stripe prices. Additionally, the subscription data processing is updated to pass currency context for accurate amount conversion. Test suites are extended to include JPY-related scenarios, verifying correct milestone handling without altering existing public API signatures except for the added optional currency parameters in relevant functions.


📜 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 8df1ddd and 5a0b98c.

📒 Files selected for processing (1)
  • ghost/core/test/unit/server/services/milestones/MilestonesService.test.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • ghost/core/test/unit/server/services/milestones/MilestonesService.test.js
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • 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.

Support

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

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in 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
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
apps/admin-x-settings/src/utils/currency.ts (1)

219-242: 💡 Verification agent

🧩 Analysis chain

Verify validation function compatibility with zero-decimal currencies

The validateCurrencyAmount function multiplies minimum and maximum amounts by 100 during validation, which assumes currencies use minor units. While JPY has a specific minimum amount defined (100), you should verify this function works correctly for all zero-decimal currencies.


🏁 Script executed:

#!/bin/bash
# Check if validateCurrencyAmount would work correctly for zero-decimal currencies

# First, let's show the implementation of validateCurrencyAmount
echo "Checking validateCurrencyAmount implementation..."
cat "apps/admin-x-settings/src/utils/currency.ts" | grep -A 25 "export function validateCurrencyAmount"

# Look for any usage of validateCurrencyAmount with zero-decimal currencies
echo -e "\nChecking for usages of validateCurrencyAmount with zero-decimal currencies..."
rg "validateCurrencyAmount.*JPY|validateCurrencyAmount.*currency.*JPY|validateCurrencyAmount.*zeroDecimal" -A 5 -B 5

Length of output: 1252


🏁 Script executed:

#!/bin/bash
# Inspect the implementation of minimumAmountForCurrency
echo "=== minimumAmountForCurrency implementation ==="
rg -n -C5 "function minimumAmountForCurrency" apps/admin-x-settings/src/utils/currency.ts

# Search for currency metadata (decimals / zeroDecimal flags)
echo -e "\n=== Currency metadata (decimals / zeroDecimal) ==="
rg -n "decimals" -C3 apps/admin-x-settings/src/utils
rg -n "zeroDecimal" -C3 .

# Verify getSymbol currency lookup mapping as well
echo -e "\n=== getSymbol implementation ==="
rg -n -C5 "function getSymbol" apps/admin-x-settings/src/utils/currency.ts

Length of output: 4729


Update validateCurrencyAmount to handle zero-decimal currencies correctly

The current implementation always multiplies the major-unit minimum/maximum by 100, which only works for currencies with two minor-unit decimals. Zero-decimal currencies (e.g. JPY, KRW, VND) use a factor of 1.

In apps/admin-x-settings/src/utils/currency.ts → validateCurrencyAmount:

• Import and use isZeroDecimalCurrency to derive the minor-unit factor:

import {isZeroDecimalCurrency} from './currency';

const unit = isZeroDecimalCurrency(currency) ? 1 : 100;

• Replace hard-coded * 100 with * unit:

-    if (cents !== 0 && cents < (minAmount * 100)) {
-        return `Non-zero amount must be at least ${symbol}${minAmount}.`;
-    }
+    if (cents !== 0 && cents < (minAmount * unit)) {
+        return `Non-zero amount must be at least ${symbol}${minAmount}.`;
+    }

-    if (maxAmount && cents !== 0 && cents > (maxAmount * 100)) {
-        return `Suggested amount cannot be more than ${symbol}${maxAmount}.`;
-    }
+    if (maxAmount && cents !== 0 && cents > (maxAmount * unit)) {
+        return `Suggested amount cannot be more than ${symbol}${maxAmount}.`;
+    }

This ensures the correct threshold for both two-decimal and zero-decimal currencies.

🧹 Nitpick comments (3)
ghost/core/test/unit/server/services/milestones/MilestonesService.test.js (1)

82-97: Proper test case for JPY milestone creation, but fix coding style.

The new test thoroughly verifies that JPY milestones are correctly created, which is crucial for ensuring the feature works as expected.

Fix the brace style to match project conventions:

  async getARR() { return [{currency: 'jpy', arr: 750}]; },
- async hasImportedMembersInPeriod() { return false; },
- async getDefaultCurrency() { return 'jpy'; }
+ async hasImportedMembersInPeriod() { 
+     return false; 
+ },
+ async getDefaultCurrency() { 
+     return 'jpy'; 
+ }
🧰 Tools
🪛 ESLint

[error] 88-88: Statement inside of curly braces should be on next line.

(brace-style)


[error] 88-88: Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.

(brace-style)


[error] 89-89: Statement inside of curly braces should be on next line.

(brace-style)


[error] 89-89: Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.

(brace-style)


[error] 90-90: Statement inside of curly braces should be on next line.

(brace-style)


[error] 90-90: Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.

(brace-style)

ghost/core/core/server/services/members/members-api/services/PaymentsService.js (2)

442-449: Correct handling of zero-decimal currencies in Stripe price comparison.

This properly compares Stripe's unit_amount with the expected amount based on whether the currency is zero-decimal or not. For zero-decimal currencies like JPY, it correctly divides by 100 to account for how Ghost stores prices internally versus how Stripe expects them.

Add a clarifying comment about why we're dividing by 100 for zero-decimal currencies:

  // For comparison with Stripe's unit_amount, we need to handle zero-decimal currencies
  // For zero-decimal currencies, Stripe's unit_amount will be the same as our tierAmount
  // For other currencies, Stripe's unit_amount will be 100x our tierAmount
+ // We divide by 100 for zero-decimal currencies because our amounts are stored in cents internally,
+ // but Stripe expects them in the base currency units (e.g., 1 yen instead of 100 cents)
  const expectedUnitAmount = isZeroDecimalCurrency(tier.currency)
      ? tierAmount / 100
      : tierAmount;

484-486: Proper handling of zero-decimal currencies when creating Stripe prices.

This correctly formats the amount for Stripe based on whether the currency is zero-decimal or not, ensuring that prices are created with the correct amounts in Stripe.

Similar to above, add a clarifying comment about the division by 100:

  // For zero-decimal currencies like JPY, we don't need to multiply by 100
  // For other currencies, Stripe expects the amount in cents (smallest currency unit)
+ // We divide by 100 for zero-decimal currencies because our amounts are stored in cents internally,
+ // but for currencies like JPY, Stripe expects amounts in whole yen, not "cents of yen"
  const amount = isZeroDecimalCurrency(tier.currency)
      ? priceAmount / 100
      : priceAmount;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 80aa346 and 8df1ddd.

📒 Files selected for processing (5)
  • apps/admin-x-settings/src/utils/currency.ts (2 hunks)
  • ghost/admin/app/utils/currency.js (2 hunks)
  • ghost/admin/app/utils/subscription-data.js (1 hunks)
  • ghost/core/core/server/services/members/members-api/services/PaymentsService.js (4 hunks)
  • ghost/core/test/unit/server/services/milestones/MilestonesService.test.js (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
ghost/admin/app/utils/subscription-data.js (1)
ghost/admin/app/utils/currency.js (1)
  • getNonDecimal (138-143)
apps/admin-x-settings/src/utils/currency.ts (2)
ghost/admin/app/utils/currency.js (2)
  • zeroDecimalCurrencies (132-132)
  • isZeroDecimalCurrency (134-136)
ghost/core/core/server/services/members/members-api/services/PaymentsService.js (1)
  • zeroDecimalCurrencies (8-8)
ghost/admin/app/utils/currency.js (2)
ghost/core/core/server/services/members/members-api/services/PaymentsService.js (1)
  • zeroDecimalCurrencies (8-8)
apps/admin-x-settings/src/utils/currency.ts (1)
  • isZeroDecimalCurrency (159-161)
🪛 ESLint
ghost/core/test/unit/server/services/milestones/MilestonesService.test.js

[error] 88-88: Statement inside of curly braces should be on next line.

(brace-style)


[error] 88-88: Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.

(brace-style)


[error] 89-89: Statement inside of curly braces should be on next line.

(brace-style)


[error] 89-89: Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.

(brace-style)


[error] 90-90: Statement inside of curly braces should be on next line.

(brace-style)


[error] 90-90: Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.

(brace-style)

🔇 Additional comments (11)
ghost/admin/app/utils/subscription-data.js (1)

20-20: Updated to handle zero-decimal currencies correctly.

The code now passes the currency code to getNonDecimal which will correctly handle zero-decimal currencies like JPY by not dividing by 100 when appropriate.

ghost/core/test/unit/server/services/milestones/MilestonesService.test.js (1)

37-41: Added JPY to supported milestones currencies.

This correctly adds Japanese Yen to the supported milestone currencies with the same milestone values as other currencies.

ghost/admin/app/utils/currency.js (3)

56-56: Added JPY to supported currencies.

Japanese Yen has been correctly added to the currencies list, which is required for proper dropdown selection and display throughout the application.


131-136: Added zero-decimal currencies support.

This addition of the zeroDecimalCurrencies array and the isZeroDecimalCurrency helper function properly identifies currencies that don't use minor units, following Stripe's conventions.


138-142: Updated getNonDecimal to handle zero-decimal currencies.

The function now correctly checks if a currency is zero-decimal and returns the amount unchanged if so, otherwise dividing by 100 as before. This is essential for proper amount display, particularly for JPY.

ghost/core/core/server/services/members/members-api/services/PaymentsService.js (1)

7-17: Implemented zero-decimal currency support.

The addition of the zeroDecimalCurrencies array and isZeroDecimalCurrency helper function is well-documented and follows the same pattern as implemented in the admin utilities.

apps/admin-x-settings/src/utils/currency.ts (5)

63-63: Excellent addition of JPY to currency options

Adding Japanese Yen to the supported currencies list will enable appropriate representation in the UI. This aligns with the PR objective of adding JPY support to the platform.


156-157: Appropriate implementation of zero-decimal currencies list

The constant and comment correctly define currencies that don't use minor units (including JPY). This implementation matches the constants in other parts of the codebase like ghost/admin/app/utils/currency.js and ensures consistent handling across the application.


159-161: Well-implemented helper function

The isZeroDecimalCurrency function correctly:

  • Handles case-insensitivity with toUpperCase()
  • Uses optional chaining to safely handle null/undefined
  • Returns a boolean as expected

This implementation is consistent with similar helper functions in other parts of the codebase.


163-168: Proper handling of zero-decimal currencies in conversion function

The currencyToDecimal function has been appropriately updated to:

  • Accept an optional currency parameter (maintaining backward compatibility)
  • Skip division by 100 for zero-decimal currencies
  • Maintain existing behavior for decimal currencies

This change is essential for correctly handling JPY and other zero-decimal currencies.


170-174: Correct implementation for inverse conversion

The currencyFromDecimal function has been properly updated with the same pattern as currencyToDecimal, ensuring symmetrical conversion behavior for zero-decimal currencies. This ensures amounts are not incorrectly multiplied by 100 for currencies like JPY.

mtane0412 added 3 commits May 2, 2025 21:42
The changes improve the readability of the code by adding line breaks to the asynchronous functions within the queries object.  This enhances maintainability and understanding of the test suite.
Copy link

codecov bot commented May 3, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 71.84%. Comparing base (dc0c405) to head (4ff59ac).
Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #23151   +/-   ##
=======================================
  Coverage   71.84%   71.84%           
=======================================
  Files        1435     1435           
  Lines       99367    99369    +2     
  Branches    12201    12201           
=======================================
+ Hits        71388    71390    +2     
  Misses      26989    26989           
  Partials      990      990           
Flag Coverage Δ
admin-tests 48.58% <100.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@cathysarisky
Copy link
Member

cathysarisky commented May 5, 2025

Hey @mtane0412 !

(I'm not a Ghost Foundation employee, just an open-source contributor. )

I can't tell you anything for sure, but I don't think this could be merged without a whole bunch of new tests. (And indeed, you don't want it to get merged without new tests, because you don't want to break something.) For best success on getting the core team to evaluate and merge it, you should write a set of tests that demonstrate that it works. I'd take a look at the existing tests, and basically try to add one that tests JPY in the same way other currencies are being tested.

Aside: How's it look in Portal? I'd be a little bit surprised if you didn't need some changes there, too...

p.s. I started the test suite. Passing that will be a good start (but definitely not enough). I recommend getting your tests (old and new) all passing on your local install, then pushing changes here to confirm that they're good on CI also. You can @ me if you need me to get your tests started again (after confirming they work locally as much as possible) - tests here won't auto-run for you since you're new.

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