Files
slogan/styleagent/service/ad_service.go
T

57 lines
1.5 KiB
Go

package service
import (
"context"
"errors"
"slogan-agent/styleagent/consts"
"slogan-agent/styleagent/dao"
"github.com/gogf/gf/v2/frame/g"
)
type adService struct{}
var AdService = new(adService)
type AdRewardResult struct {
AdType string `json:"ad_type"`
RemainingToday int `json:"remaining_today"`
}
// Claim 领取广告激励:服务端限频计数,不信任客户端
func (s *adService) Claim(ctx context.Context, userId int64, adType string) (*AdRewardResult, error) {
if adType != consts.AdTypeEffectExtra && adType != consts.AdTypeVipTrial {
return nil, errors.New("无效的广告类型")
}
limit := rewardQuota(ctx, adType)
used, err := dao.AdRewardLog.CountTodayByType(ctx, userId, adType)
if err != nil {
return nil, err
}
if used >= limit {
return nil, errors.New("今日次数已用完")
}
if _, err := dao.AdRewardLog.Insert(ctx, userId, adType, limit); err != nil {
return nil, errors.New("今日次数已用完") // 唯一索引兜底并发
}
if adType == consts.AdTypeVipTrial {
_ = dao.UserMember.Upsert(ctx, userId, 0, NextExpire(nil, 1), consts.MemberSourceAdTrial)
}
return &AdRewardResult{AdType: adType, RemainingToday: limit - used - 1}, nil
}
func rewardQuota(ctx context.Context, adType string) int {
if adType == consts.AdTypeVipTrial {
return g.Cfg().MustGet(ctx, "ad.limit_vip_trial", 1).Int()
}
return g.Cfg().MustGet(ctx, "ad.limit_effect_extra", 2).Int()
}
func rewardRemaining(limit, used int) int {
if r := limit - used; r > 0 {
return r
}
return 0
}