63 lines
1.8 KiB
Go
63 lines
1.8 KiB
Go
package user
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
)
|
||
|
||
// getExchangeRate 获取积分兑换比率
|
||
// 配置含义:1 元 = X 积分(后台配置的值)
|
||
// 计算:分 / (100 / rate) = 分 * rate / 100
|
||
// 当 rate=1 时:1元=1积分,100分=1积分
|
||
// 当 rate=2 时:1元=2积分,50分=1积分
|
||
func (s *service) getExchangeRate(ctx context.Context) int64 {
|
||
// 读取后台配置的 key:points.exchange_rate
|
||
cfg, _ := s.readDB.SystemConfigs.WithContext(ctx).Where(s.readDB.SystemConfigs.ConfigKey.Eq("points.exchange_rate")).First()
|
||
rate := int64(1) // 默认 1 元 = 1 积分
|
||
if cfg != nil {
|
||
var r int64
|
||
_, _ = fmt.Sscanf(cfg.ConfigValue, "%d", &r)
|
||
if r > 0 {
|
||
rate = r
|
||
}
|
||
}
|
||
return rate
|
||
}
|
||
|
||
// CentsToPointsFloat 分 → 积分(浮点数,用于 API 返回展示)
|
||
// 公式:积分 = 分 * rate / 100
|
||
// 例如:rate=1, 3580分 → 35.8积分
|
||
// CentsToPointsFloat 分 → 积分(浮点数,用于 API 返回展示)
|
||
// 公式:积分 = 分 * rate / 100
|
||
// 例如:rate=1, 3580分 → 35.8积分
|
||
func (s *service) CentsToPointsFloat(ctx context.Context, cents int64) float64 {
|
||
if cents == 0 {
|
||
return 0
|
||
}
|
||
rate := s.getExchangeRate(ctx)
|
||
return float64(cents) * float64(rate) / 100
|
||
}
|
||
|
||
// CentsToPoints 分 → 积分(整数,向下取整,用于计算)
|
||
// 公式:积分 = 分 * rate / 100
|
||
func (s *service) CentsToPoints(ctx context.Context, cents int64) (int64, error) {
|
||
if cents <= 0 {
|
||
return 0, nil
|
||
}
|
||
rate := s.getExchangeRate(ctx)
|
||
return (cents * rate) / 100, nil
|
||
}
|
||
|
||
// PointsToCents 积分 → 分(用于将用户输入的积分转为分)
|
||
// 公式:分 = 积分 * 100 / rate
|
||
func (s *service) PointsToCents(ctx context.Context, pts int64) (int64, error) {
|
||
if pts <= 0 {
|
||
return 0, nil
|
||
}
|
||
rate := s.getExchangeRate(ctx)
|
||
if rate == 0 {
|
||
rate = 1
|
||
}
|
||
return (pts * 100) / rate, nil
|
||
}
|