From f02510eff178bf6bb2152c631fa8d70d09f5bf32 Mon Sep 17 00:00:00 2001 From: Lobster <66687899+LobsterEnigma@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:19:16 -0500 Subject: [PATCH] fix(subscription): respect site currency display mode --- .../payment_webhook_availability_test.go | 116 +++++++++++ controller/subscription.go | 18 +- model/subscription.go | 34 ++- .../__tests__/subscription-currency.test.tsx | 196 ++++++++++++++++++ .../dialogs/subscription-purchase-dialog.tsx | 87 ++++---- .../dialogs/user-subscriptions-dialog.tsx | 5 +- .../components/subscriptions-columns.tsx | 13 +- .../subscriptions-mutate-drawer.tsx | 20 +- web/src/features/subscriptions/lib/format.ts | 15 ++ web/src/features/subscriptions/lib/index.ts | 7 +- web/src/features/subscriptions/types.ts | 2 + .../components/subscription-plans-card.tsx | 11 +- web/src/i18n/locales/en.json | 4 + web/src/i18n/locales/fr.json | 4 + web/src/i18n/locales/ja.json | 4 + web/src/i18n/locales/ru.json | 4 + web/src/i18n/locales/vi.json | 4 + web/src/i18n/locales/zh-TW.json | 4 + web/src/i18n/locales/zh.json | 4 + web/src/lib/currency.ts | 13 +- 20 files changed, 481 insertions(+), 84 deletions(-) create mode 100644 web/src/features/subscriptions/components/__tests__/subscription-currency.test.tsx diff --git a/controller/payment_webhook_availability_test.go b/controller/payment_webhook_availability_test.go index 3e6aed964341..295f56d86abd 100644 --- a/controller/payment_webhook_availability_test.go +++ b/controller/payment_webhook_availability_test.go @@ -5,10 +5,12 @@ import ( "crypto/rsa" "crypto/x509" "encoding/base64" + "fmt" "maps" "net/http" "net/http/httptest" "net/url" + "os" "strings" "testing" @@ -36,6 +38,120 @@ func confirmPaymentComplianceForTest(t *testing.T) { paymentSetting.ComplianceTermsVersion = operation_setting.CurrentComplianceTermsVersion } +func TestSubscriptionPriceFollowsSiteCurrency(t *testing.T) { + setupEpayCallbackTest(t) + operation_setting.GetPaymentSetting().EpaySignType = operation_setting.EpaySignTypeMD5 + operation_setting.EpayKey = "test_key" + previousDB, previousLogDB := model.DB, model.LOG_DB + previousMain, previousLog := common.MainDatabaseType(), common.LogDatabaseType() + previousRate, previousUnit := operation_setting.USDExchangeRate, common.QuotaPerUnit + general := operation_setting.GetGeneralSetting() + previousDisplayType := general.QuotaDisplayType + previousRedis := common.RedisEnabled + common.RedisEnabled = false + t.Cleanup(func() { + model.DB, model.LOG_DB = previousDB, previousLogDB + common.SetMainDatabaseType(previousMain) + common.SetLogDatabaseType(previousLog) + operation_setting.USDExchangeRate, common.QuotaPerUnit = previousRate, previousUnit + general.QuotaDisplayType = previousDisplayType + common.RedisEnabled = previousRedis + }) + operation_setting.USDExchangeRate, common.QuotaPerUnit = 7, 500000 + + for _, tc := range []struct { + kind common.DatabaseType + env string + version string + }{ + {common.DatabaseTypeSQLite, "", "SELECT sqlite_version()"}, + {common.DatabaseTypeMySQL, "TEST_MYSQL_DSN", "SELECT VERSION()"}, + {common.DatabaseTypePostgreSQL, "TEST_POSTGRES_DSN", "SHOW server_version"}, + } { + t.Run(string(tc.kind), func(t *testing.T) { + general.QuotaDisplayType = operation_setting.QuotaDisplayTypeCNY + dsn := os.Getenv(tc.env) + if tc.env != "" && dsn == "" { + t.Skip(tc.env + " is not configured") + } + db, _ := newAuditTestDatabase(t, string(tc.kind), dsn) + model.DB, model.LOG_DB = db, db + common.SetMainDatabaseType(tc.kind) + common.SetLogDatabaseType(tc.kind) + var version string + require.NoError(t, db.Raw(tc.version).Scan(&version).Error) + t.Logf("%s %s", tc.kind, version) + require.NoError(t, db.AutoMigrate( + &model.SubscriptionPlan{}, &model.SubscriptionOrder{}, &model.UserSubscription{}, + &model.User{}, &model.SystemTask{}, &model.Log{}, + )) + user := model.User{Username: "subscription-buyer", Quota: 50_000_000} + require.NoError(t, db.Create(&user).Error) + + router := gin.New() + router.Use(func(c *gin.Context) { c.Set("id", user.Id) }) + router.POST("/plans", AdminCreateSubscriptionPlan) + router.GET("/plans", GetSubscriptionPlans) + router.POST("/balance", SubscriptionRequestBalancePay) + router.POST("/epay", SubscriptionRequestEpay) + request := func(method, path, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, req) + require.Equal(t, http.StatusOK, recorder.Code) + return recorder + } + + response := request(http.MethodPost, "/plans", `{"plan":{"title":"Plan","price_amount":50,"total_amount":4285714,"enabled":true}}`) + var created struct { + Success bool `json:"success"` + Data model.SubscriptionPlan `json:"data"` + } + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &created)) + require.True(t, created.Success, response.Body.String()) + planID := created.Data.Id + t.Cleanup(func() { model.InvalidateSubscriptionPlanCache(planID) }) + + response = request(http.MethodGet, "/plans", "") + var listed struct { + Data []SubscriptionPlanDTO `json:"data"` + } + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &listed)) + require.Len(t, listed.Data, 1) + assert.Equal(t, 50.0, listed.Data[0].Plan.PriceAmount) + require.NotNil(t, listed.Data[0].BalanceQuota) + assert.Equal(t, 3_571_429, *listed.Data[0].BalanceQuota) + + response = request(http.MethodPost, "/epay", fmt.Sprintf(`{"plan_id":%d,"payment_method":"alipay"}`, planID)) + var checkout struct { + Message string `json:"message"` + Data map[string]string `json:"data"` + } + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &checkout)) + require.Equal(t, "success", checkout.Message) + assert.Equal(t, "50.00", checkout.Data["money"]) + + response = request(http.MethodPost, "/balance", fmt.Sprintf(`{"plan_id":%d,"expected_quota":1}`, planID)) + assert.Contains(t, response.Body.String(), "The balance price changed.") + response = request(http.MethodPost, "/balance", fmt.Sprintf(`{"plan_id":%d,"expected_quota":3571429}`, planID)) + require.Contains(t, response.Body.String(), `"success":true`) + require.NoError(t, db.First(&user, user.Id).Error) + assert.Equal(t, 46_428_571, user.Quota) + + general.QuotaDisplayType = operation_setting.QuotaDisplayTypeUSD + listed.Data = nil + response = request(http.MethodGet, "/plans", "") + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &listed)) + require.Len(t, listed.Data, 1) + assert.Equal(t, 50.0, listed.Data[0].Plan.PriceAmount) + require.NotNil(t, listed.Data[0].BalanceQuota) + assert.Equal(t, 25_000_000, *listed.Data[0].BalanceQuota) + }) + } +} + func TestStripeWebhookEnabledRequiresTopUpAndWebhookConfig(t *testing.T) { confirmPaymentComplianceForTest(t) originalAPISecret := setting.StripeApiSecret diff --git a/controller/subscription.go b/controller/subscription.go index 4f9ed09b107c..3c4d6449f7a7 100644 --- a/controller/subscription.go +++ b/controller/subscription.go @@ -15,7 +15,8 @@ import ( // ---- Shared types ---- type SubscriptionPlanDTO struct { - Plan model.SubscriptionPlan `json:"plan"` + Plan model.SubscriptionPlan `json:"plan"` + BalanceQuota *int `json:"balance_quota,omitempty"` } type BillingPreferenceRequest struct { @@ -23,7 +24,8 @@ type BillingPreferenceRequest struct { } type SubscriptionBalancePayRequest struct { - PlanId int `json:"plan_id"` + PlanId int `json:"plan_id"` + ExpectedQuota *int `json:"expected_quota"` } // ---- User APIs ---- @@ -42,9 +44,13 @@ func GetSubscriptionPlans(c *gin.Context) { result := make([]SubscriptionPlanDTO, 0, len(plans)) for _, p := range plans { p.NormalizeDefaults() - result = append(result, SubscriptionPlanDTO{ - Plan: p, - }) + record := SubscriptionPlanDTO{Plan: p} + if *p.AllowBalancePay { + if quota, err := p.BalanceQuota(); err == nil { + record.BalanceQuota = "a + } + } + result = append(result, record) } common.ApiSuccess(c, result) } @@ -108,7 +114,7 @@ func SubscriptionRequestBalancePay(c *gin.Context) { return } - if err := model.PurchaseSubscriptionWithBalance(userId, req.PlanId); err != nil { + if err := model.PurchaseSubscriptionWithBalance(userId, req.PlanId, req.ExpectedQuota); err != nil { common.ApiError(c, err) return } diff --git a/model/subscription.go b/model/subscription.go index 5cc6e12649ba..57d24b1f77f4 100644 --- a/model/subscription.go +++ b/model/subscription.go @@ -3,6 +3,7 @@ package model import ( "errors" "fmt" + "math" "strconv" "strings" "sync" @@ -10,6 +11,7 @@ import ( "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/pkg/cachex" + "github.com/QuantumNous/new-api/setting/operation_setting" "github.com/samber/hot" "github.com/shopspring/decimal" "gorm.io/gorm" @@ -754,21 +756,31 @@ func AdminBindSubscription(userId int, planId int, sourceNote string) (*common.M return nil, nil } -func calcSubscriptionBalanceQuota(priceAmount float64) (int, error) { - if priceAmount <= 0 { +// BalanceQuota returns the wallet quota charged for the plan price. +func (p SubscriptionPlan) BalanceQuota() (int, error) { + if p.PriceAmount < 0 || math.IsNaN(p.PriceAmount) || math.IsInf(p.PriceAmount, 0) { + return 0, common.NewMessage("Price cannot be negative") + } + if p.PriceAmount == 0 { return 0, nil } - if common.QuotaPerUnit <= 0 { + if common.QuotaPerUnit <= 0 || math.IsNaN(common.QuotaPerUnit) || math.IsInf(common.QuotaPerUnit, 0) { return 0, common.NewMessage("Quota unit is misconfigured") } - quota := decimal.NewFromFloat(priceAmount). - Mul(decimal.NewFromFloat(common.QuotaPerUnit)). - Ceil() + rate := operation_setting.GetUsdToCurrencyRate(operation_setting.USDExchangeRate) + if rate <= 0 || math.IsNaN(rate) || math.IsInf(rate, 0) { + return 0, common.NewMessage("Balance payment is unavailable") + } + amount := decimal.NewFromFloat(p.PriceAmount).Mul(decimal.NewFromFloat(common.QuotaPerUnit)) + quota, remainder := amount.QuoRem(decimal.NewFromFloat(rate), 0) + if remainder.IsPositive() { + quota = quota.Add(decimal.NewFromInt(1)) + } return common.WalletQuotaFromDecimalStrict(quota) } // PurchaseSubscriptionWithBalance creates a subscription by deducting the user's wallet quota. -func PurchaseSubscriptionWithBalance(userId int, planId int) error { +func PurchaseSubscriptionWithBalance(userId int, planId int, expectedQuota *int) error { if userId <= 0 || planId <= 0 { return errors.New("invalid userId or planId") } @@ -785,17 +797,17 @@ func PurchaseSubscriptionWithBalance(userId int, planId int) error { if !plan.Enabled { return common.NewMessage("Subscription plan is not enabled") } - if plan.PriceAmount < 0 { - return common.NewMessage("Price cannot be negative") - } if plan.AllowBalancePay != nil && !*plan.AllowBalancePay { return common.NewMessage("This plan does not allow balance redemption") } - requiredQuota, err := calcSubscriptionBalanceQuota(plan.PriceAmount) + requiredQuota, err := plan.BalanceQuota() if err != nil { return err } + if expectedQuota != nil && *expectedQuota != requiredQuota { + return common.NewMessage("The balance price changed. Refresh and try again.") + } var user User if err := lockForUpdate(tx).Where("id = ?", userId).First(&user).Error; err != nil { diff --git a/web/src/features/subscriptions/components/__tests__/subscription-currency.test.tsx b/web/src/features/subscriptions/components/__tests__/subscription-currency.test.tsx new file mode 100644 index 000000000000..294d42cc9991 --- /dev/null +++ b/web/src/features/subscriptions/components/__tests__/subscription-currency.test.tsx @@ -0,0 +1,196 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, expect, it, vi } from 'vitest' + +import { toIntlLocale } from '@/i18n/languages' +import { api } from '@/lib/api' +import { formatLocalCurrencyAmount } from '@/lib/currency' +import { + DEFAULT_CURRENCY_CONFIG, + useSystemConfigStore, +} from '@/stores/system-config-store' + +import { subscriptionPlanSchema } from '../../types' +import { SubscriptionPurchaseDialog } from '../dialogs/subscription-purchase-dialog' +import { SubscriptionsMutateDrawer } from '../subscriptions-mutate-drawer' +import { SubscriptionsProvider } from '../subscriptions-provider' + +const plan = subscriptionPlanSchema.parse({ + id: 1, + title: 'Budget Pro', + price_amount: 50, + currency: 'USD', + duration_unit: 'month', + duration_value: 1, + quota_reset_period: 'never', + enabled: true, + sort_order: 0, + max_purchase_per_user: 0, + total_amount: 4_285_714, +}) + +const initialConfig = useSystemConfigStore.getState().config + +afterEach(() => { + useSystemConfigStore.getState().setConfig(initialConfig) +}) + +it('uses the site currency for the same price when the display mode changes', () => { + useSystemConfigStore + .getState() + .setConfig({ currency: DEFAULT_CURRENCY_CONFIG }) + render( + + ) + const dialog = within(screen.getByRole('dialog')) + expect(dialog.getByText('$50')).toBeVisible() + + act(() => { + useSystemConfigStore.getState().setConfig({ + currency: { + ...DEFAULT_CURRENCY_CONFIG, + quotaDisplayType: 'CNY', + usdExchangeRate: 7, + }, + }) + }) + expect(dialog.getByText('¥50')).toBeVisible() +}) + +it('shows the same CNY price for the plan and the wallet deduction', async () => { + useSystemConfigStore.getState().setConfig({ + currency: { + ...DEFAULT_CURRENCY_CONFIG, + quotaDisplayType: 'CNY', + usdExchangeRate: 7, + }, + }) + const pay = vi + .spyOn(api, 'post') + .mockResolvedValue({ data: { success: true } }) + const user = userEvent.setup() + render( + + ) + + const dialog = within(screen.getByRole('dialog')) + expect(dialog.getAllByText('¥50')).toHaveLength(2) + expect(dialog.getByText('¥60')).toBeVisible() + await user.click(dialog.getByRole('button', { name: 'Pay with Balance' })) + await waitFor(() => + expect(pay).toHaveBeenCalledWith('/api/subscription/balance/pay', { + plan_id: 1, + expected_quota: 3_571_429, + }) + ) +}) + +it('labels the price and quota fields with the active display currency', async () => { + const { config, setConfig } = useSystemConfigStore.getState() + vi.spyOn(api, 'get').mockResolvedValue({ data: { success: true, data: [] } }) + + setConfig({ + currency: { ...DEFAULT_CURRENCY_CONFIG, quotaDisplayType: 'CNY' }, + }) + const client = new QueryClient() + const editor = render( + + + + + + ) + + try { + const dialog = within(await screen.findByRole('dialog')) + expect( + dialog.getByRole('spinbutton', { name: 'Plan Price (CNY)' }) + ).toBeVisible() + expect( + dialog.getByRole('spinbutton', { name: 'Quota (CNY)' }) + ).toBeVisible() + expect(dialog.queryByLabelText('Pricing currency')).toBeNull() + + act(() => setConfig({ currency: DEFAULT_CURRENCY_CONFIG })) + + expect( + dialog.getByRole('spinbutton', { name: 'Plan Price (USD)' }) + ).toBeVisible() + expect( + dialog.getByRole('spinbutton', { name: 'Quota (USD)' }) + ).toBeVisible() + } finally { + editor.unmount() + client.clear() + setConfig(config) + } +}) + +const currency = { + ...DEFAULT_CURRENCY_CONFIG, + quotaDisplayType: 'CNY' as const, + usdExchangeRate: 7, +} + +it.each([ + ['zhCN', '¥199'], + ['zhTW', '¥199'], + ['en', '¥199'], + ['fr', '199 ¥'], + ['ja', '¥199'], + ['ru', '199 ¥'], + ['vi', '199 ¥'], +])( + 'formats the configured price in %s without applying the exchange rate', + (language, price) => { + expect( + formatLocalCurrencyAmount( + 199, + { locale: toIntlLocale(language) }, + currency + ).replaceAll(/\s/g, ' ') + ).toBe(price) + } +) + +it('uses the runtime locale when the interface language is invalid', () => { + expect( + formatLocalCurrencyAmount( + 199, + { locale: toIntlLocale('invalid_locale') }, + currency + ) + ).toContain('199') +}) diff --git a/web/src/features/subscriptions/components/dialogs/subscription-purchase-dialog.tsx b/web/src/features/subscriptions/components/dialogs/subscription-purchase-dialog.tsx index 230b116c4685..24c13579f242 100644 --- a/web/src/features/subscriptions/components/dialogs/subscription-purchase-dialog.tsx +++ b/web/src/features/subscriptions/components/dialogs/subscription-purchase-dialog.tsx @@ -27,10 +27,8 @@ import { Alert, AlertDescription } from '@/components/ui/alert' import { Button } from '@/components/ui/button' import { Combobox } from '@/components/ui/combobox' import { Separator } from '@/components/ui/separator' -import { useSystemConfig } from '@/hooks/use-system-config' import { formatQuota } from '@/lib/format' import { handleServerError } from '@/lib/handle-server-error' -import { DEFAULT_CURRENCY_CONFIG } from '@/stores/system-config-store' import { paySubscriptionStripe, @@ -39,7 +37,11 @@ import { paySubscriptionWaffoPancake, paySubscriptionBalance, } from '../../api' -import { formatDuration, formatResetPeriod } from '../../lib' +import { + formatDuration, + formatResetPeriod, + useSubscriptionPriceFormatter, +} from '../../lib' import type { PlanRecord } from '../../types' interface PaymentMethod { @@ -64,7 +66,7 @@ interface Props { export function SubscriptionPurchaseDialog(props: Props) { const { t } = useTranslation() - const { currency } = useSystemConfig() + const formatPrice = useSubscriptionPriceFormatter() const [paying, setPaying] = useState(false) const [selectedEpayMethod, setSelectedEpayMethod] = useState('') @@ -85,20 +87,19 @@ export function SubscriptionPurchaseDialog(props: Props) { props.enableWaffoPancake && !!plan.waffo_pancake_product_id const hasEpay = props.enableOnlineTopUp && (props.epayMethods || []).length > 0 - const hasAnyPayment = hasStripe || hasCreem || hasWaffoPancake || hasEpay + const hasHostedCheckout = hasStripe || hasCreem || hasWaffoPancake const totalAmount = Number(plan.total_amount || 0) - const price = Number(plan.price_amount || 0).toFixed(2) - const quotaPerUnit = - currency?.quotaPerUnit && currency.quotaPerUnit > 0 - ? currency.quotaPerUnit - : DEFAULT_CURRENCY_CONFIG.quotaPerUnit - const balanceCost = Math.max( - 0, - Math.ceil(Number(plan.price_amount || 0) * quotaPerUnit) - ) + const balanceCost = props.plan?.balance_quota const userQuota = Math.max(0, Number(props.userQuota || 0)) const allowBalancePay = plan.allow_balance_pay !== false - const insufficientBalance = userQuota < balanceCost + let balanceError: string | undefined + if (!allowBalancePay) { + balanceError = t('This plan does not allow balance redemption') + } else if (balanceCost === undefined) { + balanceError = t('Balance payment is unavailable') + } else if (userQuota < balanceCost) { + balanceError = t('Insufficient balance') + } const limitReached = (props.purchaseLimit || 0) > 0 && (props.purchaseCount || 0) >= (props.purchaseLimit || 0) @@ -207,9 +208,13 @@ export function SubscriptionPurchaseDialog(props: Props) { toast.error(t('This plan does not allow balance redemption')) return } + if (balanceCost === undefined) return setPaying(true) try { - const res = await paySubscriptionBalance({ plan_id: plan.id }) + const res = await paySubscriptionBalance({ + plan_id: plan.id, + expected_quota: balanceCost, + }) if (res.success) { toast.success(t('Subscription purchased successfully')) void props.onPurchaseSuccess?.() @@ -284,9 +289,11 @@ export function SubscriptionPurchaseDialog(props: Props) { )} -
- {t('Amount Due')} - ${price} +
+ {t('Plan Price')} + + {formatPrice(plan.price_amount)} +
@@ -300,44 +307,40 @@ export function SubscriptionPurchaseDialog(props: Props) { )}
-
- {t('Required')} - {formatQuota(balanceCost)} -
-
- {t('Available')} - {formatQuota(userQuota)} -
- {!allowBalancePay ? ( + {allowBalancePay && balanceCost !== undefined && ( + <> +
+ + {t('Balance required')} + + {formatQuota(balanceCost)} +
+
+ {t('Available')} + {formatQuota(userQuota)} +
+ + )} + {balanceError && ( - - {t('This plan does not allow balance redemption')} - + {balanceError} - ) : ( - insufficientBalance && ( - - {t('Insufficient balance')} - - ) )}
- {hasAnyPayment && ( + {(hasHostedCheckout || hasEpay) && (

{t('Select payment method')}

- {(hasStripe || hasCreem || hasWaffoPancake) && ( + {hasHostedCheckout && (
{hasStripe && (
+
. For commercial licensing, please contact support@quantumnous.com */ import type { TFunction } from 'i18next' +import { useCallback } from 'react' +import { useTranslation } from 'react-i18next' +import { toIntlLocale } from '@/i18n/languages' +import { formatLocalCurrencyAmount } from '@/lib/currency' import dayjs from '@/lib/dayjs' +import { useSystemConfigStore } from '@/stores/system-config-store' import type { SubscriptionPlan } from '../types' +export function useSubscriptionPriceFormatter(): (amount: number) => string { + const { i18n } = useTranslation() + const currency = useSystemConfigStore((state) => state.config.currency) + const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language) + return useCallback( + (amount: number) => formatLocalCurrencyAmount(amount, { locale }, currency), + [currency, locale] + ) +} + export function formatDuration( plan: Partial, t: TFunction diff --git a/web/src/features/subscriptions/lib/index.ts b/web/src/features/subscriptions/lib/index.ts index 783d2d05964d..1ea86a6b7f33 100644 --- a/web/src/features/subscriptions/lib/index.ts +++ b/web/src/features/subscriptions/lib/index.ts @@ -16,7 +16,12 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -export { formatDuration, formatResetPeriod, formatTimestamp } from './format' +export { + formatDuration, + formatResetPeriod, + formatTimestamp, + useSubscriptionPriceFormatter, +} from './format' export { getPlanFormSchema, PLAN_FORM_DEFAULTS, diff --git a/web/src/features/subscriptions/types.ts b/web/src/features/subscriptions/types.ts index 1a0203cbedab..3058f1e151f2 100644 --- a/web/src/features/subscriptions/types.ts +++ b/web/src/features/subscriptions/types.ts @@ -50,6 +50,7 @@ export type SubscriptionPlan = z.infer export interface PlanRecord { plan: SubscriptionPlan + balance_quota?: number } // ============================================================================ @@ -92,6 +93,7 @@ export interface PlanPayload { export interface SubscriptionPayRequest { plan_id: number payment_method?: string + expected_quota?: number } export interface SubscriptionPayResponse { diff --git a/web/src/features/wallet/components/subscription-plans-card.tsx b/web/src/features/wallet/components/subscription-plans-card.tsx index 91282fd9fd66..79e562c3413e 100644 --- a/web/src/features/wallet/components/subscription-plans-card.tsx +++ b/web/src/features/wallet/components/subscription-plans-card.tsx @@ -51,7 +51,11 @@ import { updateBillingPreference, } from '@/features/subscriptions/api' import { SubscriptionPurchaseDialog } from '@/features/subscriptions/components/dialogs/subscription-purchase-dialog' -import { formatDuration, formatResetPeriod } from '@/features/subscriptions/lib' +import { + formatDuration, + formatResetPeriod, + useSubscriptionPriceFormatter, +} from '@/features/subscriptions/lib' import type { PlanRecord, UserSubscriptionRecord, @@ -101,6 +105,7 @@ export function SubscriptionPlansCard({ onPurchaseSuccess, }: SubscriptionPlansCardProps) { const { t } = useTranslation() + const formatPrice = useSubscriptionPriceFormatter() const [plans, setPlans] = useState([]) const [activeSubscriptions, setActiveSubscriptions] = useState< @@ -529,7 +534,7 @@ export function SubscriptionPlansCard({ const plan = p?.plan if (!plan) return null const totalAmount = Number(plan.total_amount || 0) - const price = Number(plan.price_amount || 0).toFixed(2) + const price = formatPrice(plan.price_amount) const isPopular = index === 0 && plans.length > 1 const limit = Number(plan.max_purchase_per_user || 0) const count = planPurchaseCountMap.get(plan.id) || 0 @@ -581,7 +586,7 @@ export function SubscriptionPlansCard({
- ${price} + {price}
diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index d9bc785e50b7..33df1b7bc701 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -874,9 +874,11 @@ "Balance and top-up management": "Balance and top-up management", "Balance depleted": "Balance depleted", "Balance is shown in quota units": "Balance is shown in quota units", + "Balance payment is unavailable": "Balance payment is unavailable", "Balance queried successfully": "Balance queried successfully", "Balance Query": "Balance Query", "Balance Query route does not support pass-through": "Balance Query route does not support pass-through", + "Balance required": "Balance required", "Balance response not recognized": "Balance response not recognized", "Balance update failed": "Balance update failed", "Balance update started in the background": "Balance update started in the background.", @@ -4905,6 +4907,7 @@ "Plan Name": "Plan Name", "Plan name cannot be empty": "Plan name cannot be empty", "Plan Price": "Plan Price", + "Plan Price ({{currency}})": "Plan Price ({{currency}})", "Plan price cannot be empty": "Plan price cannot be empty", "Plan price must be greater than zero": "Plan price must be greater than zero", "Plan Quota": "Plan Quota", @@ -6585,6 +6588,7 @@ "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.", "The API key used for the requests": "The API key used for the requests", "The authenticator code is incorrect.": "The authenticator code is incorrect.", + "The balance price changed. Refresh and try again.": "The balance price changed. Refresh and try again.", "The binding will complete automatically after authorization": "The binding will complete automatically after authorization", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.", diff --git a/web/src/i18n/locales/fr.json b/web/src/i18n/locales/fr.json index a6c6a7942e16..19870c860da9 100644 --- a/web/src/i18n/locales/fr.json +++ b/web/src/i18n/locales/fr.json @@ -874,9 +874,11 @@ "Balance and top-up management": "Gestion du solde et des recharges", "Balance depleted": "Solde épuisé", "Balance is shown in quota units": "Le solde est affiché en unités de quota", + "Balance payment is unavailable": "Le paiement avec le solde est indisponible", "Balance queried successfully": "Solde interrogé avec succès", "Balance Query": "Consultation du solde", "Balance Query route does not support pass-through": "La route de consultation du solde ne prend pas en charge la transmission directe", + "Balance required": "Solde requis", "Balance response not recognized": "Réponse de solde non reconnue", "Balance update failed": "Échec de la mise à jour des soldes", "Balance update started in the background": "La mise à jour des soldes a démarré en arrière-plan.", @@ -4905,6 +4907,7 @@ "Plan Name": "Nom du plan", "Plan name cannot be empty": "Le nom du forfait ne peut pas être vide", "Plan Price": "Prix du forfait", + "Plan Price ({{currency}})": "Prix du forfait ({{currency}})", "Plan price cannot be empty": "Le prix du forfait ne peut pas être vide", "Plan price must be greater than zero": "Le prix du forfait doit être supérieur à zéro", "Plan Quota": "Quota du forfait", @@ -6585,6 +6588,7 @@ "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "L'administrateur n'a pas encore configuré de contenu 'À propos'. Vous pouvez le définir dans la page des paramètres, en supportant le HTML ou l'URL.", "The API key used for the requests": "La clé API utilisée pour les requêtes", "The authenticator code is incorrect.": "Le code d’authentification est incorrect.", + "The balance price changed. Refresh and try again.": "Le montant à débiter du solde a changé. Actualisez la page et réessayez.", "The binding will complete automatically after authorization": "La liaison se terminera automatiquement après l'autorisation", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "Le produit associé alimente les recharges de portefeuille : lorsqu’un utilisateur saisit un montant, new-api lance le paiement sur ce produit Pancake unique et remplace le prix pour la session, sans devoir précréer des SKU de 1 $, 5 $ ou 10 $.", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "La boutique associée est le conteneur parent de tous les produits Pancake que new-api crée depuis cette administration, y compris le produit de recharge de portefeuille et les produits de forfaits d’abonnement. Une seule boutique suffit ; choisissez-en une autre uniquement si vous gérez réellement des catalogues Pancake séparés.", diff --git a/web/src/i18n/locales/ja.json b/web/src/i18n/locales/ja.json index aed1930d4b2d..c59fe097443e 100644 --- a/web/src/i18n/locales/ja.json +++ b/web/src/i18n/locales/ja.json @@ -874,9 +874,11 @@ "Balance and top-up management": "残高とチャージ管理", "Balance depleted": "残高なし", "Balance is shown in quota units": "残高はクォータ単位で表示されます", + "Balance payment is unavailable": "残高払いは現在利用できません", "Balance queried successfully": "残高の取得に成功しました", "Balance Query": "残高照会", "Balance Query route does not support pass-through": "残高照会ルートはパススルーに対応していません", + "Balance required": "必要残高", "Balance response not recognized": "残高レスポンスを認識できません", "Balance update failed": "残高の更新に失敗しました", "Balance update started in the background": "残高の更新をバックグラウンドで開始しました。", @@ -4905,6 +4907,7 @@ "Plan Name": "プラン名", "Plan name cannot be empty": "プラン名を入力してください", "Plan Price": "プラン価格", + "Plan Price ({{currency}})": "プラン価格 ({{currency}})", "Plan price cannot be empty": "プランの価格を入力してください", "Plan price must be greater than zero": "プラン価格は 0 より大きい必要があります", "Plan Quota": "プランのクォータ", @@ -6585,6 +6588,7 @@ "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "管理者はまだ「概要」コンテンツを設定していません。設定ページでHTMLまたはURLをサポートして設定できます。", "The API key used for the requests": "リクエストに使用された API キー", "The authenticator code is incorrect.": "認証アプリのコードが正しくありません。", + "The balance price changed. Refresh and try again.": "必要な残高が変更されました。ページを更新して再試行してください。", "The binding will complete automatically after authorization": "認証後、バインディングは自動的に完了します", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "紐付け済み商品はウォレットチャージに使用されます。ユーザーが任意の金額を入力すると、new-api はこの単一の Pancake 商品でチェックアウトを実行し、セッションごとに価格を上書きします。$1 / $5 / $10 の SKU を事前作成する必要はありません。", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "紐付け済みストアは、この管理画面から new-api が作成するすべての Pancake 商品の親コンテナです。ウォレットチャージ商品とサブスクリプションプラン商品が含まれます。通常は 1 つのストアで十分です。別々の Pancake カタログを本当に運用する場合のみ別のストアを固定してください。", diff --git a/web/src/i18n/locales/ru.json b/web/src/i18n/locales/ru.json index 6140ad1a1574..351a5fddf2b3 100644 --- a/web/src/i18n/locales/ru.json +++ b/web/src/i18n/locales/ru.json @@ -874,9 +874,11 @@ "Balance and top-up management": "Управление балансом и пополнением", "Balance depleted": "Баланс исчерпан", "Balance is shown in quota units": "Баланс показан в единицах квоты", + "Balance payment is unavailable": "Оплата с баланса недоступна", "Balance queried successfully": "Баланс успешно запрошен", "Balance Query": "Запрос баланса", "Balance Query route does not support pass-through": "Маршрут запроса баланса не поддерживает сквозную передачу", + "Balance required": "Необходимый остаток", "Balance response not recognized": "Ответ с балансом не распознан", "Balance update failed": "Не удалось обновить балансы", "Balance update started in the background": "Обновление балансов запущено в фоновом режиме.", @@ -4905,6 +4907,7 @@ "Plan Name": "Название плана", "Plan name cannot be empty": "Название плана не может быть пустым", "Plan Price": "Цена тарифа", + "Plan Price ({{currency}})": "Цена тарифа ({{currency}})", "Plan price cannot be empty": "Цена плана не может быть пустой", "Plan price must be greater than zero": "Цена плана должна быть больше нуля", "Plan Quota": "Квота тарифа", @@ -6585,6 +6588,7 @@ "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "Администратор еще не настроил содержимое раздела «О программе». Вы можете установить его на странице настроек, поддерживается HTML или URL.", "The API key used for the requests": "API-ключ, использованный для запросов", "The authenticator code is incorrect.": "Неверный код аутентификатора.", + "The balance price changed. Refresh and try again.": "Сумма списания с баланса изменилась. Обновите страницу и попробуйте снова.", "The binding will complete automatically after authorization": "Привязка завершится автоматически после авторизации", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "Привязанный продукт используется для пополнения кошелька: когда пользователь вводит любую сумму, new-api запускает оплату через этот единственный продукт Pancake и переопределяет цену для каждой сессии — не нужно заранее создавать SKU на $1 / $5 / $10.", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "Привязанный магазин является родительским контейнером для всех продуктов Pancake, которые new-api создает из этой админки: как продукта пополнения кошелька, так и продуктов планов подписки. Одного магазина достаточно; выбирайте другой только если действительно ведете отдельные каталоги Pancake.", diff --git a/web/src/i18n/locales/vi.json b/web/src/i18n/locales/vi.json index 88f215d42bf4..8112b4d71929 100644 --- a/web/src/i18n/locales/vi.json +++ b/web/src/i18n/locales/vi.json @@ -874,9 +874,11 @@ "Balance and top-up management": "Quản lý số dư và nạp tiền", "Balance depleted": "Đã hết số dư", "Balance is shown in quota units": "Số dư được hiển thị theo đơn vị hạn mức", + "Balance payment is unavailable": "Hiện không thể thanh toán bằng số dư", "Balance queried successfully": "Truy vấn số dư thành công", "Balance Query": "Truy vấn số dư", "Balance Query route does not support pass-through": "Tuyến truy vấn số dư không hỗ trợ truyền thẳng", + "Balance required": "Số dư cần có", "Balance response not recognized": "Không nhận dạng được phản hồi số dư", "Balance update failed": "Cập nhật số dư thất bại", "Balance update started in the background": "Đã bắt đầu cập nhật số dư trong nền.", @@ -4905,6 +4907,7 @@ "Plan Name": "Tên gói", "Plan name cannot be empty": "Tên gói không được để trống", "Plan Price": "Giá gói", + "Plan Price ({{currency}})": "Giá gói ({{currency}})", "Plan price cannot be empty": "Giá gói không được để trống", "Plan price must be greater than zero": "Giá gói phải lớn hơn 0", "Plan Quota": "Hạn ngạch gói", @@ -6585,6 +6588,7 @@ "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "Quản trị viên chưa cấu hình bất kỳ nội dung giới thiệu nào. Bạn có thể thiết lập nó trong trang cài đặt, hỗ trợ HTML hoặc URL.", "The API key used for the requests": "Khóa API được dùng cho các yêu cầu", "The authenticator code is incorrect.": "Mã xác thực không chính xác.", + "The balance price changed. Refresh and try again.": "Số dư cần thanh toán đã thay đổi. Hãy tải lại trang và thử lại.", "The binding will complete automatically after authorization": "Việc liên kết sẽ hoàn tất tự động sau khi ủy quyền", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "Sản phẩm đã liên kết dùng cho nạp ví: khi người dùng nhập bất kỳ số tiền nào, new-api chạy thanh toán trên một sản phẩm Pancake duy nhất này và ghi đè giá theo từng phiên — không cần tạo trước SKU $1 / $5 / $10.", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "Cửa hàng đã liên kết là vùng chứa cha cho mọi sản phẩm Pancake mà new-api tạo từ trang quản trị này — bao gồm sản phẩm nạp ví và mọi sản phẩm gói đăng ký. Một cửa hàng là đủ; chỉ ghim cửa hàng khác nếu bạn thực sự vận hành các catalog Pancake riêng.", diff --git a/web/src/i18n/locales/zh-TW.json b/web/src/i18n/locales/zh-TW.json index bbedc2d12086..a896b3773f3c 100644 --- a/web/src/i18n/locales/zh-TW.json +++ b/web/src/i18n/locales/zh-TW.json @@ -874,9 +874,11 @@ "Balance and top-up management": "餘額儲值管理", "Balance depleted": "餘額已耗盡", "Balance is shown in quota units": "餘額以額度單位顯示", + "Balance payment is unavailable": "目前無法使用餘額付款", "Balance queried successfully": "餘額查詢成功", "Balance Query": "餘額查詢", "Balance Query route does not support pass-through": "餘額查詢路由不支援透傳", + "Balance required": "所需餘額", "Balance response not recognized": "無法識別餘額回應", "Balance update failed": "餘額更新失敗", "Balance update started in the background": "餘額更新已在背景開始。", @@ -4905,6 +4907,7 @@ "Plan Name": "套餐名稱", "Plan name cannot be empty": "套餐名稱不能為空", "Plan Price": "套餐價格", + "Plan Price ({{currency}})": "套餐價格 ({{currency}})", "Plan price cannot be empty": "套餐價格不能為空", "Plan price must be greater than zero": "套餐價格必須大於 0", "Plan Quota": "套餐額度", @@ -6585,6 +6588,7 @@ "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "管理員尚未設定任何關於內容。您可以在設定頁面中進行設定,支援 HTML 或 URL。", "The API key used for the requests": "請求所使用的 API 金鑰", "The authenticator code is incorrect.": "驗證器驗證碼錯誤。", + "The balance price changed. Refresh and try again.": "所需餘額已變更,請重新整理後再試。", "The binding will complete automatically after authorization": "授權後連結將自動完成", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "已連結產品用於錢包儲值:當用戶輸入任意金額時,new-api 會基於這個單一 Pancake 產品發起結帳,並按對話覆蓋價格,無需預先建立 $1 / $5 / $10 的 SKU。", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "已連結店鋪是 new-api 從此管理端建立的所有 Pancake 產品的父容器,包括錢包儲值產品和訂閱套餐產品。一個店鋪通常足夠;只有在確實運營多個 Pancake 目錄時才需要連結不同店鋪。", diff --git a/web/src/i18n/locales/zh.json b/web/src/i18n/locales/zh.json index 1cf0e8775f94..4d6bc137d4e8 100644 --- a/web/src/i18n/locales/zh.json +++ b/web/src/i18n/locales/zh.json @@ -874,9 +874,11 @@ "Balance and top-up management": "余额充值管理", "Balance depleted": "余额已耗尽", "Balance is shown in quota units": "余额以额度单位显示", + "Balance payment is unavailable": "当前无法使用余额支付", "Balance queried successfully": "余额查询成功", "Balance Query": "余额查询", "Balance Query route does not support pass-through": "余额查询路由不支持透传", + "Balance required": "所需余额", "Balance response not recognized": "无法识别余额响应", "Balance update failed": "余额更新失败", "Balance update started in the background": "余额更新已在后台开始。", @@ -4905,6 +4907,7 @@ "Plan Name": "套餐名称", "Plan name cannot be empty": "套餐名称不能为空", "Plan Price": "套餐价格", + "Plan Price ({{currency}})": "套餐价格 ({{currency}})", "Plan price cannot be empty": "套餐价格不能为空", "Plan price must be greater than zero": "套餐价格必须大于 0", "Plan Quota": "套餐额度", @@ -6585,6 +6588,7 @@ "The administrator has not configured any about content yet. You can set it in the settings page, supporting HTML or URL.": "管理员尚未配置任何关于内容。您可以在设置页面中进行设置,支持 HTML 或 URL。", "The API key used for the requests": "请求所使用的 API 密钥", "The authenticator code is incorrect.": "认证器验证码错误。", + "The balance price changed. Refresh and try again.": "所需余额已变更,请刷新后重试。", "The binding will complete automatically after authorization": "授权后绑定将自动完成", "The bound Product powers wallet top-ups: when a user enters any amount, new-api runs the checkout against this single Pancake product and overrides the price per session — no need to pre-create $1 / $5 / $10 SKUs.": "已绑定产品用于钱包充值:当用户输入任意金额时,new-api 会基于这个单一 Pancake 产品发起结账,并按会话覆盖价格,无需预先创建 $1 / $5 / $10 的 SKU。", "The bound Store is the parent container for every Pancake product new-api creates from this admin — both the wallet top-up product and any subscription-plan products. One store is enough; pin a different one only if you genuinely run separate Pancake catalogs.": "已绑定店铺是 new-api 从此管理端创建的所有 Pancake 产品的父容器,包括钱包充值产品和订阅套餐产品。一个店铺通常足够;只有在确实运营多个 Pancake 目录时才需要绑定不同店铺。", diff --git a/web/src/lib/currency.ts b/web/src/lib/currency.ts index 15a3d345d05c..54894bafd0e8 100644 --- a/web/src/lib/currency.ts +++ b/web/src/lib/currency.ts @@ -159,9 +159,10 @@ export function parseCurrencyDisplayType( return isCurrencyDisplayType(value) ? value : fallback } -function getConfig(): CurrencyConfig { - const { config } = useSystemConfigStore.getState() - const currency = config?.currency ?? DEFAULT_CURRENCY_CONFIG +function getConfig( + currency = useSystemConfigStore.getState().config?.currency ?? + DEFAULT_CURRENCY_CONFIG +): CurrencyConfig { return { ...DEFAULT_CURRENCY_CONFIG, ...currency, @@ -625,12 +626,12 @@ export function isCurrencyDisplayEnabled(): boolean { */ export function formatLocalCurrencyAmount( amount: number | null | undefined, - options?: CurrencyFormatOptions + options?: CurrencyFormatOptions, + currency?: CurrencyConfig ): string { if (amount == null || Number.isNaN(amount)) return '-' - const { config } = getCurrencyDisplay() - const meta = getBillingDisplayMeta(config) + const meta = getBillingDisplayMeta(getConfig(currency)) const merged = mergeOptions(options) return formatCurrencyValue(amount, merged, meta)