generated from kedaya_haitao/template
77 lines
1.9 KiB
Go
77 lines
1.9 KiB
Go
package rate
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"strconv"
|
||
"strings"
|
||
|
||
"gitea.timerzz.com/kedaya_haitao/common/pkg/subscribe"
|
||
"gitea.timerzz.com/kedaya_haitao/common/structs/storage"
|
||
"gitea.timerzz.com/kedaya_haitao/common/structs/utils"
|
||
"github.com/golang/glog"
|
||
"github.com/redis/go-redis/v9"
|
||
"golang.org/x/sync/errgroup"
|
||
)
|
||
|
||
type Controller struct {
|
||
ctx context.Context
|
||
storage *storage.Storage
|
||
subscribe *subscribe.Server
|
||
}
|
||
|
||
func NewController(ctx context.Context, storage *storage.Storage, rdb *redis.Client) *Controller {
|
||
return &Controller{
|
||
storage: storage,
|
||
subscribe: subscribe.NewServer(ctx, rdb),
|
||
}
|
||
}
|
||
|
||
func (c *Controller) Run() error {
|
||
c.subscribe.SetErrorHandle(func(err error) {
|
||
glog.Error(err)
|
||
})
|
||
if err := c.subscribe.Subscribe(utils.ProfitRate_Channel, c.Rate); err != nil {
|
||
return fmt.Errorf("订阅失败:%v", err)
|
||
}
|
||
c.subscribe.Run()
|
||
return nil
|
||
}
|
||
|
||
// 处理接受到的信息
|
||
func (c *Controller) Rate(ctx context.Context, idString string) error {
|
||
var ids = strings.Split(idString, ",")
|
||
var wg errgroup.Group
|
||
for _, id := range ids {
|
||
var i = id
|
||
wg.Go(func() error {
|
||
return c.rate(ctx, i)
|
||
})
|
||
}
|
||
return wg.Wait()
|
||
}
|
||
|
||
// 处理接收到的信息
|
||
func (c *Controller) rate(ctx context.Context, idString string) error {
|
||
i, _ := strconv.Atoi(idString)
|
||
if i <= 0 {
|
||
return fmt.Errorf("接收到的id不正确:%s", idString)
|
||
}
|
||
id := uint(i)
|
||
article, err := c.storage.Article().Get(storage.NewGetArticleQuery().SetID(id))
|
||
if err != nil {
|
||
return fmt.Errorf("获取商品 id: %d, 失败:%v", id, err)
|
||
}
|
||
after, changed := utils.ProfitRate(&article)
|
||
if !changed {
|
||
return nil
|
||
}
|
||
// 保存更新
|
||
return c.storage.Article().Update(*after, "cost_price", "sell_price", "available", "updated_at", "rate", "GrossProfit")
|
||
}
|
||
|
||
func Decimal(num float64) float64 {
|
||
num, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", num), 64)
|
||
return num
|
||
}
|