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

496 lines
18 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. var fatherSign model.EggSignIn
  196. if directPushRewardSetting.MemberSelfIsOpenGetTeamReward == "1" {
  197. fmt.Println("user:::::::::::::", user)
  198. has, err44 := engine.Where("uid =?", user.ParentUid).And("end_time >=?", time.Now().Format("2006-01-02 15:04:05")).Get(&fatherSign)
  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. ch.Publish(md2.EggEnergyExchange, md2.EggEnergyTeamAssistanceReq{
  258. AssistanceUid: uid,
  259. Uid: vv.Uid,
  260. AssistanceValue: vv.RewardValue,
  261. SignStart: fatherSign.StartTime,
  262. SignEnd: fatherSign.EndTime,
  263. }, md2.EggEnergyTeamAssistance)
  264. }
  265. }
  266. err = session.Commit()
  267. if err != nil {
  268. _ = session.Rollback()
  269. return rewardValue, errors.New("事务提交失败")
  270. }
  271. }
  272. //增加 egg_user_watch_records 记录
  273. eggEnergyUserWatchRecordsDb := implement.NewEggEnergyUserWatchRecordsDb(engine)
  274. eggEnergyUserWatchRecords, err1 := eggEnergyUserWatchRecordsDb.EggEnergyUserWatchRecordsGetOneByParams(map[string]interface{}{
  275. "key": "uid",
  276. "value": uid,
  277. })
  278. if err1 != nil {
  279. return rewardValue, err1
  280. }
  281. if eggEnergyUserWatchRecords == nil {
  282. residueWatchAdNum := egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum) - 1
  283. if residueWatchAdNum < 0 {
  284. residueWatchAdNum = egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum)
  285. }
  286. eggEnergyUserWatchRecords = &model.EggEnergyUserWatchRecords{
  287. Uid: uid,
  288. NextWatchAdDate: now.Add(time.Hour * time.Duration(egg_system_rules.StrToInt(videoRewardSystem.EachRoundHour))),
  289. ResidueWatchAdNum: egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum) - 1,
  290. CreateAt: now.Format("2006-01-02 15:04:05"),
  291. UpdateAt: now.Format("2006-01-02 15:04:05"),
  292. }
  293. _, err2 := eggEnergyUserWatchRecordsDb.EggEnergyUserWatchRecordsInsert(eggEnergyUserWatchRecords)
  294. if err2 != nil {
  295. return rewardValue, err2
  296. }
  297. } else {
  298. residueWatchAdNum := eggEnergyUserWatchRecords.ResidueWatchAdNum - 1
  299. nextWatchAdDate := eggEnergyUserWatchRecords.NextWatchAdDate
  300. if residueWatchAdNum == 0 { //最后一条广告
  301. residueWatchAdNum = egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum)
  302. }
  303. if residueWatchAdNum == egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum)-1 { //第一条广告
  304. nextWatchAdDate = now.Add(time.Hour * time.Duration(egg_system_rules.StrToInt(videoRewardSystem.EachRoundHour)))
  305. }
  306. eggEnergyUserWatchRecords.ResidueWatchAdNum = residueWatchAdNum
  307. eggEnergyUserWatchRecords.NextWatchAdDate = nextWatchAdDate
  308. _, err2 := eggEnergyUserWatchRecordsDb.EggEnergyUserWatchRecordsUpdate(eggEnergyUserWatchRecords.Id, eggEnergyUserWatchRecords, "residue_watch_ad_num", "next_watch_ad_date")
  309. if err2 != nil {
  310. return rewardValue, err2
  311. }
  312. }
  313. var watchAdDate string
  314. if eggEnergyUserWatchRecords.ResidueWatchAdNum == egg_system_rules.StrToInt(videoRewardSystem.RewardTotalNum) {
  315. if eggEnergyUserWatchRecords.NextWatchAdDate.Before(time.Now()) {
  316. watchAdDate = ""
  317. } else {
  318. watchAdDate = eggEnergyUserWatchRecords.NextWatchAdDate.Format("2006-01-02 15:04:05")
  319. }
  320. } else {
  321. watchAdDate = time.Now().Add(time.Duration(egg_system_rules.StrToInt64(videoRewardSystem.IntervalMinutes)) * time.Second).Format("2006-01-02 15:04:05")
  322. }
  323. cache.SetEx(redisKey, watchAdDate, 60*60*24) //TODO::默认缓存1小时
  324. return
  325. }
  326. func dealEcpm(user model.User, ecpm string, ch *rabbit.Channel) {
  327. //查找缓存中的ecpm值和当前的ecpm是否一致
  328. key := fmt.Sprintf(md.UserEcpmCacheKey, user.Id)
  329. ecpmCacheValue, _ := cache.GetString(key)
  330. if ecpmCacheValue == "" || ecpmCacheValue != ecpm {
  331. //更新缓存值
  332. cache.SetEx(key, ecpm, md.UserEcpmCacheTime)
  333. //TODO::推入rabbitmq 异步处理
  334. ch.Publish(md2.EggEnergyExchange, md.DealUserEcpmReq{
  335. Uid: user.Id,
  336. Ecpm: ecpm,
  337. }, md2.EggEnergyRoutKeyForDealUserEcpm)
  338. }
  339. }
  340. func ActivityCoinToAlipayRealName(engine *xorm.Engine, uid int64, amount string) (err error) {
  341. amountValue, _ := decimal.NewFromString(amount)
  342. //1、查找 `egg_energy_basic_setting` 基础设置
  343. eggEnergyBasicSettingDb := implement.NewEggEnergyBasicSettingDb(engine)
  344. eggEnergyBasicSetting, err := eggEnergyBasicSettingDb.EggEnergyBasicSettingGetOneByParams(map[string]interface{}{
  345. "key": "is_open",
  346. "value": 1,
  347. })
  348. if err != nil {
  349. return
  350. }
  351. if eggEnergyBasicSetting == nil {
  352. err = errors.New("蛋蛋能量设置未开启!")
  353. return
  354. }
  355. var coin model.VirtualCoin
  356. _, err = engine.Where("id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).Get(&coin)
  357. if err != nil {
  358. return
  359. }
  360. personActivePointsCoinExchangeRatioValue, _ := decimal.NewFromString(coin.ExchangeRatio)
  361. //2、判断个人蛋蛋积分是否足够
  362. var personUserVirtualAmount model.UserVirtualAmount
  363. _, err = engine.Where("coin_id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).And("uid =?", uid).Get(&personUserVirtualAmount)
  364. if err != nil {
  365. fmt.Println("err:::::1111", err)
  366. return
  367. }
  368. personUserVirtualAmountValue, _ := decimal.NewFromString(personUserVirtualAmount.Amount)
  369. needVirtualAmountValue := amountValue.Mul(personActivePointsCoinExchangeRatioValue)
  370. needVirtualAmount, _ := amountValue.Mul(personActivePointsCoinExchangeRatioValue).Float64()
  371. if personUserVirtualAmountValue.LessThan(needVirtualAmountValue) {
  372. err = errors.New("当前蛋蛋积分不足!")
  373. return
  374. }
  375. //3、扣除对应个人蛋蛋积分
  376. session := engine.NewSession()
  377. defer func() {
  378. session.Close()
  379. if err := recover(); err != nil {
  380. _ = zhios_order_relate_logx.Error(err)
  381. }
  382. }()
  383. session.Begin()
  384. //给相应的用户加上"个人"活跃积分
  385. err = rule.DealUserVirtualCoin(session, md.DealUserVirtualCoinReq{
  386. Kind: "sub",
  387. Title: enum.UserVirtualAmountFlowTransferType.String(enum.EggPointCoinToAliPayRealName),
  388. TransferType: int(enum.EggPointCoinToAliPayRealName),
  389. CoinId: eggEnergyBasicSetting.PersonEggPointsCoinId,
  390. Uid: uid,
  391. Amount: needVirtualAmount,
  392. })
  393. if err != nil {
  394. _ = session.Rollback()
  395. fmt.Println("err:::::2222", err)
  396. return err
  397. }
  398. err = session.Commit()
  399. if err != nil {
  400. _ = session.Rollback()
  401. return errors.New("事务提交失败")
  402. }
  403. return
  404. }
  405. func CheckActivityCoinToAlipayRealName(engine *xorm.Engine, uid int64, amount string) (err error, isCan bool) {
  406. amountValue, _ := decimal.NewFromString(amount)
  407. //1、查找 `egg_energy_basic_setting` 基础设置
  408. eggEnergyBasicSettingDb := implement.NewEggEnergyBasicSettingDb(engine)
  409. eggEnergyBasicSetting, err := eggEnergyBasicSettingDb.EggEnergyBasicSettingGetOneByParams(map[string]interface{}{
  410. "key": "is_open",
  411. "value": 1,
  412. })
  413. if err != nil {
  414. return
  415. }
  416. if eggEnergyBasicSetting == nil {
  417. err = errors.New("蛋蛋能量设置未开启!")
  418. return
  419. }
  420. var coin model.VirtualCoin
  421. _, err = engine.Where("id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).Get(&coin)
  422. if err != nil {
  423. return
  424. }
  425. personActivePointsCoinExchangeRatioValue, _ := decimal.NewFromString(coin.ExchangeRatio)
  426. //2、判断个人蛋蛋积分是否足够
  427. var personUserVirtualAmount model.UserVirtualAmount
  428. _, err = engine.Where("coin_id = ?", eggEnergyBasicSetting.PersonEggPointsCoinId).And("uid =?", uid).Get(&personUserVirtualAmount)
  429. if err != nil {
  430. fmt.Println("err:::::1111", err)
  431. return
  432. }
  433. personUserVirtualAmountValue, _ := decimal.NewFromString(personUserVirtualAmount.Amount)
  434. needVirtualAmountValue := amountValue.Mul(personActivePointsCoinExchangeRatioValue)
  435. if personUserVirtualAmountValue.GreaterThan(needVirtualAmountValue) {
  436. isCan = true
  437. }
  438. return
  439. }
  440. // CalcUserContinuousDailyActivityDays 计算用户连续活跃天数
  441. func CalcUserContinuousDailyActivityDays(engine *xorm.Engine, uid int, startDate string, endDate string) (err error, days int, isContinuousDailyActivity bool) {
  442. startAt, err := time.ParseInLocation("2006-01-02", startDate, time.Local) //起始时间
  443. endAt, err := time.ParseInLocation("2006-01-02", endDate, time.Local) //起始时间
  444. var list []model.EggEnergyUserActivity
  445. err = engine.Where("date >= ?", startAt.Format("2006-01-02")).
  446. And("date < ?", endAt.Format("2006-01-02")).
  447. And("uid =?", uid).Find(&list)
  448. if err != nil {
  449. fmt.Println("err:::::1111", err)
  450. return
  451. }
  452. days = len(list)
  453. diffDays := egg_system_rules.GetDiffDays(endAt, startAt) //相差天数
  454. if days == diffDays {
  455. isContinuousDailyActivity = true
  456. }
  457. return
  458. }