蛋蛋星球-制度模式
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.

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