Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
116 changes: 116 additions & 0 deletions controller/payment_webhook_availability_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import (
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"fmt"
"maps"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"

Expand Down Expand Up @@ -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
Expand Down
18 changes: 12 additions & 6 deletions controller/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,17 @@ 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 {
BillingPreference string `json:"billing_preference"`
}

type SubscriptionBalancePayRequest struct {
PlanId int `json:"plan_id"`
PlanId int `json:"plan_id"`
ExpectedQuota *int `json:"expected_quota"`
}

// ---- User APIs ----
Expand All @@ -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 = &quota
}
}
result = append(result, record)
}
common.ApiSuccess(c, result)
}
Expand Down Expand Up @@ -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
}
Expand Down
34 changes: 23 additions & 11 deletions model/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ package model
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"sync"
"time"

"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"
Expand Down Expand Up @@ -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")
}
Expand All @@ -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 {
Expand Down
Loading