蛋蛋星球-制度模式
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

442 rivejä
16 KiB

  1. package egg_energy
  2. import (
  3. "code.fnuoos.com/EggPlanet/egg_models.git/src/implement"
  4. "code.fnuoos.com/EggPlanet/egg_models.git/src/model"
  5. "code.fnuoos.com/EggPlanet/egg_system_rules.git/enum"
  6. "code.fnuoos.com/EggPlanet/egg_system_rules.git/md"
  7. "code.fnuoos.com/EggPlanet/egg_system_rules.git/rule"
  8. md2 "code.fnuoos.com/EggPlanet/egg_system_rules.git/rule/egg_energy/md"
  9. egg_system_rules "code.fnuoos.com/EggPlanet/egg_system_rules.git/utils"
  10. "code.fnuoos.com/EggPlanet/egg_system_rules.git/utils/cache"
  11. "code.fnuoos.com/EggPlanet/egg_system_rules.git/utils/es"
  12. zhios_order_relate_logx "code.fnuoos.com/EggPlanet/egg_system_rules.git/utils/logx"
  13. es2 "code.fnuoos.com/go_rely_warehouse/zyos_go_es.git/es"
  14. "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit"
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "github.com/olivere/elastic/v7"
  19. "github.com/shopspring/decimal"
  20. "strings"
  21. "time"
  22. "xorm.io/xorm"
  23. )
  24. // SettlementGiveActivityCoin 结算观看激励广告得到蛋蛋积分
  25. func SettlementGiveActivityCoin(engine *xorm.Engine, user model.User, ecpm string, ch *rabbit.Channel) (rewardValue float64, err error) {
  26. uid := user.Id
  27. now := time.Now()
  28. //1、查找 `egg_energy_basic_setting` 基础设置
  29. eggEnergyBasicSettingDb := implement.NewEggEnergyBasicSettingDb(engine)
  30. eggEnergyBasicSetting, err := eggEnergyBasicSettingDb.EggEnergyBasicSettingGetOneByParams(map[string]interface{}{
  31. "key": "is_open",
  32. "value": 1,
  33. })
  34. if err != nil {
  35. return
  36. }
  37. if eggEnergyBasicSetting == nil {
  38. err = errors.New("蛋蛋能量设置未开启!")
  39. return
  40. }
  41. if eggEnergyBasicSetting.VideoRewardIsOpen == 1 {
  42. var videoRewardSystem *md2.VideoRewardSystemStruct
  43. err = json.Unmarshal([]byte(eggEnergyBasicSetting.VideoRewardSystem), &videoRewardSystem)
  44. if err != nil {
  45. return
  46. }
  47. if videoRewardSystem.RewardTotalNum == "" || videoRewardSystem.IntervalMinutes == "" || videoRewardSystem.EachRoundHour == "" {
  48. err = errors.New("视屏奖励机制设置未完全!")
  49. return
  50. }
  51. var rewardSystem []*md2.RewardSystemStruct
  52. err = json.Unmarshal([]byte(eggEnergyBasicSetting.RewardSystem), &rewardSystem)
  53. if err != nil {
  54. return
  55. }
  56. if len(rewardSystem) == 0 {
  57. err = errors.New("未设置奖励机制!")
  58. return
  59. }
  60. go dealEcpm(user, ecpm, ch) //TODO::协程处理ecpm的变化
  61. //TODO::奖励多少个活跃积分(根据ecpm, 新用户机制, 蛋蛋分机制)
  62. redisConn := cache.GetPool().Get()
  63. defer redisConn.Close()
  64. sysCfgDb := implement.NewSysCfgDb(engine, redisConn)
  65. videoRewardUnitPrice := sysCfgDb.SysCfgGetWithDb(enum.VideoRewardUnitPrice)
  66. if videoRewardUnitPrice != "" { //处理ecpm
  67. var coin model.VirtualCoin
  68. _, err = engine.Where("id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).Get(&coin)
  69. if err != nil {
  70. return rewardValue, err
  71. }
  72. activePointsCoinExchangeRatioValue, _ := decimal.NewFromString(coin.ExchangeRatio)
  73. videoRewardUnitPriceValue, _ := decimal.NewFromString(videoRewardUnitPrice)
  74. rewardValue, _ = videoRewardUnitPriceValue.Mul(activePointsCoinExchangeRatioValue).Float64()
  75. } else {
  76. rewardValue = egg_system_rules.StrToFloat64(videoRewardSystem.RewardValue)
  77. }
  78. var newUserRewardRules *md2.NewUserRewardRules
  79. err = json.Unmarshal([]byte(eggEnergyBasicSetting.NewUserIncentiveRules), &newUserRewardRules)
  80. if err != nil {
  81. return
  82. }
  83. userCreateAt := egg_system_rules.String2Time(user.CreateAt)
  84. if int(now.Sub(userCreateAt).Hours()/24) <= newUserRewardRules.ContinueDays { //处理新用户机制
  85. rewardValue *= newUserRewardRules.RewardCoefficient
  86. }
  87. score := 60.00
  88. esIndex := es.GetLatestEffectiveIndexFromAlias(now)
  89. esIndexName := md.EggEnergyUserEggScoreEsAlias + "_" + esIndex
  90. results, err1 := es2.FirstDoc(esIndexName, esIndex+"_"+egg_system_rules.Int64ToStr(user.Id))
  91. if err1 != nil {
  92. if !elastic.IsNotFound(err1) {
  93. return rewardValue, err1
  94. }
  95. }
  96. if !elastic.IsNotFound(err1) {
  97. var doc md.EggEnergyUserEggScoreEs
  98. err = json.Unmarshal(results.Source, &doc)
  99. if err != nil {
  100. return
  101. }
  102. score = doc.ScoreValue
  103. }
  104. eggPointPartitionCoefficientManagementDb := implement.NewEggPointPartitionCoefficientManagementDb(engine)
  105. eggPointPartitionCoefficientManagements, err1 := eggPointPartitionCoefficientManagementDb.EggPointPartitionCoefficientManagementGetAll()
  106. if err1 != nil {
  107. return rewardValue, err1
  108. }
  109. for _, v := range *eggPointPartitionCoefficientManagements { //处理蛋蛋分机制
  110. if egg_system_rules.StrToFloat64(v.StartScore) <= score && egg_system_rules.StrToFloat64(v.EndScore) >= score {
  111. rewardValue *= egg_system_rules.StrToFloat64(v.Coefficient)
  112. }
  113. }
  114. //处理圈层奖励
  115. var rewardSystemMap = map[int]*md2.RewardSystemStruct{}
  116. for _, v := range rewardSystem {
  117. rewardSystemMap[v.Level] = v
  118. }
  119. publicPlatoonUserRelationDb := implement.NewPublicPlatoonUserRelationDb(engine)
  120. publicPlatoonUserRelation, err1 := publicPlatoonUserRelationDb.PublicPlatoonUserRelationGetOneByParams(map[string]interface{}{
  121. "key": "uid",
  122. "value": uid,
  123. })
  124. if err1 != nil {
  125. return rewardValue, err1
  126. }
  127. var rewardFather []struct {
  128. Uid int64 `json:"uid"` //用户id
  129. RewardValue float64 `json:"reward_value"` //奖励值
  130. }
  131. var fatherUids []string
  132. if publicPlatoonUserRelation != nil {
  133. fatherUids = strings.Split(publicPlatoonUserRelation.FatherUid, "-")
  134. }
  135. for k, id := range fatherUids {
  136. tmpOneCirclesPublicPlatoonUserRelation, err11 := publicPlatoonUserRelationDb.PublicPlatoonUserRelationGetOneByParams(map[string]interface{}{
  137. "key": "id",
  138. "value": id,
  139. })
  140. if err11 != nil {
  141. return rewardValue, err11
  142. }
  143. if tmpOneCirclesPublicPlatoonUserRelation == nil {
  144. continue
  145. }
  146. if tmpOneCirclesPublicPlatoonUserRelation.Uid <= 0 {
  147. //待填充位
  148. continue
  149. }
  150. fatherUid := egg_system_rules.Int64ToStr(tmpOneCirclesPublicPlatoonUserRelation.Uid)
  151. fatherReward := rewardSystemMap[k+1]
  152. //TODO::判断是否活跃
  153. var m model.EggSignIn
  154. has, err33 := engine.Where("uid =?", fatherUid).And("end_time >=?", time.Now().Format("2006-01-02 15:04:05")).Get(&m)
  155. if err33 != nil {
  156. return rewardValue, err33
  157. }
  158. if !has {
  159. //不活跃不需要奖励
  160. continue
  161. }
  162. //判断是否满足奖励条件
  163. userRelateDb := implement.NewUserRelateDb(engine)
  164. userCount, _, err2 := userRelateDb.SumUserRelateByParentUid(fatherUid)
  165. if err2 != nil {
  166. return rewardValue, err2
  167. }
  168. if fatherReward != nil && userCount >= egg_system_rules.StrToInt64(fatherReward.RewardCondition) {
  169. fatherRewardValue := rewardValue * (egg_system_rules.StrToFloat64(fatherReward.RewardValue) / 100)
  170. rewardFather = append(rewardFather, struct {
  171. Uid int64 `json:"uid"` //用户id
  172. RewardValue float64 `json:"reward_value"` //奖励值
  173. }{
  174. Uid: egg_system_rules.StrToInt64(fatherUid),
  175. RewardValue: fatherRewardValue,
  176. })
  177. }
  178. }
  179. //增加 egg_user_watch_records 记录
  180. eggEnergyUserWatchRecordsDb := implement.NewEggEnergyUserWatchRecordsDb(engine)
  181. eggEnergyUserWatchRecords, err1 := eggEnergyUserWatchRecordsDb.EggEnergyUserWatchRecordsGetOneByParams(map[string]interface{}{
  182. "key": "uid",
  183. "value": uid,
  184. })
  185. if err1 != nil {
  186. return rewardValue, err1
  187. }
  188. now := time.Now()
  189. if eggEnergyUserWatchRecords == nil {
  190. residueWatchAdNum := egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum) - 1
  191. if residueWatchAdNum < 0 {
  192. residueWatchAdNum = egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum)
  193. }
  194. eggEnergyUserWatchRecords = &model.EggEnergyUserWatchRecords{
  195. Uid: uid,
  196. NextWatchAdDate: now.Add(time.Hour * time.Duration(egg_system_rules.StrToInt(videoRewardSystem.EachRoundHour))),
  197. ResidueWatchAdNum: egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum) - 1,
  198. CreateAt: now.Format("2006-01-02 15:04:05"),
  199. UpdateAt: now.Format("2006-01-02 15:04:05"),
  200. }
  201. _, err2 := eggEnergyUserWatchRecordsDb.EggEnergyUserWatchRecordsInsert(eggEnergyUserWatchRecords)
  202. if err2 != nil {
  203. return rewardValue, err2
  204. }
  205. } else {
  206. residueWatchAdNum := eggEnergyUserWatchRecords.ResidueWatchAdNum - 1
  207. nextWatchAdDate := eggEnergyUserWatchRecords.NextWatchAdDate
  208. if residueWatchAdNum == 0 { //最后一条广告
  209. residueWatchAdNum = egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum)
  210. }
  211. if residueWatchAdNum == egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum)-1 { //第一条广告
  212. nextWatchAdDate = now.Add(time.Hour * time.Duration(egg_system_rules.StrToInt(videoRewardSystem.EachRoundHour)))
  213. }
  214. eggEnergyUserWatchRecords.ResidueWatchAdNum = residueWatchAdNum
  215. eggEnergyUserWatchRecords.NextWatchAdDate = nextWatchAdDate
  216. _, err2 := eggEnergyUserWatchRecordsDb.EggEnergyUserWatchRecordsUpdate(eggEnergyUserWatchRecords.Id, eggEnergyUserWatchRecords, "residue_watch_ad_num", "next_watch_ad_date")
  217. if err2 != nil {
  218. return rewardValue, err2
  219. }
  220. }
  221. session := engine.NewSession()
  222. defer func() {
  223. session.Close()
  224. if err := recover(); err != nil {
  225. _ = zhios_order_relate_logx.Error(err)
  226. }
  227. }()
  228. session.Begin()
  229. //给相应的用户加上"个人"活跃积分
  230. err = rule.DealUserVirtualCoin(session, md.DealUserVirtualCoinReq{
  231. Kind: "add",
  232. Title: enum.UserVirtualAmountFlowTransferType.String(enum.EggEnergyWatchAdRewardPersonalActiveCoin),
  233. TransferType: int(enum.EggEnergyWatchAdRewardPersonalActiveCoin),
  234. CoinId: eggEnergyBasicSetting.PersonEggPointsCoinId,
  235. Uid: uid,
  236. Amount: rewardValue,
  237. })
  238. if err != nil {
  239. _ = session.Rollback()
  240. fmt.Println("err:::::2222", err)
  241. return rewardValue, err
  242. }
  243. //给相应的用户加上"团队"活跃积分
  244. for _, vv := range rewardFather {
  245. //TODO::推入rabbitmq 异步处理
  246. ch.Publish(md2.EggEnergyExchange, md.DealUserVirtualCoinReq{
  247. Kind: "add",
  248. Title: enum.UserVirtualAmountFlowTransferType.String(enum.EggEnergyWatchAdRewardTeamActiveCoin),
  249. TransferType: int(enum.EggEnergyWatchAdRewardTeamActiveCoin),
  250. CoinId: eggEnergyBasicSetting.TeamEggPointsCoinId,
  251. Uid: vv.Uid,
  252. Amount: vv.RewardValue,
  253. }, md2.EggEnergyRoutKeyForSettlementPublicGiveActivityCoin)
  254. }
  255. err = session.Commit()
  256. if err != nil {
  257. _ = session.Rollback()
  258. return rewardValue, errors.New("事务提交失败")
  259. }
  260. redisKey := fmt.Sprintf(md2.UserNextWatchAdDate, uid)
  261. var watchAdDate string
  262. if eggEnergyUserWatchRecords.ResidueWatchAdNum == egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum) {
  263. if eggEnergyUserWatchRecords.NextWatchAdDate.Before(time.Now()) {
  264. watchAdDate = ""
  265. } else {
  266. watchAdDate = eggEnergyUserWatchRecords.NextWatchAdDate.Format("2006-01-02 15:04:05")
  267. }
  268. } else {
  269. watchAdDate = time.Now().Add(time.Duration(egg_system_rules.StrToInt64(videoRewardSystem.IntervalMinutes)) * time.Second).Format("2006-01-02 15:04:05")
  270. }
  271. cache.SetEx(redisKey, watchAdDate, 60*60*24) //TODO::默认缓存1小时
  272. }
  273. return
  274. }
  275. func dealEcpm(user model.User, ecpm string, ch *rabbit.Channel) {
  276. //查找缓存中的ecpm值和当前的ecpm是否一致
  277. key := fmt.Sprintf(md.UserEcpmCacheKey, user.Id)
  278. ecpmCacheValue, _ := cache.GetString(key)
  279. if ecpmCacheValue == "" || ecpmCacheValue != ecpm {
  280. //更新缓存值
  281. cache.SetEx(key, ecpm, md.UserEcpmCacheTime)
  282. //TODO::推入rabbitmq 异步处理
  283. ch.Publish(md2.EggEnergyExchange, md.DealUserEcpmReq{
  284. Uid: user.Id,
  285. Ecpm: ecpm,
  286. }, md2.EggEnergyRoutKeyForDealUserEcpm)
  287. }
  288. }
  289. func ActivityCoinToAlipayRealName(engine *xorm.Engine, uid int64, amount string) (err error) {
  290. amountValue, _ := decimal.NewFromString(amount)
  291. //1、查找 `egg_energy_basic_setting` 基础设置
  292. eggEnergyBasicSettingDb := implement.NewEggEnergyBasicSettingDb(engine)
  293. eggEnergyBasicSetting, err := eggEnergyBasicSettingDb.EggEnergyBasicSettingGetOneByParams(map[string]interface{}{
  294. "key": "is_open",
  295. "value": 1,
  296. })
  297. if err != nil {
  298. return
  299. }
  300. if eggEnergyBasicSetting == nil {
  301. err = errors.New("蛋蛋能量设置未开启!")
  302. return
  303. }
  304. var coin model.VirtualCoin
  305. _, err = engine.Where("id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).Get(&coin)
  306. if err != nil {
  307. return
  308. }
  309. personActivePointsCoinExchangeRatioValue, _ := decimal.NewFromString(coin.ExchangeRatio)
  310. //2、判断个人蛋蛋积分是否足够
  311. var personUserVirtualAmount model.UserVirtualAmount
  312. _, err = engine.Where("coin_id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).And("uid =?", uid).Get(&personUserVirtualAmount)
  313. if err != nil {
  314. fmt.Println("err:::::1111", err)
  315. return
  316. }
  317. personUserVirtualAmountValue, _ := decimal.NewFromString(personUserVirtualAmount.Amount)
  318. needVirtualAmountValue := amountValue.Mul(personActivePointsCoinExchangeRatioValue)
  319. needVirtualAmount, _ := amountValue.Mul(personActivePointsCoinExchangeRatioValue).Float64()
  320. if personUserVirtualAmountValue.LessThan(needVirtualAmountValue) {
  321. err = errors.New("当前蛋蛋积分不足!")
  322. return
  323. }
  324. //3、扣除对应个人蛋蛋积分
  325. session := engine.NewSession()
  326. defer func() {
  327. session.Close()
  328. if err := recover(); err != nil {
  329. _ = zhios_order_relate_logx.Error(err)
  330. }
  331. }()
  332. session.Begin()
  333. //给相应的用户加上"个人"活跃积分
  334. err = rule.DealUserVirtualCoin(session, md.DealUserVirtualCoinReq{
  335. Kind: "sub",
  336. Title: enum.UserVirtualAmountFlowTransferType.String(enum.EggPointCoinToAliPayRealName),
  337. TransferType: int(enum.EggPointCoinToAliPayRealName),
  338. CoinId: eggEnergyBasicSetting.PersonEggPointsCoinId,
  339. Uid: uid,
  340. Amount: needVirtualAmount,
  341. })
  342. if err != nil {
  343. _ = session.Rollback()
  344. fmt.Println("err:::::2222", err)
  345. return err
  346. }
  347. err = session.Commit()
  348. if err != nil {
  349. _ = session.Rollback()
  350. return errors.New("事务提交失败")
  351. }
  352. return
  353. }
  354. func CheckActivityCoinToAlipayRealName(engine *xorm.Engine, uid int64, amount string) (err error, isCan bool) {
  355. amountValue, _ := decimal.NewFromString(amount)
  356. //1、查找 `egg_energy_basic_setting` 基础设置
  357. eggEnergyBasicSettingDb := implement.NewEggEnergyBasicSettingDb(engine)
  358. eggEnergyBasicSetting, err := eggEnergyBasicSettingDb.EggEnergyBasicSettingGetOneByParams(map[string]interface{}{
  359. "key": "is_open",
  360. "value": 1,
  361. })
  362. if err != nil {
  363. return
  364. }
  365. if eggEnergyBasicSetting == nil {
  366. err = errors.New("蛋蛋能量设置未开启!")
  367. return
  368. }
  369. var coin model.VirtualCoin
  370. _, err = engine.Where("id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).Get(&coin)
  371. if err != nil {
  372. return
  373. }
  374. personActivePointsCoinExchangeRatioValue, _ := decimal.NewFromString(coin.ExchangeRatio)
  375. //2、判断个人蛋蛋积分是否足够
  376. var personUserVirtualAmount model.UserVirtualAmount
  377. _, err = engine.Where("coin_id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).And("uid =?", uid).Get(&personUserVirtualAmount)
  378. if err != nil {
  379. fmt.Println("err:::::1111", err)
  380. return
  381. }
  382. personUserVirtualAmountValue, _ := decimal.NewFromString(personUserVirtualAmount.Amount)
  383. needVirtualAmountValue := amountValue.Mul(personActivePointsCoinExchangeRatioValue)
  384. if personUserVirtualAmountValue.GreaterThan(needVirtualAmountValue) {
  385. isCan = true
  386. }
  387. return
  388. }
  389. // CalcUserContinuousDailyActivityDays 计算用户连续活跃天数
  390. func CalcUserContinuousDailyActivityDays(engine *xorm.Engine, uid int, startDate string, endDate string) (err error, days int, isContinuousDailyActivity bool) {
  391. startAt, err := time.ParseInLocation("2006-01-02", startDate, time.Local) //起始时间
  392. endAt, err := time.ParseInLocation("2006-01-02", endDate, time.Local) //起始时间
  393. var list []model.EggEnergyUserActivity
  394. err = engine.Where("date >= ?", startAt.Format("2006-01-02")).
  395. And("date < ?", endAt.Format("2006-01-02")).
  396. And("uid =?", uid).Find(&list)
  397. if err != nil {
  398. fmt.Println("err:::::1111", err)
  399. return
  400. }
  401. days = len(list)
  402. diffDays := egg_system_rules.GetDiffDays(endAt, startAt) //相差天数
  403. if days == diffDays {
  404. isContinuousDailyActivity = true
  405. }
  406. return
  407. }