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

440 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. eggEnergyUserWatchRecords = &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. _, err2 := eggEnergyUserWatchRecordsDb.EggEnergyUserWatchRecordsInsert(eggEnergyUserWatchRecords)
  201. if err2 != nil {
  202. return rewardValue, err2
  203. }
  204. } else {
  205. residueWatchAdNum := eggEnergyUserWatchRecords.ResidueWatchAdNum - 1
  206. nextWatchAdDate := eggEnergyUserWatchRecords.NextWatchAdDate
  207. if residueWatchAdNum == 0 { //最后一条广告
  208. residueWatchAdNum = egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum)
  209. }
  210. if residueWatchAdNum == egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum)-1 { //第一条广告
  211. nextWatchAdDate = now.Add(time.Hour * time.Duration(egg_system_rules.StrToInt(videoRewardSystem.EachRoundHour)))
  212. }
  213. eggEnergyUserWatchRecords.ResidueWatchAdNum = residueWatchAdNum
  214. eggEnergyUserWatchRecords.NextWatchAdDate = nextWatchAdDate
  215. _, err2 := eggEnergyUserWatchRecordsDb.EggEnergyUserWatchRecordsUpdate(eggEnergyUserWatchRecords.Id, eggEnergyUserWatchRecords, "residue_watch_ad_num", "next_watch_ad_date")
  216. if err2 != nil {
  217. return rewardValue, err2
  218. }
  219. }
  220. session := engine.NewSession()
  221. defer func() {
  222. session.Close()
  223. if err := recover(); err != nil {
  224. _ = zhios_order_relate_logx.Error(err)
  225. }
  226. }()
  227. session.Begin()
  228. //给相应的用户加上"个人"活跃积分
  229. err = rule.DealUserVirtualCoin(session, md.DealUserVirtualCoinReq{
  230. Kind: "add",
  231. Title: enum.UserVirtualAmountFlowTransferType.String(enum.EggEnergyWatchAdRewardPersonalActiveCoin),
  232. TransferType: int(enum.EggEnergyWatchAdRewardPersonalActiveCoin),
  233. CoinId: eggEnergyBasicSetting.PersonEggPointsCoinId,
  234. Uid: uid,
  235. Amount: rewardValue,
  236. })
  237. if err != nil {
  238. _ = session.Rollback()
  239. fmt.Println("err:::::2222", err)
  240. return rewardValue, err
  241. }
  242. //给相应的用户加上"团队"活跃积分
  243. for _, vv := range rewardFather {
  244. //TODO::推入rabbitmq 异步处理
  245. ch.Publish(md2.EggEnergyExchange, md.DealUserVirtualCoinReq{
  246. Kind: "add",
  247. Title: enum.UserVirtualAmountFlowTransferType.String(enum.EggEnergyWatchAdRewardTeamActiveCoin),
  248. TransferType: int(enum.EggEnergyWatchAdRewardTeamActiveCoin),
  249. CoinId: eggEnergyBasicSetting.TeamEggPointsCoinId,
  250. Uid: vv.Uid,
  251. Amount: vv.RewardValue,
  252. }, md2.EggEnergyRoutKeyForSettlementPublicGiveActivityCoin)
  253. }
  254. err = session.Commit()
  255. if err != nil {
  256. _ = session.Rollback()
  257. return rewardValue, errors.New("事务提交失败")
  258. }
  259. redisKey := fmt.Sprintf(md2.UserNextWatchAdDate, uid)
  260. var watchAdDate string
  261. if eggEnergyUserWatchRecords.ResidueWatchAdNum == egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum) {
  262. if eggEnergyUserWatchRecords.NextWatchAdDate.Before(time.Now()) {
  263. watchAdDate = ""
  264. } else {
  265. watchAdDate = eggEnergyUserWatchRecords.NextWatchAdDate.Format("2006-01-02 15:04:05")
  266. }
  267. } else {
  268. watchAdDate = time.Now().Add(time.Duration(egg_system_rules.StrToInt64(videoRewardSystem.IntervalMinutes)) * time.Second).Format("2006-01-02 15:04:05")
  269. }
  270. cache.SetEx(redisKey, watchAdDate, 60*60*24) //TODO::默认缓存1小时
  271. }
  272. return
  273. }
  274. func dealEcpm(user model.User, ecpm string, ch *rabbit.Channel) {
  275. //查找缓存中的ecpm值和当前的ecpm是否一致
  276. key := fmt.Sprintf(md.UserEcpmCacheKey, user.Id)
  277. ecpmCacheValue, _ := cache.GetString(key)
  278. if ecpmCacheValue == "" || ecpmCacheValue != ecpm {
  279. //更新缓存值
  280. cache.SetEx(key, ecpm, md.UserEcpmCacheTime)
  281. //TODO::推入rabbitmq 异步处理
  282. ch.Publish(md2.EggEnergyExchange, md.DealUserEcpmReq{
  283. Uid: user.Id,
  284. Ecpm: ecpm,
  285. }, md2.EggEnergyRoutKeyForDealUserEcpm)
  286. }
  287. }
  288. func ActivityCoinToAlipayRealName(engine *xorm.Engine, uid int64, amount string) (err error) {
  289. amountValue, _ := decimal.NewFromString(amount)
  290. //1、查找 `egg_energy_basic_setting` 基础设置
  291. eggEnergyBasicSettingDb := implement.NewEggEnergyBasicSettingDb(engine)
  292. eggEnergyBasicSetting, err := eggEnergyBasicSettingDb.EggEnergyBasicSettingGetOneByParams(map[string]interface{}{
  293. "key": "is_open",
  294. "value": 1,
  295. })
  296. if err != nil {
  297. return
  298. }
  299. if eggEnergyBasicSetting == nil {
  300. err = errors.New("蛋蛋能量设置未开启!")
  301. return
  302. }
  303. var coin model.VirtualCoin
  304. _, err = engine.Where("id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).Get(&coin)
  305. if err != nil {
  306. return
  307. }
  308. personActivePointsCoinExchangeRatioValue, _ := decimal.NewFromString(coin.ExchangeRatio)
  309. //2、判断个人蛋蛋积分是否足够
  310. var personUserVirtualAmount model.UserVirtualAmount
  311. _, err = engine.Where("coin_id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).And("uid =?", uid).Get(&personUserVirtualAmount)
  312. if err != nil {
  313. fmt.Println("err:::::1111", err)
  314. return
  315. }
  316. personUserVirtualAmountValue, _ := decimal.NewFromString(personUserVirtualAmount.Amount)
  317. needVirtualAmountValue := amountValue.Mul(personActivePointsCoinExchangeRatioValue)
  318. needVirtualAmount, _ := amountValue.Mul(personActivePointsCoinExchangeRatioValue).Float64()
  319. if personUserVirtualAmountValue.LessThan(needVirtualAmountValue) {
  320. err = errors.New("当前蛋蛋积分不足!")
  321. return
  322. }
  323. //3、扣除对应个人蛋蛋积分
  324. session := engine.NewSession()
  325. defer func() {
  326. session.Close()
  327. if err := recover(); err != nil {
  328. _ = zhios_order_relate_logx.Error(err)
  329. }
  330. }()
  331. session.Begin()
  332. //给相应的用户加上"个人"活跃积分
  333. err = rule.DealUserVirtualCoin(session, md.DealUserVirtualCoinReq{
  334. Kind: "sub",
  335. Title: enum.UserVirtualAmountFlowTransferType.String(enum.EggPointCoinToAliPayRealName),
  336. TransferType: int(enum.EggPointCoinToAliPayRealName),
  337. CoinId: eggEnergyBasicSetting.PersonEggPointsCoinId,
  338. Uid: uid,
  339. Amount: needVirtualAmount,
  340. })
  341. if err != nil {
  342. _ = session.Rollback()
  343. fmt.Println("err:::::2222", err)
  344. return err
  345. }
  346. err = session.Commit()
  347. if err != nil {
  348. _ = session.Rollback()
  349. return errors.New("事务提交失败")
  350. }
  351. return
  352. }
  353. func CheckActivityCoinToAlipayRealName(engine *xorm.Engine, uid int64, amount string) (err error, isCan bool) {
  354. amountValue, _ := decimal.NewFromString(amount)
  355. //1、查找 `egg_energy_basic_setting` 基础设置
  356. eggEnergyBasicSettingDb := implement.NewEggEnergyBasicSettingDb(engine)
  357. eggEnergyBasicSetting, err := eggEnergyBasicSettingDb.EggEnergyBasicSettingGetOneByParams(map[string]interface{}{
  358. "key": "is_open",
  359. "value": 1,
  360. })
  361. if err != nil {
  362. return
  363. }
  364. if eggEnergyBasicSetting == nil {
  365. err = errors.New("蛋蛋能量设置未开启!")
  366. return
  367. }
  368. var coin model.VirtualCoin
  369. _, err = engine.Where("id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).Get(&coin)
  370. if err != nil {
  371. return
  372. }
  373. personActivePointsCoinExchangeRatioValue, _ := decimal.NewFromString(coin.ExchangeRatio)
  374. //2、判断个人蛋蛋积分是否足够
  375. var personUserVirtualAmount model.UserVirtualAmount
  376. _, err = engine.Where("coin_id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).And("uid =?", uid).Get(&personUserVirtualAmount)
  377. if err != nil {
  378. fmt.Println("err:::::1111", err)
  379. return
  380. }
  381. personUserVirtualAmountValue, _ := decimal.NewFromString(personUserVirtualAmount.Amount)
  382. needVirtualAmountValue := amountValue.Mul(personActivePointsCoinExchangeRatioValue)
  383. if personUserVirtualAmountValue.GreaterThan(needVirtualAmountValue) {
  384. isCan = true
  385. }
  386. return
  387. }
  388. // CalcUserContinuousDailyActivityDays 计算用户连续活跃天数
  389. func CalcUserContinuousDailyActivityDays(engine *xorm.Engine, uid int, startDate string, endDate string) (err error, days int, isContinuousDailyActivity bool) {
  390. startAt, err := time.ParseInLocation("2006-01-02", startDate, time.Local) //起始时间
  391. endAt, err := time.ParseInLocation("2006-01-02", endDate, time.Local) //起始时间
  392. var list []model.EggEnergyUserActivity
  393. err = engine.Where("date >= ?", startAt.Format("2006-01-02")).
  394. And("date < ?", endAt.Format("2006-01-02")).
  395. And("uid =?", uid).Find(&list)
  396. if err != nil {
  397. fmt.Println("err:::::1111", err)
  398. return
  399. }
  400. days = len(list)
  401. diffDays := egg_system_rules.GetDiffDays(endAt, startAt) //相差天数
  402. if days == diffDays {
  403. isContinuousDailyActivity = true
  404. }
  405. return
  406. }