Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 1 addition & 7 deletions controller/topup.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
48 changes: 48 additions & 0 deletions controller/topup_discount_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
7 changes: 1 addition & 6 deletions controller/topup_waffo.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
5 changes: 1 addition & 4 deletions controller/topup_waffo_pancake.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)).
Expand Down
6 changes: 3 additions & 3 deletions controller/topup_waffo_pancake_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}`))

Expand All @@ -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,
},
}

Expand Down
23 changes: 23 additions & 0 deletions setting/operation_setting/payment_setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment on lines +67 to +69
}
}
if bestThreshold == 0 {
return 1.0
}
return bestDiscount
}

func IsPaymentComplianceConfirmed() bool {
return paymentSetting.ComplianceConfirmed &&
paymentSetting.ComplianceTermsVersion == CurrentComplianceTermsVersion
Expand Down
54 changes: 54 additions & 0 deletions setting/operation_setting/payment_setting_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
}
109 changes: 109 additions & 0 deletions web/src/features/wallet/__tests__/copy.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -125,3 +130,107 @@ 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(
<I18nextProvider i18n={i18n}>
<RechargeFormCard
topupInfo={{
enable_online_topup: true,
enable_stripe_topup: false,
pay_methods: [],
min_topup: 1,
stripe_min_topup: 1,
amount_options: [200],
discount: { 100: 0.95 },
}}
presetAmounts={[{ value: 200, discount: 1 }]}
selectedPreset={null}
topupAmount={105}
paymentAmount={99.75}
priceRatio={1}
calculating={false}
paymentLoading={null}
redemptionCode=''
redeeming={false}
onSelectPreset={vi.fn()}
onTopupAmountChange={vi.fn()}
onPaymentMethodSelect={vi.fn()}
onRedemptionCodeChange={vi.fn()}
onRedeem={vi.fn()}
/>
</I18nextProvider>
)

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(
<I18nextProvider i18n={i18n}>
<RechargeFormCard
topupInfo={{
enable_online_topup: false,
enable_stripe_topup: true,
pay_methods: [],
min_topup: 1,
stripe_min_topup: 1,
amount_options: [100, 200],
discount: { 100: 0.95 },
}}
presetAmounts={[
{ value: 100, discount: 0.95 },
{ value: 200, discount: 0.95 },
]}
selectedPreset={null}
topupAmount={200}
paymentAmount={200}
priceRatio={1}
calculating={false}
paymentLoading={null}
redemptionCode=''
redeeming={false}
onSelectPreset={vi.fn()}
onTopupAmountChange={vi.fn()}
onPaymentMethodSelect={vi.fn()}
onRedemptionCodeChange={vi.fn()}
onRedeem={vi.fn()}
/>
</I18nextProvider>
)

expect(screen.getByRole('button', { name: /^100 / })).toHaveTextContent(
'优惠 5%支付 95 • 节省 5'
)
expect(screen.getByRole('button', { name: /^200 / })).toHaveTextContent(
'支付 200'
)
})
34 changes: 30 additions & 4 deletions web/src/features/wallet/components/recharge-form-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,15 @@ import {
import { formatNumber } from '@/lib/format'
import { cn } from '@/lib/utils'

import { PAYMENT_TYPES } from '../constants'
import {
formatCurrency,
getDiscountLabel,
getDiscountRateForPaymentType,
getMatchedAmountDiscount,
getPaymentIcon,
getMinTopupAmount,
isStripePayment,
calculatePresetPricing,
} from '../lib'
import type {
Expand Down Expand Up @@ -141,6 +145,17 @@ 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 redemptionEnabled = topupInfo?.enable_redemption !== false

if (loading) {
Expand Down Expand Up @@ -228,10 +243,21 @@ export function RechargeFormCard({
</Label>
<div className='grid grid-cols-2 gap-1.5 sm:gap-3 md:grid-cols-4'>
{presetAmounts.map((preset) => {
const discount =
preset.discount ||
topupInfo?.discount?.[preset.value] ||
1.0
let discount = 1.0
if (isStripeOnly) {
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
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
const {
displayValue,
actualPrice,
Expand Down
Loading