diff --git a/controller/topup.go b/controller/topup.go index a5c27a9121c4..a83d46bc3449 100644 --- a/controller/topup.go +++ b/controller/topup.go @@ -172,13 +172,7 @@ func getPayMoney(amount int64, group string) float64 { dTopupGroupRatio := decimal.NewFromFloat(topupGroupRatio) dPrice := decimal.NewFromFloat(operation_setting.Price) - // apply optional preset discount by the original request amount (if configured), default 1.0 - discount := 1.0 - if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(amount)]; ok { - if ds > 0 { - discount = ds - } - } + discount := operation_setting.GetPaymentSetting().MatchAmountDiscount(amount) dDiscount := decimal.NewFromFloat(discount) payMoney := dAmount.Mul(dPrice).Mul(dTopupGroupRatio).Mul(dDiscount) diff --git a/controller/topup_discount_test.go b/controller/topup_discount_test.go new file mode 100644 index 000000000000..c5c15acc89cb --- /dev/null +++ b/controller/topup_discount_test.go @@ -0,0 +1,48 @@ +package controller + +import ( + "maps" + "testing" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/setting" + "github.com/QuantumNous/new-api/setting/operation_setting" + "github.com/stretchr/testify/require" +) + +func TestTieredAmountDiscountAcrossGateways(t *testing.T) { + originalDisplayType := operation_setting.GetGeneralSetting().QuotaDisplayType + originalPrice := operation_setting.Price + originalWaffoUnitPrice := setting.WaffoUnitPrice + originalWaffoPancakeUnitPrice := setting.WaffoPancakeUnitPrice + originalDiscounts := make(map[int]float64, len(operation_setting.GetPaymentSetting().AmountDiscount)) + maps.Copy(originalDiscounts, operation_setting.GetPaymentSetting().AmountDiscount) + originalTopupGroupRatio := common.TopupGroupRatio2JSONString() + + t.Cleanup(func() { + operation_setting.GetGeneralSetting().QuotaDisplayType = originalDisplayType + operation_setting.Price = originalPrice + setting.WaffoUnitPrice = originalWaffoUnitPrice + setting.WaffoPancakeUnitPrice = originalWaffoPancakeUnitPrice + operation_setting.GetPaymentSetting().AmountDiscount = originalDiscounts + require.NoError(t, common.UpdateTopupGroupRatioByJSONString(originalTopupGroupRatio)) + }) + + operation_setting.GetGeneralSetting().QuotaDisplayType = operation_setting.QuotaDisplayTypeUSD + operation_setting.Price = 1.0 + setting.WaffoUnitPrice = 1.0 + setting.WaffoPancakeUnitPrice = 2.5 + operation_setting.GetPaymentSetting().AmountDiscount = map[int]float64{ + 100: 0.95, + 200: 0.90, + } + require.NoError(t, common.UpdateTopupGroupRatioByJSONString(`{"default":1}`)) + + require.InDelta(t, 99.75, getPayMoney(105, "default"), 1e-6) + require.InDelta(t, 99.75, getWaffoPayMoney(105, "default"), 1e-6) + require.InDelta(t, 249.375, getWaffoPancakePayMoney(105, "default"), 1e-6) + require.InDelta(t, 225.0, getPayMoney(250, "default"), 1e-6) + require.InDelta(t, 225.0, getWaffoPayMoney(250, "default"), 1e-6) + require.InDelta(t, 562.5, getWaffoPancakePayMoney(250, "default"), 1e-6) + require.InDelta(t, 99.0, getPayMoney(99, "default"), 1e-6) +} diff --git a/controller/topup_waffo.go b/controller/topup_waffo.go index 85a2bac878aa..67a3bec2fb98 100644 --- a/controller/topup_waffo.go +++ b/controller/topup_waffo.go @@ -95,12 +95,7 @@ func getWaffoPayMoney(amount float64, group string) float64 { if topupGroupRatio == 0 { topupGroupRatio = 1 } - discount := 1.0 - if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(originalAmount)]; ok { - if ds > 0 { - discount = ds - } - } + discount := operation_setting.GetPaymentSetting().MatchAmountDiscount(int64(originalAmount)) return amount * setting.WaffoUnitPrice * topupGroupRatio * discount } diff --git a/controller/topup_waffo_pancake.go b/controller/topup_waffo_pancake.go index 173eea39eaf8..2fc2ea30198c 100644 --- a/controller/topup_waffo_pancake.go +++ b/controller/topup_waffo_pancake.go @@ -64,10 +64,7 @@ func getWaffoPancakePayMoney(amount int64, group string) float64 { topupGroupRatio = 1 } - discount := 1.0 - if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(amount)]; ok && ds > 0 { - discount = ds - } + discount := operation_setting.GetPaymentSetting().MatchAmountDiscount(amount) payMoney := dAmount. Mul(decimal.NewFromFloat(setting.WaffoPancakeUnitPrice)). diff --git a/controller/topup_waffo_pancake_test.go b/controller/topup_waffo_pancake_test.go index 1e0b6eb9738c..f01908f3fdad 100644 --- a/controller/topup_waffo_pancake_test.go +++ b/controller/topup_waffo_pancake_test.go @@ -44,9 +44,9 @@ func TestGetWaffoPancakePayMoney(t *testing.T) { setting.WaffoPancakeUnitPrice = 2.5 operation_setting.GetPaymentSetting().AmountDiscount = map[int]float64{ + 5: 0, 10: 0.8, int(common.QuotaPerUnit * 3): 0.5, - 20: 0, } require.NoError(t, common.UpdateTopupGroupRatioByJSONString(`{"default":1,"vip":1.2}`)) @@ -73,10 +73,10 @@ func TestGetWaffoPancakePayMoney(t *testing.T) { }, { name: "non-positive discount falls back to no discount", - amount: 20, + amount: 5, group: "default", quotaDisplayType: operation_setting.QuotaDisplayTypeUSD, - expected: 50, + expected: 12.5, }, } diff --git a/setting/operation_setting/payment_setting.go b/setting/operation_setting/payment_setting.go index b744a6cb71d0..a60c73aca270 100644 --- a/setting/operation_setting/payment_setting.go +++ b/setting/operation_setting/payment_setting.go @@ -52,6 +52,29 @@ func GetPaymentSetting() *PaymentSetting { return &paymentSetting } +// MatchAmountDiscount returns the discount multiplier for the largest configured +// threshold k > 0 where int64(k) <= amount and rate > 0, or 1.0 if none matches. +func (p *PaymentSetting) MatchAmountDiscount(amount int64) float64 { + if p == nil || amount <= 0 || len(p.AmountDiscount) == 0 { + return 1.0 + } + bestThreshold := 0 + bestDiscount := 1.0 + for threshold, rate := range p.AmountDiscount { + if threshold <= 0 || rate <= 0 { + continue + } + if int64(threshold) <= amount && threshold > bestThreshold { + bestThreshold = threshold + bestDiscount = rate + } + } + if bestThreshold == 0 { + return 1.0 + } + return bestDiscount +} + func IsPaymentComplianceConfirmed() bool { return paymentSetting.ComplianceConfirmed && paymentSetting.ComplianceTermsVersion == CurrentComplianceTermsVersion diff --git a/setting/operation_setting/payment_setting_test.go b/setting/operation_setting/payment_setting_test.go new file mode 100644 index 000000000000..1343818d5d97 --- /dev/null +++ b/setting/operation_setting/payment_setting_test.go @@ -0,0 +1,54 @@ +package operation_setting + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestPaymentSettingMatchAmountDiscount(t *testing.T) { + tiered := &PaymentSetting{ + AmountDiscount: map[int]float64{ + 100: 0.95, + 200: 0.90, + }, + } + + testCases := []struct { + name string + setting *PaymentSetting + amount int64 + expected float64 + }{ + {name: "exact 100 tier", setting: tiered, amount: 100, expected: 0.95}, + {name: "105 matches 100 tier", setting: tiered, amount: 105, expected: 0.95}, + {name: "199 matches 100 tier", setting: tiered, amount: 199, expected: 0.95}, + {name: "exact 200 tier", setting: tiered, amount: 200, expected: 0.90}, + {name: "250 matches 200 tier", setting: tiered, amount: 250, expected: 0.90}, + {name: "below lowest tier returns 1.0", setting: tiered, amount: 99, expected: 1.0}, + {name: "zero amount returns 1.0", setting: tiered, amount: 0, expected: 1.0}, + {name: "empty map returns 1.0", setting: &PaymentSetting{AmountDiscount: map[int]float64{}}, amount: 105, expected: 1.0}, + {name: "nil map returns 1.0", setting: &PaymentSetting{}, amount: 105, expected: 1.0}, + {name: "nil receiver returns 1.0", setting: nil, amount: 105, expected: 1.0}, + { + name: "non-positive keys and rates are ignored", + setting: &PaymentSetting{ + AmountDiscount: map[int]float64{ + -50: 0.5, + 0: 0.6, + 100: 0.95, + 200: 0, + 300: -0.8, + }, + }, + amount: 350, + expected: 0.95, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + require.InDelta(t, tc.expected, tc.setting.MatchAmountDiscount(tc.amount), 1e-9) + }) + } +} diff --git a/web/src/features/wallet/__tests__/copy.test.tsx b/web/src/features/wallet/__tests__/copy.test.tsx index ac0a89f53ae9..fce796f0330f 100644 --- a/web/src/features/wallet/__tests__/copy.test.tsx +++ b/web/src/features/wallet/__tests__/copy.test.tsx @@ -27,6 +27,11 @@ import zh from '@/i18n/locales/zh.json' import { api } from '@/lib/api' import { RechargeFormCard } from '../components/recharge-form-card' +import { + getDiscountRateForPaymentType, + getMatchedAmountDiscount, + mergePresetAmounts, +} from '../lib' const i18n = createInstance() @@ -125,3 +130,153 @@ it.each([ expect(screen.getByPlaceholderText('Minimum 1')).toBeVisible() } ) + +it('selects the highest qualifying positive discount threshold', () => { + const discounts = { 100: 0.95, 200: 0.9, 50: 0 } + expect(getMatchedAmountDiscount(99, discounts)).toBe(1) + expect(getMatchedAmountDiscount(100, discounts)).toBe(0.95) + expect(getMatchedAmountDiscount(105, discounts)).toBe(0.95) + expect(getMatchedAmountDiscount(250, discounts)).toBe(0.9) +}) + +it('keeps exact-key lookup for Stripe and tiered thresholds for other methods', () => { + const discounts = { 100: 0.95, 200: 0.9 } + expect(getDiscountRateForPaymentType(100, discounts, 'stripe')).toBe(0.95) + expect(getDiscountRateForPaymentType(105, discounts, 'stripe')).toBe(1) + expect(getDiscountRateForPaymentType(105, discounts, 'waffo_pancake')).toBe( + 0.95 + ) + expect(getDiscountRateForPaymentType(250, discounts, 'waffo')).toBe(0.9) +}) + +it('applies tiered thresholds when merging preset amounts', () => { + expect(mergePresetAmounts([50, 105, 200], { 100: 0.95 })).toEqual([ + { value: 50, discount: 1 }, + { value: 105, discount: 0.95 }, + { value: 200, discount: 0.95 }, + ]) +}) + +it('displays tiered discount savings on recharge preset cards', () => { + render( + + + + ) + + expect(screen.getByRole('button', { name: /^200 / })).toHaveTextContent( + '优惠 5%支付 190 • 节省 10' + ) +}) + +it('suppresses threshold-only savings on preset cards when Stripe is the only enabled gateway', () => { + render( + + + + ) + + expect(screen.getByRole('button', { name: /^100 / })).toHaveTextContent( + '优惠 5%支付 95 • 节省 5' + ) + expect(screen.getByRole('button', { name: /^200 / })).toHaveTextContent( + '支付 200' + ) +}) + +it('gates threshold-only savings on preset cards when Stripe is the active payment method in multi-gateway mode', () => { + render( + + + + ) + + expect(screen.getByRole('button', { name: /^100 / })).toHaveTextContent( + '优惠 5%支付 95 • 节省 5' + ) + expect(screen.getByRole('button', { name: /^200 / })).toHaveTextContent( + '支付 200' + ) +}) diff --git a/web/src/features/wallet/components/recharge-form-card.tsx b/web/src/features/wallet/components/recharge-form-card.tsx index c98b638ed6d8..473f49ae4aa3 100644 --- a/web/src/features/wallet/components/recharge-form-card.tsx +++ b/web/src/features/wallet/components/recharge-form-card.tsx @@ -37,11 +37,16 @@ import { import { formatNumber } from '@/lib/format' import { cn } from '@/lib/utils' +import { PAYMENT_TYPES } from '../constants' import { formatCurrency, + getDefaultPaymentType, getDiscountLabel, + getDiscountRateForPaymentType, + getMatchedAmountDiscount, getPaymentIcon, getMinTopupAmount, + isStripePayment, calculatePresetPricing, } from '../lib' import type { @@ -81,6 +86,7 @@ interface RechargeFormCardProps { waffoMinTopup?: number onWaffoMethodSelect?: (method: WaffoPayMethod, index: number) => void enableWaffoPancakeTopup?: boolean + activePaymentType?: string } export function RechargeFormCard({ @@ -111,6 +117,7 @@ export function RechargeFormCard({ waffoMinTopup, onWaffoMethodSelect, enableWaffoPancakeTopup, + activePaymentType, }: RechargeFormCardProps) { const { t } = useTranslation() const [localAmount, setLocalAmount] = useState(topupAmount.toString()) @@ -141,6 +148,21 @@ export function RechargeFormCard({ const hasWaffoPaymentMethods = Array.isArray(waffoPayMethods) && waffoPayMethods.length > 0 const minTopup = getMinTopupAmount(topupInfo) + const isStripeOnly = Boolean( + topupInfo?.enable_stripe_topup && + !topupInfo?.enable_online_topup && + !enableWaffoTopup && + !enableWaffoPancakeTopup && + !topupInfo?.enable_waffo_topup && + !topupInfo?.enable_waffo_pancake_topup && + !(topupInfo?.pay_methods ?? []).some( + (method) => !isStripePayment(method.type) + ) + ) + const resolvedPaymentType = + activePaymentType ?? getDefaultPaymentType(topupInfo) + const isStripeSelected = + isStripeOnly || isStripePayment(resolvedPaymentType) const redemptionEnabled = topupInfo?.enable_redemption !== false if (loading) { @@ -228,10 +250,21 @@ export function RechargeFormCard({
{presetAmounts.map((preset) => { - const discount = - preset.discount || - topupInfo?.discount?.[preset.value] || - 1.0 + let discount = 1.0 + if (isStripeSelected) { + discount = getDiscountRateForPaymentType( + preset.value, + topupInfo?.discount, + PAYMENT_TYPES.STRIPE + ) + } else if (preset.discount && preset.discount < 1) { + discount = preset.discount + } else { + discount = getMatchedAmountDiscount( + preset.value, + topupInfo?.discount + ) + } const { displayValue, actualPrice, diff --git a/web/src/features/wallet/index.tsx b/web/src/features/wallet/index.tsx index 5a9cb9e08702..aee8eccdefd5 100644 --- a/web/src/features/wallet/index.tsx +++ b/web/src/features/wallet/index.tsx @@ -32,7 +32,7 @@ import { TransferDialog } from './components/dialogs/transfer-dialog' import { RechargeFormCard } from './components/recharge-form-card' import { SubscriptionPlansCard } from './components/subscription-plans-card' import { WalletStatsCard } from './components/wallet-stats-card' -import { DEFAULT_DISCOUNT_RATE, PAYMENT_TYPES } from './constants' +import { PAYMENT_TYPES } from './constants' import { useTopupInfo, usePayment, @@ -44,6 +44,7 @@ import { } from './hooks' import { getDefaultPaymentType, + getDiscountRateForPaymentType, getMinTopupAmount, dispatchSelectedPayment, } from './lib' @@ -272,8 +273,12 @@ export function Wallet(props: WalletProps) { // Get discount rate for current topup amount const getDiscountRate = useCallback(() => { - return topupInfo?.discount?.[topupAmount] || DEFAULT_DISCOUNT_RATE - }, [topupInfo, topupAmount]) + return getDiscountRateForPaymentType( + topupAmount, + topupInfo?.discount, + getCurrentPaymentType() + ) + }, [topupAmount, topupInfo?.discount, getCurrentPaymentType]) const handleSubscriptionAvailabilityChange = useCallback( (available: boolean) => { @@ -328,6 +333,7 @@ export function Wallet(props: WalletProps) { enableWaffoPancakeTopup={ topupInfo?.enable_waffo_pancake_topup } + activePaymentType={getCurrentPaymentType()} />
diff --git a/web/src/features/wallet/lib/format.ts b/web/src/features/wallet/lib/format.ts index 4c3f3f5934ad..b30352fb3fe9 100644 --- a/web/src/features/wallet/lib/format.ts +++ b/web/src/features/wallet/lib/format.ts @@ -18,7 +18,7 @@ For commercial licensing, please contact support@quantumnous.com */ import type { TFunction } from 'i18next' -import { DEFAULT_DISCOUNT_RATE } from '../constants' +import { DEFAULT_DISCOUNT_RATE, PAYMENT_TYPES } from '../constants' // ============================================================================ // Wallet-specific Formatting Functions @@ -63,14 +63,75 @@ export function formatCurrency(amount: number | string): string { }).format(numeric) } +/** + * Match the highest discount tier whose threshold is <= amount. + */ +export function getMatchedAmountDiscount( + amount: number, + discounts?: Record | null +): number { + if (!Number.isFinite(amount) || amount <= 0 || !discounts) { + return DEFAULT_DISCOUNT_RATE + } + + let bestThreshold = 0 + let bestRate = DEFAULT_DISCOUNT_RATE + + for (const [rawThreshold, rawRate] of Object.entries(discounts)) { + const threshold = Number(rawThreshold) + const rate = Number(rawRate) + if ( + !Number.isFinite(threshold) || + threshold <= 0 || + threshold > amount || + !Number.isFinite(rate) || + rate <= 0 + ) { + continue + } + + if (threshold > bestThreshold) { + bestThreshold = threshold + bestRate = rate + } + } + + return bestRate +} + +/** + * Resolve discount rate by payment method: Stripe quotes still use exact-key + * discount lookup, while other gateways use tiered threshold matching. + */ +export function getDiscountRateForPaymentType( + amount: number, + discounts?: Record | null, + paymentType?: string +): number { + if (paymentType === PAYMENT_TYPES.STRIPE) { + if (!Number.isFinite(amount) || amount <= 0 || !discounts) { + return DEFAULT_DISCOUNT_RATE + } + const exactRate = Number(discounts[amount]) + return Number.isFinite(exactRate) && exactRate > 0 + ? exactRate + : DEFAULT_DISCOUNT_RATE + } + + return getMatchedAmountDiscount(amount, discounts) +} + /** * Get discount label for display (e.g., "20% OFF") */ export function getDiscountLabel(discount: number, t: TFunction): string { - if (discount >= DEFAULT_DISCOUNT_RATE) { + if (discount <= 0 || discount >= DEFAULT_DISCOUNT_RATE) { return '' } const off = Math.round((1 - discount) * 100) + if (off <= 0) { + return '' + } return t('{{percent}}% OFF', { percent: off }) } diff --git a/web/src/features/wallet/lib/payment.ts b/web/src/features/wallet/lib/payment.ts index 2ea8fa2c2dc4..b9ae90c6ee69 100644 --- a/web/src/features/wallet/lib/payment.ts +++ b/web/src/features/wallet/lib/payment.ts @@ -25,6 +25,7 @@ import { DEFAULT_MIN_TOPUP, } from '../constants' import type { PaymentMethod, PresetAmount, TopupInfo } from '../types' +import { getMatchedAmountDiscount } from './format' // ============================================================================ // Payment Processing Functions @@ -214,6 +215,6 @@ export function mergePresetAmounts( return amountOptions.map((amount) => ({ value: amount, - discount: discounts[amount] || 1.0, + discount: getMatchedAmountDiscount(amount, discounts), })) }