Skip to content
9 changes: 7 additions & 2 deletions apps/api-go/controller/discount_code.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,9 +230,14 @@ func ValidateDiscountCode(c *gin.Context) {
common.ApiErrorMsg(c, err.Error())
return
}
amount = topUpConfigAmountFromLegacy(legacy)
if _, canonical := canonicalTopUpCredit(c); canonical {
amount = topUpConfigAmountFromResolved(resolved)
amount, err = topUpCouponAmountForCredits(resolved.CreditedQuota)
if err != nil {
common.ApiErrorMsg(c, err.Error())
return
}
} else {
amount = topUpConfigAmountFromLegacy(legacy)
}
if topUpRequestUnit("") == "CREDIT" {
amount = amount.Floor()
Expand Down
24 changes: 16 additions & 8 deletions apps/api-go/controller/topup.go
Original file line number Diff line number Diff line change
Expand Up @@ -1010,19 +1010,27 @@ func applyTopUpSettlementRatios(settlementAmount, discountAmount decimal.Decimal
}

func applyTopUpSettlementRatiosWithOriginal(settlementAmount, discountAmount decimal.Decimal, group string, dPaymentRatio decimal.Decimal) (decimal.Decimal, decimal.Decimal) {
topupGroupRatio := common.GetTopupGroupRatio(group)
if topupGroupRatio == 0 {
topupGroupRatio = 1
}

dTopupGroupRatio := decimal.NewFromFloat(topupGroupRatio)
// apply optional preset discount by the original request amount (if configured), default 1.0
// Read old request-unit configuration only at this compatibility boundary.
groupRatio := topUpRechargeGroupFactor(group)
discount := 1.0
if ds, exists := operation_setting.GetPaymentSetting().AmountDiscount[discountAmount.String()]; exists && ds > 0 {
discount = ds
}
dDiscount := decimal.NewFromFloat(discount)
return applyTopUpSettlementFactorsWithOriginal(settlementAmount, groupRatio, dPaymentRatio, decimal.NewFromFloat(discount))
}

func topUpRechargeGroupFactor(group string) decimal.Decimal {
topupGroupRatio := common.GetTopupGroupRatio(group)
if topupGroupRatio == 0 {
topupGroupRatio = 1
}
return decimal.NewFromFloat(topupGroupRatio)
}

// applyTopUpSettlementFactorsWithOriginal accepts only money and dimensionless
// factors. It reads no configuration. New CREDIT and compatibility callers
// share this one rounding policy.
func applyTopUpSettlementFactorsWithOriginal(settlementAmount, dTopupGroupRatio, dPaymentRatio, dDiscount decimal.Decimal) (decimal.Decimal, decimal.Decimal) {
// Group/payment pricing and fees belong to both sides of the comparison.
// Only an eligible amount preset and then a coupon can reduce this basis.
base := settlementAmount.
Expand Down
27 changes: 18 additions & 9 deletions apps/api-go/controller/topup_canonical_credit.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,13 +145,6 @@ func canonicalTopUpCredit(c *gin.Context) (resolvedTopUpAmount, bool) {
return amount, exists && ok
}

func topUpConfigAmountFromResolved(amount resolvedTopUpAmount) decimal.Decimal {
if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
return decimal.NewFromInt(amount.CreditedQuota)
}
return amount.LegacyBatch
}

func quoteTopUpResolvedWithSettlementPricing(amount resolvedTopUpAmount, group string, pricing payMethodSettlementPricing, ratio decimal.Decimal) (decimal.Decimal, error) {
_, paid, err := quoteTopUpResolvedSettlementAmounts(amount, group, pricing, ratio)
return paid, err
Expand All @@ -173,7 +166,19 @@ func quoteTopUpResolvedSettlementAmounts(amount resolvedTopUpAmount, group strin
if err != nil {
return decimal.Zero, decimal.Zero, err
}
original, paid := applyTopUpSettlementRatiosWithOriginal(settlement, topUpConfigAmountFromResolved(amount), group, ratio)
// Match the same validated CREDIT catalog published to new clients. The
// compatibility LegacyBatch projection cannot select a different discount.
groupRatio := topUpRechargeGroupFactor(group)
tokens := operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens
discounts, err := topUpCreditDiscounts(operation_setting.GetPaymentSetting().AmountDiscount, tokens)
if err != nil {
return decimal.Zero, decimal.Zero, err
}
discount := 1.0
if configured, exists := discounts[strconv.FormatInt(amount.CreditedQuota, 10)]; exists {
discount = configured
}
original, paid := applyTopUpSettlementFactorsWithOriginal(settlement, groupRatio, ratio, decimal.NewFromFloat(discount))
return original, paid, nil
}

Expand Down Expand Up @@ -222,7 +227,11 @@ func applyDiscountCodeQuoteRequest(c *gin.Context, base decimal.Decimal, amount
var discount *model.DiscountCode
var err error
if _, canonical := canonicalTopUpCredit(c); canonical {
paid, discount, err = applyDiscountCodeQuoteDecimal(base, topUpConfigAmountFromResolved(amount), code, userID)
qualification, qualificationErr := topUpCouponAmountForCredits(amount.CreditedQuota)
if qualificationErr != nil {
return decimal.Zero, nil, qualificationErr
}
paid, discount, err = applyDiscountCodeQuoteDecimal(base, qualification, code, userID)
} else {
paid, discount, err = applyDiscountCodeQuoteLegacyDecimal(base, amount.LegacyBatch, code, userID)
}
Expand Down
35 changes: 35 additions & 0 deletions apps/api-go/controller/topup_credit_discounts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package controller

import (
"fmt"
"math"
"strconv"

"github.com/LIghtJUNction/api.lmm.best/setting/operation_setting"
)

// topUpCreditDiscounts is the one adapter for persisted amount-discount keys.
// Both public catalog metadata and canonical quotes use this validated map of
// actual ledger credits. The persisted configuration is not rewritten.
func topUpCreditDiscounts(config operation_setting.PaymentAmountDiscount, tokens bool) (map[string]float64, error) {
discounts := make(map[string]float64, len(config))
for amount, discount := range config {
value, err := operation_setting.ParsePaymentDiscountAmount(amount)
if err != nil {
return nil, err
}
credits, err := operation_setting.PaymentConfigAmountCredit(value, tokens)
if err != nil {
return nil, err
}
if math.IsNaN(discount) || math.IsInf(discount, 0) || discount <= 0 {
return nil, fmt.Errorf("invalid top-up discount for catalog amount %s", amount)
}
key := strconv.FormatInt(credits, 10)
if previous, exists := discounts[key]; exists && previous != discount {
return nil, fmt.Errorf("conflicting top-up discounts for credit amount %s", key)
}
discounts[key] = discount
}
return discounts, nil
}
120 changes: 120 additions & 0 deletions apps/api-go/controller/topup_credit_discounts_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package controller

import (
"math"
"reflect"
"testing"

"github.com/LIghtJUNction/api.lmm.best/common"
"github.com/LIghtJUNction/api.lmm.best/setting/operation_setting"
"github.com/shopspring/decimal"
)

func TestCreditDiscountCatalogPreservesPolicies(t *testing.T) {
previousQPU := common.QuotaPerUnit
common.QuotaPerUnit = 500000
t.Cleanup(func() { common.QuotaPerUnit = previousQPU })
for _, tc := range []struct {
name string
tokens bool
input operation_setting.PaymentAmountDiscount
want map[string]float64
}{
{"USD_presets", false, operation_setting.PaymentAmountDiscount{"1": 0.8, "3.5": 0.7}, map[string]float64{"500000": 0.8, "1750000": 0.7}},
{"raw_credit_presets", true, operation_setting.PaymentAmountDiscount{"500000": 0.8, "1750000": 0.7}, map[string]float64{"500000": 0.8, "1750000": 0.7}},
{"positive_surcharge_preserved", false, operation_setting.PaymentAmountDiscount{"2": 1.1}, map[string]float64{"1000000": 1.1}},
{"equivalent_spelling", false, operation_setting.PaymentAmountDiscount{"3.5": 0.7, "3.50": 0.7}, map[string]float64{"1750000": 0.7}},
} {
t.Run(tc.name, func(t *testing.T) {
before := make(operation_setting.PaymentAmountDiscount, len(tc.input))
for key, value := range tc.input {
before[key] = value
}
got, err := topUpCreditDiscounts(tc.input, tc.tokens)
if err != nil || !reflect.DeepEqual(got, tc.want) {
t.Fatalf("discounts=%v error=%v want=%v", got, err, tc.want)
}
if !reflect.DeepEqual(before, tc.input) {
t.Fatal("reading discounts changed the persisted configuration")
}
})
}
}

func TestCreditDiscountCatalogRejectsConflictsWithoutPartialResult(t *testing.T) {
previousQPU := common.QuotaPerUnit
common.QuotaPerUnit = 500000
t.Cleanup(func() { common.QuotaPerUnit = previousQPU })
for _, config := range []operation_setting.PaymentAmountDiscount{
{"3.5": 0.7, "3.50": 0.8},
{"1": 0.8, "bad": 0.5},
{"1": math.NaN()}, {"1": math.Inf(1)}, {"1": 0}, {"1": -1},
} {
if got, err := topUpCreditDiscounts(config, false); err == nil || got != nil {
t.Fatalf("invalid catalog yielded partial/default discounts: %v %v", got, err)
}
}
}

func TestCanonicalQuoteIgnoresLegacyBatchProjection(t *testing.T) {
previousQPU := common.QuotaPerUnit
common.QuotaPerUnit = 500000
t.Cleanup(func() { common.QuotaPerUnit = previousQPU })
preserveChannelPricing(t)
preservePaymentCreditAnchor(t, "500000")
operation_setting.GetGeneralSetting().QuotaDisplayType = "CNY"
operation_setting.GetPaymentSetting().AmountDiscount = operation_setting.PaymentAmountDiscount{"1": 0.8}
if err := common.UpdateTopupGroupRatioByJSONString(`{"default":1,"ldc":0.14}`); err != nil {
t.Fatal(err)
}
pricing := payMethodSettlementPricing{
settlementCurrency: "LDC", usesSettlementUnitsPerPlatformUnit: true,
settlementUnitsPerPlatformUnit: decimal.NewFromInt(10),
}
for _, projection := range []string{"0", "1", "99", "0.000001"} {
original, paid, err := quoteTopUpResolvedSettlementAmounts(resolvedTopUpAmount{
CreditedQuota: 500000, LegacyBatch: decimal.RequireFromString(projection),
}, "ldc", pricing, decimal.RequireFromString("0.5"))
if err != nil || original.String() != "0.7" || paid.String() != "0.56" {
t.Fatalf("projection=%s original=%s paid=%s error=%v", projection, original, paid, err)
}
}
}

func TestCouponPreviewAndCheckoutCreditQualification(t *testing.T) {
previousQPU := common.QuotaPerUnit
common.QuotaPerUnit = 500000
t.Cleanup(func() { common.QuotaPerUnit = previousQPU })
preserveChannelPricing(t)
for _, display := range []string{"USD", "CNY", "TOKENS"} {
operation_setting.GetGeneralSetting().QuotaDisplayType = display
amount, err := topUpCouponAmountForCredits(1750000)
want := "3.5"
if display == "TOKENS" {
want = "1750000"
}
if err != nil || amount.String() != want {
t.Fatalf("display=%s amount=%s error=%v", display, amount, err)
}
}
for _, invalid := range []int64{0, -1, common.MaxWalletQuota + 1} {
if _, err := topUpCouponAmountForCredits(invalid); err == nil {
t.Fatalf("accepted invalid credits %d", invalid)
}
}
}

func TestTopUpSettlementFactorsPreserveRoundingOrder(t *testing.T) {
for _, tc := range []struct{ base, group, payment, discount, original, paid string }{
{"10", "0.14", "0.5", "0.8", "0.7", "0.56"},
{"0.015", "1", "1", "0.3", "0.02", "0"},
{"10", "1", "1", "0.95", "10", "9.5"},
} {
original, paid := applyTopUpSettlementFactorsWithOriginal(
decimal.RequireFromString(tc.base), decimal.RequireFromString(tc.group),
decimal.RequireFromString(tc.payment), decimal.RequireFromString(tc.discount))
if original.String() != tc.original || paid.String() != tc.paid {
t.Fatalf("original=%s paid=%s want=%s/%s", original, paid, tc.original, tc.paid)
}
}
}
30 changes: 6 additions & 24 deletions apps/api-go/controller/topup_credit_metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package controller

import (
"fmt"
"math"
"strconv"
"strings"

Expand Down Expand Up @@ -34,14 +33,8 @@ func topUpCreditMetadata(payMethods []map[string]string) (gin.H, error) {
}
quotaPerBatch := decimal.NewFromFloat(common.QuotaPerUnit)
tokens := operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens
catalogCredit := func(raw string, discount bool) (int64, error) {
var value decimal.Decimal
var err error
if discount {
value, err = operation_setting.ParsePaymentDiscountAmount(raw)
} else {
value, err = operation_setting.ParsePaymentAmount(raw)
}
catalogCredit := func(raw string) (int64, error) {
value, err := operation_setting.ParsePaymentAmount(raw)
if err != nil {
return 0, err
}
Expand All @@ -51,26 +44,15 @@ func topUpCreditMetadata(payMethods []map[string]string) (gin.H, error) {
paymentSetting := operation_setting.GetPaymentSetting()
options := make([]int64, 0, len(paymentSetting.AmountOptions))
for _, amount := range paymentSetting.AmountOptions {
credits, err := catalogCredit(amount.String(), false)
credits, err := catalogCredit(amount.String())
if err != nil {
return nil, err
}
options = append(options, credits)
}
discounts := make(map[string]float64, len(paymentSetting.AmountDiscount))
for amount, discount := range paymentSetting.AmountDiscount {
credits, err := catalogCredit(amount, true)
if err != nil {
return nil, err
}
if math.IsNaN(discount) || math.IsInf(discount, 0) || discount <= 0 {
return nil, fmt.Errorf("invalid top-up discount for catalog amount %s", amount)
}
key := strconv.FormatInt(credits, 10)
if previous, exists := discounts[key]; exists && previous != discount {
return nil, fmt.Errorf("conflicting top-up discounts for credit amount %s", key)
}
discounts[key] = discount
discounts, err := topUpCreditDiscounts(paymentSetting.AmountDiscount, tokens)
if err != nil {
return nil, err
}

metadata := gin.H{
Expand Down
24 changes: 24 additions & 0 deletions apps/api-go/controller/topup_legacy_coupon.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package controller

import (
"errors"

"github.com/LIghtJUNction/api.lmm.best/common"
"github.com/LIghtJUNction/api.lmm.best/setting/operation_setting"
"github.com/shopspring/decimal"
)

// topUpCouponAmountForCredits is the read adapter for existing coupon minimums.
// Both preview and checkout derive qualification from the same actual credit
// amount, never from resolvedTopUpAmount.LegacyBatch. Retain this adapter until
// persisted coupon terms have an audited, versioned unit migration.
func topUpCouponAmountForCredits(credits int64) (decimal.Decimal, error) {
if credits <= 0 || credits > common.MaxWalletQuota || common.ValidateWalletQuota(int(credits)) != nil || !validQuotaPerUnit() {
return decimal.Zero, errors.New("invalid coupon credit amount")
}
amount := decimal.NewFromInt(credits)
if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
return amount, nil
}
return amount.Div(decimal.NewFromFloat(common.QuotaPerUnit)), nil
}