蛋蛋星球-客户端
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.
 
 
 
 
 

925 regels
28 KiB

  1. package hdl
  2. import (
  3. "applet/app/cfg"
  4. "applet/app/db"
  5. "applet/app/e"
  6. "applet/app/md"
  7. "applet/app/svc"
  8. "applet/app/utils"
  9. "applet/app/utils/cache"
  10. "code.fnuoos.com/EggPlanet/egg_models.git/src/implement"
  11. "code.fnuoos.com/EggPlanet/egg_models.git/src/model"
  12. "code.fnuoos.com/EggPlanet/egg_system_rules.git"
  13. rule2 "code.fnuoos.com/EggPlanet/egg_system_rules.git"
  14. "code.fnuoos.com/EggPlanet/egg_system_rules.git/enum"
  15. md2 "code.fnuoos.com/EggPlanet/egg_system_rules.git/md"
  16. "code.fnuoos.com/EggPlanet/egg_system_rules.git/rule"
  17. "code.fnuoos.com/EggPlanet/egg_system_rules.git/rule/egg_energy"
  18. enum2 "code.fnuoos.com/EggPlanet/egg_system_rules.git/rule/egg_energy/enum"
  19. md3 "code.fnuoos.com/EggPlanet/egg_system_rules.git/rule/egg_energy/md"
  20. svc2 "code.fnuoos.com/EggPlanet/egg_system_rules.git/rule/egg_energy/svc"
  21. es2 "code.fnuoos.com/EggPlanet/egg_system_rules.git/utils/es"
  22. "code.fnuoos.com/go_rely_warehouse/zyos_go_es.git/es"
  23. "context"
  24. "encoding/json"
  25. "errors"
  26. "fmt"
  27. "github.com/gin-gonic/gin"
  28. "github.com/olivere/elastic/v7"
  29. "github.com/shopspring/decimal"
  30. "strconv"
  31. "time"
  32. )
  33. const PointsCenterCalcExchangeRedisKey = "Points_Center_Cache_Key"
  34. // PointsCenterGetBasic
  35. // @Summary 蛋蛋星球-积分中心-上部分基础信息(获取)
  36. // @Tags 积分中心
  37. // @Description 上部分基础信息(获取)
  38. // @Accept json
  39. // @Produce json
  40. // @param Authorization header string true "验证参数Bearer和token空格拼接"
  41. // @Success 200 {object} md.PointsCenterGetBasicResp "具体数据"
  42. // @Failure 400 {object} md.Response "具体错误"
  43. // @Router /api/v1/pointsCenter/basic [GET]
  44. func PointsCenterGetBasic(c *gin.Context) {
  45. val, exists := c.Get("user")
  46. if !exists {
  47. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  48. return
  49. }
  50. user, ok := val.(*model.User)
  51. if !ok {
  52. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  53. return
  54. }
  55. settingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
  56. setting, err := settingDb.EggEnergyBasicSettingGetOne()
  57. if err != nil {
  58. e.OutErr(c, e.ERR_DB_ORM, nil)
  59. return
  60. }
  61. virtualAmountDb := implement.NewUserVirtualAmountDb(db.Db)
  62. // 蛋蛋能量 (个人 + 团队)
  63. eggPersonalEnergy, err := virtualAmountDb.GetUserVirtualWalletBySession(user.Id, setting.PersonEggEnergyCoinId)
  64. if err != nil {
  65. e.OutErr(c, e.ERR_DB_ORM, nil)
  66. return
  67. }
  68. eggTeamEnergy, err := virtualAmountDb.GetUserVirtualWalletBySession(user.Id, setting.TeamEggEnergyCoinId)
  69. if err != nil {
  70. e.OutErr(c, e.ERR_DB_ORM, nil)
  71. return
  72. }
  73. eggEnergy := utils.StrToFloat64(eggPersonalEnergy.Amount) + utils.StrToFloat64(eggTeamEnergy.Amount)
  74. // 蛋蛋能量价值
  75. coreDataDb := implement.NewEggEnergyCoreDataDb(db.Db)
  76. coreData, err := coreDataDb.EggEnergyCoreDataGet()
  77. if err != nil {
  78. e.OutErr(c, e.ERR_DB_ORM, nil)
  79. return
  80. }
  81. eggEnergyAmount := utils.StrToFloat64(coreData.NowPrice) * eggEnergy
  82. // 活跃积分(蛋蛋积分 = 团队 + 个人)
  83. eggPersonalPoint, err := virtualAmountDb.GetUserVirtualWalletBySession(user.Id, setting.PersonEggPointsCoinId)
  84. if err != nil {
  85. e.OutErr(c, e.ERR_DB_ORM, nil)
  86. return
  87. }
  88. eggTeamPoint, err := virtualAmountDb.GetUserVirtualWalletBySession(user.Id, setting.TeamEggPointsCoinId)
  89. if err != nil {
  90. e.OutErr(c, e.ERR_DB_ORM, nil)
  91. return
  92. }
  93. eggPoint := utils.StrToFloat64(eggPersonalPoint.Amount) + utils.StrToFloat64(eggTeamPoint.Amount)
  94. // 蛋蛋积分价值
  95. coinDb := implement.NewVirtualCoinDb(db.Db)
  96. coin, err := coinDb.VirtualCoinGetOneByParams(map[string]interface{}{
  97. "key": "id",
  98. "value": setting.PersonEggPointsCoinId,
  99. })
  100. if err != nil {
  101. e.OutErr(c, e.ERR_DB_ORM, nil)
  102. return
  103. }
  104. var eggPointValue decimal.Decimal
  105. if coin != nil {
  106. ratio, _ := decimal.NewFromString(coin.ExchangeRatio)
  107. eggPointValue = decimal.NewFromFloat(eggPoint).Div(ratio)
  108. }
  109. eggPointValue = decimal.NewFromInt(0)
  110. // 账户余额
  111. walletDb := implement.NewUserWalletDb(db.Db)
  112. wallet, err := walletDb.GetUserVirtualWallet(user.Id)
  113. if err != nil {
  114. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  115. return
  116. }
  117. resp := md.PointsCenterGetBasicResp{
  118. Energy: utils.Float64ToStr(eggEnergy),
  119. EnergyValue: utils.Float64ToStr(eggEnergyAmount),
  120. WalletAmount: wallet.Amount,
  121. EggPoint: utils.Float64ToStr(eggPoint),
  122. EggPointValue: eggPointValue.String(),
  123. }
  124. e.OutSuc(c, resp, nil)
  125. }
  126. // InitialData
  127. // @Summary 蛋蛋星球-积分中心-初始数据(获取)
  128. // @Tags 积分中心
  129. // @Description 初始数据(获取)
  130. // @Accept json
  131. // @Produce json
  132. // @param Authorization header string true "验证参数Bearer和token空格拼接"
  133. // @Success 200 {object} md.InitialDataResp "具体数据"
  134. // @Failure 400 {object} md.Response "具体错误"
  135. // @Router /api/v1/pointsCenter/initialData [GET]
  136. func InitialData(c *gin.Context) {
  137. settingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
  138. setting, err := settingDb.EggEnergyBasicSettingGetOne()
  139. if err != nil {
  140. e.OutErr(c, e.ERR_DB_ORM, nil)
  141. return
  142. }
  143. resp := md.InitialDataResp{
  144. InitialPrice: setting.InitialPrice,
  145. TotalIssuanceAmount: setting.TotalIssuanceAmount,
  146. TotalTechnologyTeam: setting.TotalTechnologyTeam,
  147. TotalAngelInvestor: setting.TotalAngelInvestor,
  148. TotalOperateFund: setting.TotalOperateFund,
  149. TotalEcologicalDevelopment: setting.TotalEcologicalDevelopment,
  150. }
  151. e.OutSuc(c, resp, nil)
  152. }
  153. // DynamicData
  154. // @Summary 蛋蛋星球-积分中心-动态数据(获取)
  155. // @Tags 积分中心
  156. // @Description 动态数据(获取)
  157. // @Accept json
  158. // @Produce json
  159. // @param Authorization header string true "验证参数Bearer和token空格拼接"
  160. // @Success 200 {object} md.DynamicDataResp "具体数据"
  161. // @Failure 400 {object} md.Response "具体错误"
  162. // @Router /api/v1/pointsCenter/dynamicData [GET]
  163. func DynamicData(c *gin.Context) {
  164. settingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
  165. setting, err := settingDb.EggEnergyBasicSettingGetOne()
  166. if err != nil {
  167. e.OutErr(c, e.ERR_DB_ORM, nil)
  168. return
  169. }
  170. // 1.用户持有总量
  171. redisKey1 := PointsCenterCalcExchangeRedisKey + "_1"
  172. redisValue1, err := cache.GetString(redisKey1)
  173. if err != nil {
  174. if err.Error() == "redigo: nil returned" {
  175. amountDb := implement.NewUserVirtualAmountDb(db.Db)
  176. total, err := amountDb.UserVirtualAmountGetSumByCoinKind(setting.PersonEggEnergyCoinId)
  177. if err != nil {
  178. e.OutErr(c, e.ERR_DB_ORM, nil)
  179. return
  180. }
  181. //将获取到的余额值缓存至redis
  182. redisValue1 = utils.Float64ToStr(total)
  183. cache.SetEx(redisKey1, redisValue1, 60)
  184. } else {
  185. e.OutErr(c, e.ERR, err.Error())
  186. return
  187. }
  188. }
  189. // 2.星级分红
  190. redisKey2 := PointsCenterCalcExchangeRedisKey + "_2"
  191. redisValue2, err := cache.GetString(redisKey2)
  192. if err != nil {
  193. if err.Error() == "redigo: nil returned" {
  194. coreDataDb := implement.NewEggEnergyCoreDataDb(db.Db)
  195. coreData, err := coreDataDb.EggEnergyCoreDataGet()
  196. if err != nil {
  197. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  198. return
  199. }
  200. redisValue2 = coreData.StarLevelDividends
  201. cache.SetEx(redisKey2, redisValue2, 60)
  202. } else {
  203. e.OutErr(c, e.ERR, err.Error())
  204. return
  205. }
  206. }
  207. // 3.发展委员会
  208. redisKey3 := PointsCenterCalcExchangeRedisKey + "_3"
  209. redisValue3, err := cache.GetString(redisKey3)
  210. if err != nil {
  211. if err.Error() == "redigo: nil returned" {
  212. coreDataDb := implement.NewEggEnergyCoreDataDb(db.Db)
  213. coreData, err := coreDataDb.EggEnergyCoreDataGet()
  214. if err != nil {
  215. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  216. return
  217. }
  218. redisValue3 = coreData.DevelopmentCommittee
  219. cache.SetEx(redisKey3, redisValue3, 60)
  220. } else {
  221. e.OutErr(c, e.ERR, err.Error())
  222. return
  223. }
  224. }
  225. // 4.公益基金
  226. redisKey4 := PointsCenterCalcExchangeRedisKey + "_4"
  227. redisValue4, err := cache.GetString(redisKey4)
  228. if err != nil {
  229. if err.Error() == "redigo: nil returned" {
  230. coreDataDb := implement.NewEggEnergyCoreDataDb(db.Db)
  231. coreData, err := coreDataDb.EggEnergyCoreDataGet()
  232. if err != nil {
  233. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  234. return
  235. }
  236. redisValue4 = coreData.PublicWelfareAndCharity
  237. cache.SetEx(redisKey4, redisValue4, 60)
  238. } else {
  239. e.OutErr(c, e.ERR, err.Error())
  240. return
  241. }
  242. }
  243. resp := md.DynamicDataResp{
  244. UserTotalHold: redisValue1,
  245. StarLevelDividends: redisValue2,
  246. DevelopmentCommittee: redisValue3,
  247. PublicWelfareAndCharity: redisValue4,
  248. }
  249. e.OutSuc(c, resp, nil)
  250. }
  251. // PointsExchangeGetBasic
  252. // @Summary 蛋蛋星球-积分中心-积分兑换基础信息(获取)
  253. // @Tags 积分中心
  254. // @Description 积分兑换基础信息(获取)
  255. // @Accept json
  256. // @Produce json
  257. // @param Authorization header string true "验证参数Bearer和token空格拼接"
  258. // @Success 200 {object} md.PointsExchangeGetBasicResp "具体数据"
  259. // @Failure 400 {object} md.Response "具体错误"
  260. // @Router /api/v1/pointsCenter/pointsExchangeBasic [GET]
  261. func PointsExchangeGetBasic(c *gin.Context) {
  262. val, exists := c.Get("user")
  263. if !exists {
  264. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  265. return
  266. }
  267. user, ok := val.(*model.User)
  268. if !ok {
  269. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  270. return
  271. }
  272. // 1. 获取蛋蛋能量货币类型
  273. settingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
  274. setting, err := settingDb.EggEnergyBasicSettingGetOne()
  275. if err != nil {
  276. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  277. return
  278. }
  279. coinID := setting.PersonEggEnergyCoinId
  280. // 2. 获取可兑蛋蛋能量
  281. virtualAmountDb := implement.NewUserVirtualAmountDb(db.Db)
  282. eggEnergyAmount, err := virtualAmountDb.GetUserVirtualWalletBySession(user.Id, coinID)
  283. if err != nil {
  284. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  285. return
  286. }
  287. // 3. 可用现金
  288. walletDb := implement.NewUserWalletDb(db.Db)
  289. wallet, err := walletDb.GetUserVirtualWallet(user.Id)
  290. if err != nil {
  291. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  292. return
  293. }
  294. resp := md.PointsExchangeGetBasicResp{
  295. AvailableEnergy: eggEnergyAmount.Amount,
  296. AvailableCash: wallet.Amount,
  297. }
  298. e.OutSuc(c, resp, nil)
  299. }
  300. // GetPriceCurve
  301. // @Summary 蛋蛋星球-积分中心-价格趋势(获取)
  302. // @Tags 积分中心
  303. // @Description 价格趋势(获取)
  304. // @Accept json
  305. // @Produce json
  306. // @param Authorization header string true "验证参数Bearer和token空格拼接"
  307. // @Param kind query string false "1:按天 2:按小时 3:按周"
  308. // @Success 200 {object} md.GetPriceCurveResp "具体数据"
  309. // @Failure 400 {object} md.Response "具体错误"
  310. // @Router /api/v1/pointsCenter/priceCurve [GET]
  311. func GetPriceCurve(c *gin.Context) {
  312. kind := c.DefaultQuery("kind", "1")
  313. now := time.Now()
  314. priceDb := implement.NewEggEnergyPriceDb(db.Db)
  315. m, has, err := priceDb.EggEnergyPriceGetLastOne()
  316. if err != nil {
  317. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  318. return
  319. }
  320. if has == false {
  321. e.OutErr(c, e.ERR_NO_DATA, "未查询到数据")
  322. return
  323. }
  324. var yData []interface{}
  325. var xData []interface{}
  326. switch kind {
  327. case "1":
  328. var date = now.AddDate(0, 0, -6).Format("2006-01-02")
  329. var sql = fmt.Sprintf("SELECT price,date FROM `egg_energy_price` WHERE HOUR = 23 AND DATE >= \"%s\" AND DATE != \"%s\" ORDER BY DATE ASC ", date, now.Format("2006-01-02"))
  330. results, _ := db.Db.QueryString(db.Db, sql)
  331. for _, v := range results {
  332. tmpDate := utils.String2TimeV2(v["date"])
  333. yData = append(yData, v["price"])
  334. xData = append(xData, tmpDate.Format("01-02"))
  335. }
  336. yData = append(yData, m.Price)
  337. tmpDate := utils.String2TimeV2(m.Date)
  338. xData = append(xData, tmpDate.Format("01-02"))
  339. break
  340. case "2":
  341. for i := 29; i >= 1; i-- {
  342. date := now.Add(-time.Hour * 4 * time.Duration(i)).Format("2006-01-02")
  343. hour := now.Add(-time.Hour * 4 * time.Duration(i)).Hour()
  344. var sql = "SELECT price,date,hour FROM `egg_energy_price` WHERE HOUR = %d AND DATE = \"%s\" "
  345. sql = fmt.Sprintf(sql, hour, date)
  346. results, _ := db.Db.QueryString(sql)
  347. if results != nil {
  348. //if results[0]["date"] != now.Format("2006-01-02") {
  349. // continue
  350. //}
  351. yData = append(yData, results[0]["price"])
  352. xData = append(xData, results[0]["hour"]+":00")
  353. }
  354. }
  355. yData = append(yData, m.Price)
  356. xData = append(xData, m.Hour+":00")
  357. break
  358. case "3":
  359. var nums = 6
  360. for i := nums; i >= 1; i-- {
  361. var date = now.AddDate(0, 0, -7*i).Format("2006-01-02")
  362. var sql = "SELECT price,date FROM `egg_energy_price` WHERE HOUR = 23 AND DATE = \"%s\" "
  363. sql = fmt.Sprintf(sql, date)
  364. results, _ := db.Db.QueryString(db.Db, sql)
  365. if results != nil {
  366. tmpDate := utils.String2TimeV2(results[0]["date"])
  367. yData = append(yData, results[0]["price"])
  368. xData = append(xData, tmpDate.Format("01-02"))
  369. }
  370. }
  371. yData = append(yData, m.Price)
  372. tmpDate := utils.String2TimeV2(m.Date)
  373. xData = append(xData, tmpDate.Format("01-02"))
  374. break
  375. }
  376. e.OutSuc(c, md.GetPriceCurveResp{
  377. YData: yData,
  378. XData: xData,
  379. }, nil)
  380. return
  381. }
  382. // ExchangeEnergy
  383. // @Summary 蛋蛋星球-积分中心-能量兑换
  384. // @Tags 积分中心
  385. // @Description 能量兑换
  386. // @Accept json
  387. // @Produce json
  388. // @param Authorization header string true "验证参数Bearer和token空格拼接"
  389. // @Param req body md.ExchangeEnergyReq true "需要兑换的能量值"
  390. // @Success 200 {string} "success"
  391. // @Failure 400 {object} md.Response "具体错误"
  392. // @Router /api/v1/pointsCenter/exchangeEnergy [POST]
  393. func ExchangeEnergy(c *gin.Context) {
  394. val, exists := c.Get("user")
  395. if !exists {
  396. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  397. return
  398. }
  399. user, ok := val.(*model.User)
  400. if !ok {
  401. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  402. return
  403. }
  404. var req *md.ExchangeEnergyReq
  405. if err1 := c.ShouldBindJSON(&req); err1 != nil {
  406. e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
  407. return
  408. }
  409. // 1. 获取蛋蛋能量货币类型
  410. settingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
  411. setting, err := settingDb.EggEnergyBasicSettingGetOne()
  412. if err != nil {
  413. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  414. return
  415. }
  416. coinID := setting.PersonEggEnergyCoinId
  417. session := db.Db.NewSession()
  418. defer session.Close()
  419. // 2. 计算蛋蛋能量兑换的金额
  420. egg_system_rules.Init(cfg.RedisAddr)
  421. eggEnergyCoreData, cb, err1 := svc2.GetEggEnergyCoreData(db.Db)
  422. if err1 != nil {
  423. fmt.Println("EggEnergyAutoRecordPrices_ERR:::::", err1.Error())
  424. return
  425. }
  426. if cb != nil {
  427. defer cb() // 释放锁
  428. }
  429. // 3. 获取用户蛋蛋能量余额
  430. eggEnergyAmount, err := rule.GetUserCoinAmount(session, coinID, user.Id)
  431. if err != nil {
  432. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  433. return
  434. }
  435. // 4. 判断蛋蛋能量是否足够兑换
  436. if utils.StrToFloat64(eggEnergyAmount) < utils.StrToFloat64(req.EnergyAmount) {
  437. e.OutErr(c, e.ERR_BALANCE_NOT_ENOUGH, nil)
  438. return
  439. }
  440. // 5. 调用降价公式
  441. err, calcPriceReductionFormula := egg_energy.CalcPriceReductionFormula(req.EnergyAmount, eggEnergyCoreData, utils.IntToStr(user.Level), *setting)
  442. if err != nil {
  443. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  444. return
  445. }
  446. // 6. 更改动态数据
  447. err = egg_energy.DealAvailableEggEnergyCoin(session, int(enum2.EggEnergyExchangeAccountBalance), eggEnergyCoreData, md3.DealAvailableEggEnergyCoinReq{
  448. Amount: req.EnergyAmount,
  449. AmountFee: calcPriceReductionFormula.AmountFee,
  450. BeforePrice: calcPriceReductionFormula.BeforePrice,
  451. AfterPrice: calcPriceReductionFormula.AfterPrice,
  452. BeforePlanetTotalValue: calcPriceReductionFormula.BeforePlanetTotalValue,
  453. AfterPlanetTotalValue: calcPriceReductionFormula.AfterPlanetTotalValue,
  454. BeforeEnergyTotalNums: calcPriceReductionFormula.BeforeEnergyTotalNums,
  455. AfterEnergyTotalNums: calcPriceReductionFormula.AfterEnergyTotalNums,
  456. })
  457. if err != nil {
  458. fmt.Println("ActivityCoinAutoExchangeEggPersonEnergy:::::err111:::", err)
  459. _ = session.Rollback()
  460. return
  461. }
  462. // 7. 扣除蛋蛋能量
  463. dealUserVirtualCoinReq := md2.DealUserVirtualCoinReq{
  464. Kind: "sub",
  465. Title: enum.EggEnergyToExchangeToAmount.String(),
  466. TransferType: int(enum.EggEnergyToExchangeToAmount),
  467. CoinId: coinID,
  468. Uid: user.Id,
  469. Amount: utils.StrToFloat64(req.EnergyAmount),
  470. }
  471. err = rule.DealUserVirtualCoin(session, dealUserVirtualCoinReq)
  472. if err != nil {
  473. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  474. session.Rollback()
  475. return
  476. }
  477. // 8. 增加账户余额
  478. dealUserWalletReq := md2.DealUserWalletReq{
  479. Direction: "add",
  480. Kind: int(enum.EggEnergyExchangeAccountBalance),
  481. Title: enum.EggEnergyExchangeAccountBalance.String(),
  482. Uid: user.Id,
  483. Amount: utils.StrToFloat64(calcPriceReductionFormula.GetEggEnergyAmount),
  484. }
  485. err = rule.DealUserWallet(session, dealUserWalletReq)
  486. if err != nil {
  487. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  488. session.Rollback()
  489. return
  490. }
  491. err = session.Commit()
  492. if err != nil {
  493. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  494. return
  495. }
  496. e.OutSuc(c, "success", nil)
  497. }
  498. // GetContributionValue
  499. // @Summary 蛋蛋星球-积分中心-贡献值(获取)
  500. // @Tags 积分中心
  501. // @Description 贡献值(获取)
  502. // @Accept json
  503. // @Produce json
  504. // @param Authorization header string true "验证参数Bearer和token空格拼接"
  505. // @Success 200 {object} md.GetContributionValueResp "具体数据"
  506. // @Failure 400 {object} md.Response "具体错误"
  507. // @Router /api/v1/pointsCenter/contributionValue [GET]
  508. func GetContributionValue(c *gin.Context) {
  509. val, exists := c.Get("user")
  510. if !exists {
  511. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  512. return
  513. }
  514. user, ok := val.(*model.User)
  515. if !ok {
  516. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  517. return
  518. }
  519. settingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
  520. setting, err := settingDb.EggEnergyBasicSettingGetOne()
  521. if err != nil {
  522. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  523. return
  524. }
  525. coinID := setting.ContributionCoinId
  526. virtualAmountDb := implement.NewUserVirtualAmountDb(db.Db)
  527. virtualAmount, err := virtualAmountDb.GetUserVirtualWalletBySession(user.Id, coinID)
  528. if err != nil {
  529. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  530. return
  531. }
  532. var contributionValue string
  533. if virtualAmount != nil {
  534. contributionValueDecimal, err := decimal.NewFromString(virtualAmount.Amount)
  535. if err != nil {
  536. e.OutErr(c, e.ERR_UNMARSHAL, err.Error())
  537. return
  538. }
  539. contributionValue = contributionValueDecimal.StringFixed(0)
  540. }
  541. coinDb := implement.NewVirtualCoinDb(db.Db)
  542. coin, err := coinDb.VirtualCoinGetOneByParams(map[string]interface{}{
  543. "key": "id",
  544. "value": coinID,
  545. })
  546. if err != nil {
  547. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  548. return
  549. }
  550. var ratio string
  551. if coin != nil {
  552. ratio = coin.ExchangeRatio
  553. }
  554. resp := md.GetContributionValueResp{
  555. ContributionValue: contributionValue,
  556. Ratio: ratio,
  557. }
  558. e.OutSuc(c, resp, nil)
  559. }
  560. // GetContributionValueFlow
  561. // @Summary 蛋蛋星球-积分中心-贡献值明细(获取)
  562. // @Tags 积分中心
  563. // @Description 贡献值明细(获取)
  564. // @Accept json
  565. // @Produce json
  566. // @param Authorization header string true "验证参数Bearer和token空格拼接"
  567. // @Param limit query string true "每页大小"
  568. // @Param page query string true "页数"
  569. // @Success 200 {object} md.GetContributionValueFlowResp "具体数据"
  570. // @Failure 400 {object} md.Response "具体错误"
  571. // @Router /api/v1/pointsCenter/contributionValueFlow [GET]
  572. func GetContributionValueFlow(c *gin.Context) {
  573. page := c.DefaultQuery("page", "1")
  574. limit := c.DefaultQuery("limit", "10")
  575. val, exists := c.Get("user")
  576. if !exists {
  577. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  578. return
  579. }
  580. user, ok := val.(*model.User)
  581. if !ok {
  582. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  583. return
  584. }
  585. settingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
  586. setting, err := settingDb.EggEnergyBasicSettingGetOne()
  587. if err != nil {
  588. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  589. return
  590. }
  591. coinID := setting.ContributionCoinId
  592. flowDb := implement.NewUserVirtualCoinFlowDb(db.Db)
  593. flows, total, err := flowDb.UserVirtualCoinFlowFindByCoinAndUser(utils.StrToInt(page), utils.StrToInt(limit), coinID, user.Id, "", "", 0, false, 0)
  594. if err != nil {
  595. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  596. return
  597. }
  598. list := make([]md.ContributionValueFlowNode, len(flows))
  599. for i, flow := range flows {
  600. list[i].Title = flow.Title
  601. amountDecimal, err1 := decimal.NewFromString(flow.Amount)
  602. if err1 != nil {
  603. e.OutErr(c, e.ERR_UNMARSHAL, err1.Error())
  604. return
  605. }
  606. list[i].Amount = amountDecimal.StringFixed(0)
  607. list[i].Direction = utils.IntToStr(flow.Direction)
  608. list[i].CreateAt = flow.CreateAt
  609. }
  610. resp := md.GetContributionValueFlowResp{
  611. List: list,
  612. Paginate: md.Paginate{
  613. Limit: utils.StrToInt(limit),
  614. Page: utils.StrToInt(page),
  615. Total: total,
  616. },
  617. }
  618. e.OutSuc(c, resp, nil)
  619. }
  620. func GetPointMap(c *gin.Context) {
  621. val, exists := c.Get("user")
  622. if !exists {
  623. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  624. return
  625. }
  626. user, ok := val.(*model.User)
  627. if !ok {
  628. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  629. return
  630. }
  631. now := time.Now()
  632. // 1. 获取当期有效蛋蛋分
  633. nowIndex := md2.EggEnergyUserEggScoreEsAlias + "_" + es2.GetLatestEffectiveIndexFromAlias(now)
  634. boolQuery := elastic.NewBoolQuery()
  635. boolQuery.Filter(elastic.NewTermQuery("uid", user.Id))
  636. searchResult, err := es.EsClient.Search().
  637. Index(nowIndex).
  638. Query(boolQuery).
  639. Pretty(true).
  640. Do(context.Background())
  641. if searchResult == nil {
  642. e.OutErr(c, e.ERR_DB_ORM, errors.New("failed to get current egg score"))
  643. return
  644. }
  645. var results []md.UserEggFlowReqRespList
  646. if searchResult.Hits.TotalHits.Value != 0 {
  647. // 解析结果
  648. for _, hit := range searchResult.Hits.Hits {
  649. var doc md.UserEggFlowReqRespList
  650. err = json.Unmarshal(hit.Source, &doc)
  651. if err != nil {
  652. e.OutErr(c, e.ERR_UNMARSHAL, err.Error())
  653. return
  654. }
  655. results = append(results, doc)
  656. }
  657. }
  658. // nowScore := utils.Float64ToStr(results[0].ScoreValue)
  659. // todo 计算分数权重
  660. }
  661. // GetEggPointRecord
  662. // @Summary 蛋蛋星球-积分中心-蛋蛋分明细(获取)
  663. // @Tags 积分中心
  664. // @Description 蛋蛋分明细(获取)
  665. // @Accept json
  666. // @Produce json
  667. // @param Authorization header string true "验证参数Bearer和token空格拼接"
  668. // @Param limit query string true "每页大小"
  669. // @Param page query string true "页数"
  670. // @Success 200 {object} md.GetEggPointRecordResp "具体数据"
  671. // @Failure 400 {object} md.Response "具体错误"
  672. // @Router /api/v1/pointsCenter/record [GET]
  673. func GetEggPointRecord(c *gin.Context) {
  674. pageStr := c.DefaultQuery("page", "1")
  675. limitStr := c.DefaultQuery("limit", "5")
  676. page := utils.StrToInt(pageStr)
  677. limit := utils.StrToInt(limitStr)
  678. val, exists := c.Get("user")
  679. if !exists {
  680. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  681. return
  682. }
  683. user, ok := val.(*model.User)
  684. if !ok {
  685. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  686. return
  687. }
  688. now := time.Now()
  689. list, nowScore, indexNum, err := svc.GetEggPointRecordBase(now, user.Id, page, limit)
  690. if err != nil {
  691. resp := md.GetEggPointRecordResp{
  692. NowScore: "60",
  693. List: nil,
  694. Paginate: md.Paginate{
  695. Limit: limit,
  696. Page: page,
  697. Total: 0,
  698. },
  699. }
  700. e.OutSuc(c, resp, nil)
  701. return
  702. }
  703. resp := md.GetEggPointRecordResp{
  704. NowScore: nowScore,
  705. List: list,
  706. Paginate: md.Paginate{
  707. Limit: limit,
  708. Page: page,
  709. Total: int64(indexNum),
  710. },
  711. }
  712. e.OutSuc(c, resp, nil)
  713. }
  714. // GetEggEnergyFlow
  715. // @Summary 蛋蛋星球-积分中心-收支明细(获取)
  716. // @Tags 积分中心
  717. // @Description 收支明细(获取)
  718. // @Accept json
  719. // @Produce json
  720. // @param Authorization header string true "验证参数Bearer和token空格拼接"
  721. // @Param limit query string true "每页大小"
  722. // @Param page query string true "页数"
  723. // @Param startAt query string false "开始时间"
  724. // @Param endAt query string false "结束时间"
  725. // @Param direction query string false "流水方向(1.收入 2.支出 0.全部)"
  726. // @Success 200 {object} md.GetEggEnergyFlowResp "具体数据"
  727. // @Failure 400 {object} md.Response "具体错误"
  728. // @Router /api/v1/pointsCenter/energyFlow [GET]
  729. func GetEggEnergyFlow(c *gin.Context) {
  730. pageStr := c.DefaultQuery("page", "1")
  731. limitStr := c.DefaultQuery("limit", "10")
  732. startAt := c.Query("startAt")
  733. endAt := c.Query("endAt")
  734. directionStr := c.Query("direction")
  735. val, exists := c.Get("user")
  736. if !exists {
  737. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  738. return
  739. }
  740. user, ok := val.(*model.User)
  741. if !ok {
  742. e.OutErr(c, e.ERR_USER_CHECK_ERR, nil)
  743. return
  744. }
  745. coinDb := implement.NewVirtualCoinDb(db.Db)
  746. coins, err := coinDb.VirtualCoinFindAll()
  747. if err != nil {
  748. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  749. return
  750. }
  751. if coins == nil {
  752. e.OutErr(c, e.ERR_NO_DATA, errors.New("未初始化货币"))
  753. return
  754. }
  755. coinsList := make([]map[string]interface{}, len(coins))
  756. coinsMap := map[int]string{}
  757. for i, coin := range coins {
  758. coinsList[i] = map[string]interface{}{
  759. "coinID": coin.Id,
  760. "name": coin.Name,
  761. }
  762. coinsMap[coin.Id] = coin.Name
  763. }
  764. direction := 0
  765. switch directionStr {
  766. case "1":
  767. direction = 1
  768. case "2":
  769. direction = 2
  770. }
  771. page := utils.StrToInt(pageStr)
  772. limit := utils.StrToInt(limitStr)
  773. flowDb := implement.NewUserVirtualCoinFlowDb(db.Db)
  774. flows, total, err := flowDb.UserVirtualCoinFlowFindByCoinAndUser(page, limit, 0, user.Id, startAt, endAt, direction, false, 0)
  775. if err != nil {
  776. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  777. return
  778. }
  779. list := make([]md.EggEnergyFlowNode, len(flows))
  780. for i, flow := range flows {
  781. list[i].Title = flow.Title
  782. list[i].Amount = flow.Amount
  783. list[i].Direction = flow.Direction
  784. list[i].CreateAt = flow.CreateAt
  785. list[i].Id = flow.Id
  786. list[i].BeforeAmount = flow.BeforeAmount
  787. list[i].AfterAmount = flow.AfterAmount
  788. list[i].CoinName = coinsMap[flow.CoinId]
  789. list[i].SysFee = flow.SysFee
  790. list[i].TransferType = enum.UserVirtualAmountFlowTransferType(flow.TransferType).String()
  791. }
  792. resp := md.GetEggEnergyFlowResp{
  793. List: list,
  794. Paginate: md.Paginate{
  795. Limit: limit,
  796. Page: page,
  797. Total: total,
  798. },
  799. }
  800. e.OutSuc(c, resp, nil)
  801. }
  802. // PointsCenterCalcExchange
  803. // @Summary 蛋蛋星球-积分中心-预估积分兑换
  804. // @Tags 积分中心
  805. // @Description 蛋蛋分明细(获取)
  806. // @Accept json
  807. // @Produce json
  808. // @param Authorization header string true "验证参数Bearer和token空格拼接"
  809. // @Param amount query string true "需要兑换能量值"
  810. // @Success 200 {object} md.PointsCenterCalcExchangeResp "具体数据"
  811. // @Failure 400 {object} md.Response "具体错误"
  812. // @Router /api/v1/pointsCenter/calcExchange [GET]
  813. func PointsCenterCalcExchange(c *gin.Context) {
  814. amount := c.DefaultQuery("amount", "")
  815. user := svc.GetUser(c)
  816. engine := db.Db
  817. rule2.Init(cfg.RedisAddr)
  818. eggEnergyCoreData, cb, err1 := svc2.GetEggEnergyCoreData(engine)
  819. if err1 != nil {
  820. e.OutErr(c, e.ERR_DB_ORM, err1.Error())
  821. return
  822. }
  823. if cb != nil {
  824. defer cb() // 释放锁
  825. }
  826. eggEnergyBasicSettingDb := implement.NewEggEnergyBasicSettingDb(engine)
  827. eggEnergyBasicSetting, err1 := eggEnergyBasicSettingDb.EggEnergyBasicSettingGetOneByParams(map[string]interface{}{
  828. "key": "is_open",
  829. "value": 1,
  830. })
  831. if err1 != nil {
  832. e.OutErr(c, e.ERR_DB_ORM, err1.Error())
  833. return
  834. }
  835. if eggEnergyBasicSetting == nil {
  836. err1 = errors.New("蛋蛋能量设置未开启!")
  837. e.OutErr(c, e.ERR, err1.Error())
  838. return
  839. }
  840. //能量兑换余额
  841. err, exchangeResp := egg_energy.CalcPriceReductionFormula(amount, eggEnergyCoreData, strconv.Itoa(user.Level), *eggEnergyBasicSetting)
  842. if err != nil {
  843. e.OutErr(c, e.ERR, err.Error())
  844. return
  845. }
  846. resp := md.PointsCenterCalcExchangeResp{
  847. Value: exchangeResp.GetEggEnergyAmount,
  848. }
  849. e.OutSuc(c, resp, nil)
  850. return
  851. }