蛋蛋星球-制度模式
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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