From 2f53a960d3c74f08fd1bd0219829a7dcb6941acc Mon Sep 17 00:00:00 2001 From: LIghtJUNction Date: Sun, 11 Oct 2026 07:01:30 +0800 Subject: [PATCH 1/7] refactor(topup): validate configured discounts by credited quota --- .../controller/topup_credit_discounts.go | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 apps/api-go/controller/topup_credit_discounts.go diff --git a/apps/api-go/controller/topup_credit_discounts.go b/apps/api-go/controller/topup_credit_discounts.go new file mode 100644 index 000000000..40d883e59 --- /dev/null +++ b/apps/api-go/controller/topup_credit_discounts.go @@ -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 +} From cb567dab5ee79755bda683fa2e0dffd08fde143f Mon Sep 17 00:00:00 2001 From: LIghtJUNction Date: Sun, 11 Oct 2026 07:01:36 +0800 Subject: [PATCH 2/7] refactor(topup): isolate legacy coupon thresholds behind credit adapter --- apps/api-go/controller/topup_legacy_coupon.go | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 apps/api-go/controller/topup_legacy_coupon.go diff --git a/apps/api-go/controller/topup_legacy_coupon.go b/apps/api-go/controller/topup_legacy_coupon.go new file mode 100644 index 000000000..f8968e74f --- /dev/null +++ b/apps/api-go/controller/topup_legacy_coupon.go @@ -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 +} From b29fc04cab68db288edd349bff507c04f20a868d Mon Sep 17 00:00:00 2001 From: LIghtJUNction Date: Sun, 11 Oct 2026 07:01:48 +0800 Subject: [PATCH 3/7] refactor(topup): use authoritative CREDIT for promotions and coupon checks --- .../controller/topup_canonical_credit.go | 27 ++++++++++++------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/apps/api-go/controller/topup_canonical_credit.go b/apps/api-go/controller/topup_canonical_credit.go index f9ccd3c3e..a9f5b328c 100644 --- a/apps/api-go/controller/topup_canonical_credit.go +++ b/apps/api-go/controller/topup_canonical_credit.go @@ -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 @@ -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 } @@ -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) } From 24171ddfdeefc05cc992e9f746b81ce43a0f9678 Mon Sep 17 00:00:00 2001 From: LIghtJUNction Date: Sun, 11 Oct 2026 07:02:00 +0800 Subject: [PATCH 4/7] refactor(topup): share settlement-factor and rounding operation --- apps/api-go/controller/topup.go | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/apps/api-go/controller/topup.go b/apps/api-go/controller/topup.go index 1a3ffe44c..913c6efc3 100644 --- a/apps/api-go/controller/topup.go +++ b/apps/api-go/controller/topup.go @@ -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. From 9594d458d0f4347c3f41a02c809d222e03035b23 Mon Sep 17 00:00:00 2001 From: LIghtJUNction Date: Sun, 11 Oct 2026 07:02:12 +0800 Subject: [PATCH 5/7] refactor(topup): share CREDIT threshold decoding between catalog and checkout --- .../controller/topup_credit_metadata.go | 30 ++++--------------- 1 file changed, 6 insertions(+), 24 deletions(-) diff --git a/apps/api-go/controller/topup_credit_metadata.go b/apps/api-go/controller/topup_credit_metadata.go index 44b9cbc08..db77dc276 100644 --- a/apps/api-go/controller/topup_credit_metadata.go +++ b/apps/api-go/controller/topup_credit_metadata.go @@ -2,7 +2,6 @@ package controller import ( "fmt" - "math" "strconv" "strings" @@ -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 } @@ -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{ From f52f37254bb6fec8e31764217d101c03c50b2863 Mon Sep 17 00:00:00 2001 From: LIghtJUNction Date: Sun, 11 Oct 2026 07:02:19 +0800 Subject: [PATCH 6/7] refactor(coupon): preview qualification from canonical CREDIT --- apps/api-go/controller/discount_code.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/apps/api-go/controller/discount_code.go b/apps/api-go/controller/discount_code.go index c5ec3c516..5e258f8aa 100644 --- a/apps/api-go/controller/discount_code.go +++ b/apps/api-go/controller/discount_code.go @@ -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() From dfaba8bb79d4224d57c63f6b2f0a7cd824bdd20e Mon Sep 17 00:00:00 2001 From: LIghtJUNction Date: Sun, 11 Oct 2026 07:02:35 +0800 Subject: [PATCH 7/7] test(topup): assert canonical discounts preserve configured policies --- .../controller/topup_credit_discounts_test.go | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 apps/api-go/controller/topup_credit_discounts_test.go diff --git a/apps/api-go/controller/topup_credit_discounts_test.go b/apps/api-go/controller/topup_credit_discounts_test.go new file mode 100644 index 000000000..3a86ab07f --- /dev/null +++ b/apps/api-go/controller/topup_credit_discounts_test.go @@ -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) + } + } +}