Skip to content

Commit

Permalink
Feat/active task (#5121)
Browse files Browse the repository at this point in the history
* feat active task & first recharge discount
* sort discount step & add lock for payment
  • Loading branch information
bxy4543 authored Oct 8, 2024
1 parent d9b34cd commit 351e761
Show file tree
Hide file tree
Showing 15 changed files with 563 additions and 77 deletions.
30 changes: 23 additions & 7 deletions controllers/account/controllers/account_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"fmt"
"math"
"os"
"sort"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -276,21 +277,36 @@ const BaseUnit = 1_000_000
// return getAmountWithDiscount(amount, *discount), nil
//}

func getAmountWithDiscount(amount int64, discount pkgtypes.RechargeDiscount) int64 {
if discount.SpecialDiscount != nil && discount.SpecialDiscount[amount/BaseUnit] != 0 {
return amount + discount.SpecialDiscount[amount/BaseUnit]*BaseUnit
}
func getAmountWithDiscount(amount int64, discount pkgtypes.UserRechargeDiscount) int64 {
var r float64
for i, s := range discount.DiscountSteps {
if amount >= s*BaseUnit {
r = discount.DiscountRates[i]
for _, step := range sortSteps(discount.DefaultSteps) {
ratio := discount.DefaultSteps[step]
if amount >= step*BaseUnit {
r = ratio
} else {
break
}
}
return int64(math.Ceil(float64(amount) * r / 100))
}

func sortSteps(steps map[int64]float64) (keys []int64) {
for k := range steps {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
return keys[i] < keys[j]
})
return
}

func getFirstRechargeDiscount(amount int64, discount pkgtypes.UserRechargeDiscount) (bool, int64) {
if discount.FirstRechargeSteps != nil && discount.FirstRechargeSteps[amount/BaseUnit] != 0 {
return true, int64(math.Ceil(float64(amount) * discount.FirstRechargeSteps[amount/BaseUnit] / 100))
}
return false, getAmountWithDiscount(amount, discount)
}

func (r *AccountReconciler) BillingCVM() error {
cvmMap, err := r.CVMDBClient.GetPendingStateInstance(os.Getenv("LOCAL_REGION"))
if err != nil {
Expand Down
85 changes: 63 additions & 22 deletions controllers/account/controllers/account_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package controllers

import (
"context"
"encoding/json"
"os"
"testing"

Expand All @@ -26,8 +27,6 @@ import (
"github.com/labring/sealos/controllers/pkg/database"
"github.com/labring/sealos/controllers/pkg/database/cockroach"
"github.com/labring/sealos/controllers/pkg/database/mongo"

"github.com/labring/sealos/controllers/pkg/types"
)

//func Test_giveGift(t *testing.T) {
Expand Down Expand Up @@ -70,26 +69,26 @@ import (
// }
//}

func Test_getAmountWithDiscount(t *testing.T) {
type args struct {
amount int64
discount types.RechargeDiscount
}
tests := []struct {
name string
args args
want int64
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := getAmountWithDiscount(tt.args.amount, tt.args.discount); got != tt.want {
t.Errorf("getAmountWithDiscount() = %v, want %v", got, tt.want)
}
})
}
}
//func Test_getAmountWithDiscount(t *testing.T) {
// type args struct {
// amount int64
// discount types.RechargeDiscount
// }
// tests := []struct {
// name string
// args args
// want int64
// }{
// // TODO: Add test cases.
// }
// for _, tt := range tests {
// t.Run(tt.name, func(t *testing.T) {
// if got := getAmountWithDiscount(tt.args.amount, tt.args.discount); got != tt.want {
// t.Errorf("getAmountWithDiscount() = %v, want %v", got, tt.want)
// }
// })
// }
//}

func TestAccountReconciler_BillingCVM(t *testing.T) {
dbCtx := context.Background()
Expand Down Expand Up @@ -136,3 +135,45 @@ func TestAccountReconciler_BillingCVM(t *testing.T) {
t.Errorf("AccountReconciler.BillingCVM() error = %v", err)
}
}

func TestAccountV2_GetAccountConfig(t *testing.T) {
os.Setenv("LOCAL_REGION", "")
v2Account, err := cockroach.NewCockRoach("", "")
if err != nil {
t.Fatalf("unable to connect to cockroach: %v", err)
}
defer func() {
err := v2Account.Close()
if err != nil {
t.Errorf("unable to disconnect from cockroach: %v", err)
}
}()
err = v2Account.InitTables()
if err != nil {
t.Fatalf("unable to init tables: %v", err)
}

//if err = v2Account.InsertAccountConfig(&types.AccountConfig{
// TaskProcessRegion: "192.160.0.55.nip.io",
// FirstRechargeDiscountSteps: map[int64]float64{
// 8: 100, 32: 100, 128: 100, 256: 100, 512: 100, 1024: 100,
// },
// DefaultDiscountSteps: map[int64]float64{
// //128,256,512,1024,2048,4096; 10,15,20,25,30,35
// 128: 10, 256: 15, 512: 20, 1024: 25, 2048: 30, 4096: 35,
// },
//}); err != nil {
// t.Fatalf("unable to insert account config: %v", err)
//}

aa, err := v2Account.GetAccountConfig()
if err != nil {
t.Fatalf("failed to get account config: %v", err)
}

data, err := json.MarshalIndent(aa, "", " ")
if err != nil {
t.Fatalf("failed to marshal account config: %v", err)
}
t.Logf("success get account config:\n%s", string(data))
}
67 changes: 39 additions & 28 deletions controllers/account/controllers/payment_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import (
"sync"
"time"

"github.com/google/uuid"

"sigs.k8s.io/controller-runtime/pkg/manager"

pkgtypes "github.com/labring/sealos/controllers/pkg/types"
Expand All @@ -47,6 +49,8 @@ type PaymentReconciler struct {
Logger logr.Logger
reconcileDuration time.Duration
createDuration time.Duration
accountConfig pkgtypes.AccountConfig
userLock map[uuid.UUID]*sync.Mutex
domain string
}

Expand All @@ -69,13 +73,14 @@ const (
//+kubebuilder:rbac:groups=account.sealos.io,resources=payments/finalizers,verbs=update

// SetupWithManager sets up the controller with the Manager.
func (r *PaymentReconciler) SetupWithManager(mgr ctrl.Manager) error {
func (r *PaymentReconciler) SetupWithManager(mgr ctrl.Manager) (err error) {
const controllerName = "payment_controller"
r.Logger = ctrl.Log.WithName(controllerName)
r.Logger.V(1).Info("init reconcile controller payment")
r.domain = os.Getenv("DOMAIN")
r.reconcileDuration = defaultReconcileDuration
r.createDuration = defaultCreateDuration
r.userLock = make(map[uuid.UUID]*sync.Mutex)
if duration := os.Getenv(EnvPaymentReconcileDuration); duration != "" {
reconcileDuration, err := time.ParseDuration(duration)
if err == nil {
Expand All @@ -88,6 +93,14 @@ func (r *PaymentReconciler) SetupWithManager(mgr ctrl.Manager) error {
r.createDuration = createDuration
}
}
r.accountConfig, err = r.Account.AccountV2.GetAccountConfig()
if err != nil {
return fmt.Errorf("get account config failed: %w", err)
}
if len(r.accountConfig.DefaultDiscountSteps) == 0 {
return fmt.Errorf("default discount steps is empty")
}
r.Logger.V(1).Info("account config", "config", r.accountConfig)
r.Logger.V(1).Info("reconcile duration", "reconcileDuration", r.reconcileDuration, "createDuration", r.createDuration)
if err := mgr.Add(r); err != nil {
return fmt.Errorf("add payment controller failed: %w", err)
Expand Down Expand Up @@ -142,22 +155,6 @@ func (r *PaymentReconciler) reconcilePayments(_ context.Context) (errs []error)
}

func (r *PaymentReconciler) reconcileCreatePayments(ctx context.Context) (errs []error) {
//paymentList := &accountv1.PaymentList{}
//listOpts := &client.ListOptions{
// FieldSelector: fields.OneTermEqualSelector("status.tradeNO", ""),
//}
//// handler old payment
//err := r.Client.List(context.Background(), paymentList, listOpts)
//if err != nil {
// errs = append(errs, fmt.Errorf("watch payment failed: %w", err))
// return
//}
//for _, payment := range paymentList.Items {
// if err := r.reconcileNewPayment(&payment); err != nil {
// errs = append(errs, fmt.Errorf("reconcile payment failed: payment: %s, user: %s, err: %w", payment.Name, payment.Spec.UserID, err))
// }
//}
// watch new payment
watcher, err := r.WatchClient.Watch(context.Background(), &accountv1.PaymentList{}, &client.ListOptions{})
if err != nil {
errs = append(errs, fmt.Errorf("watch payment failed: %w", err))
Expand Down Expand Up @@ -211,20 +208,34 @@ func (r *PaymentReconciler) reconcilePayment(payment *accountv1.Payment) error {
if err != nil {
return fmt.Errorf("get user failed: %w", err)
}
if r.userLock[user.UID] == nil {
r.userLock[user.UID] = &sync.Mutex{}
}
r.userLock[user.UID].Lock()
defer r.userLock[user.UID].Unlock()
userDiscount, err := r.Account.AccountV2.GetUserRechargeDiscount(&pkgtypes.UserQueryOpts{ID: payment.Spec.UserID})
if err != nil {
return fmt.Errorf("get user discount failed: %w", err)
}
//1¥ = 100WechatPayAmount; 1 WechatPayAmount = 10000 SealosAmount
payAmount := orderAmount * 10000
gift := getAmountWithDiscount(payAmount, r.Account.DefaultDiscount)
isFirstRecharge, gift := getFirstRechargeDiscount(payAmount, userDiscount)
paymentRaw := pkgtypes.PaymentRaw{
UserUID: user.UID,
Amount: payAmount,
Gift: gift,
CreatedAt: payment.CreationTimestamp.Time,
RegionUserOwner: getUsername(payment.Namespace),
Method: payment.Spec.PaymentMethod,
TradeNO: payment.Status.TradeNO,
CodeURL: payment.Status.CodeURL,
}
if isFirstRecharge {
paymentRaw.ActivityType = pkgtypes.ActivityTypeFirstRecharge
}

if err = r.Account.AccountV2.Payment(&pkgtypes.Payment{
PaymentRaw: pkgtypes.PaymentRaw{
UserUID: user.UID,
Amount: payAmount,
Gift: gift,
CreatedAt: payment.CreationTimestamp.Time,
RegionUserOwner: getUsername(payment.Namespace),
Method: payment.Spec.PaymentMethod,
TradeNO: payment.Status.TradeNO,
CodeURL: payment.Status.CodeURL,
},
PaymentRaw: paymentRaw,
}); err != nil {
return fmt.Errorf("payment failed: %w", err)
}
Expand Down
Loading

0 comments on commit 351e761

Please sign in to comment.