get_charts_logic.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package dashboard
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/suyuan32/simple-admin-common/msg/errormsg"
  6. "strconv"
  7. "time"
  8. "wechat-api/ent/custom_types"
  9. "wechat-api/ent/label"
  10. "wechat-api/ent/predicate"
  11. "wechat-api/ent/usagestatisticday"
  12. "wechat-api/ent/usagestatistichour"
  13. "wechat-api/internal/svc"
  14. "wechat-api/internal/types"
  15. "github.com/zeromicro/go-zero/core/logx"
  16. )
  17. type GetChartsLogic struct {
  18. logx.Logger
  19. ctx context.Context
  20. svcCtx *svc.ServiceContext
  21. }
  22. func NewGetChartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetChartsLogic {
  23. return &GetChartsLogic{
  24. Logger: logx.WithContext(ctx),
  25. ctx: ctx,
  26. svcCtx: svcCtx}
  27. }
  28. type SumUint struct {
  29. Addtime uint64 `json:"addtime"`
  30. Value uint64 `json:"value"`
  31. }
  32. type SumInt struct {
  33. Addtime uint64 `json:"addtime"`
  34. Value int64 `json:"value"`
  35. }
  36. func (l *GetChartsLogic) GetCharts(req *types.ChartsReq) (resp *types.ChartsResp, err error) {
  37. // 获取组织id
  38. var organizationId uint64 = 0
  39. isAdmin := l.ctx.Value("isAdmin").(bool)
  40. if isAdmin && req.OrganizationId != nil && *req.OrganizationId != 0 {
  41. if req.OrganizationId != nil && *req.OrganizationId != 0 {
  42. organizationId = *req.OrganizationId
  43. }
  44. } else {
  45. organizationId = l.ctx.Value("organizationId").(uint64)
  46. }
  47. // 解析起始和截止时间
  48. layouts := []string{
  49. "2006-01", // 对应 "2024-01"
  50. "2006-01-02", // 对应 "2024-01-01"
  51. }
  52. var layoutsType int
  53. var startTime time.Time
  54. for i, layout := range layouts {
  55. startTime, err = time.Parse(layout, *req.StartDate)
  56. layoutsType = i
  57. if err == nil {
  58. break
  59. }
  60. }
  61. if err != nil {
  62. fmt.Println("解析开始时间失败:", err)
  63. return
  64. }
  65. var endTime time.Time
  66. for _, layout := range layouts {
  67. endTime, err = time.Parse(layout, *req.EndDate)
  68. if err == nil {
  69. break
  70. }
  71. }
  72. if err != nil {
  73. fmt.Println("解析结束时间失败:", err)
  74. return
  75. }
  76. // 判断截止日期是否包含当前日
  77. var isCurrentDay bool
  78. now := time.Now()
  79. if layoutsType == 0 {
  80. isCurrentDay = endTime.Year() == now.Year() && endTime.Month() == now.Month()
  81. } else {
  82. isCurrentDay = endTime.Year() == now.Year() && endTime.Month() == now.Month() && endTime.Day() == now.Day()
  83. }
  84. // 定义变量
  85. aiResponse := types.ChartsUint{}
  86. sopRun := types.ChartsUint{}
  87. totalFriend := types.ChartsUint{}
  88. totalGroup := types.ChartsUint{}
  89. accountBalance := types.ChartsUint{}
  90. consumeToken := types.ChartsUint{}
  91. activeUser := types.ChartsUint{}
  92. newUser := types.ChartsInt{}
  93. var labelDists []custom_types.LabelDist
  94. if layoutsType == 1 && *req.StartDate == *req.EndDate {
  95. startAddTimeString := startTime.Format("2006010200")
  96. startAddTime, err := strconv.ParseUint(startAddTimeString, 10, 64)
  97. if err != nil {
  98. fmt.Println("转换开始时间失败:", err)
  99. return nil, err
  100. }
  101. nextDayMidnight := time.Date(startTime.Year(), startTime.Month(), startTime.Day()+1, 0, 0, 0, 0, startTime.Location())
  102. nextDayMidnightString := nextDayMidnight.Format("2006010200")
  103. nextDayAddTime, err := strconv.ParseUint(nextDayMidnightString, 10, 64)
  104. if err != nil {
  105. fmt.Println("转换次日0点时间失败:", err)
  106. return nil, err
  107. }
  108. var predicates []predicate.UsageStatisticHour
  109. predicates = append(predicates, usagestatistichour.OrganizationID(organizationId))
  110. predicates = append(predicates, usagestatistichour.BotID(""))
  111. predicates = append(predicates, usagestatistichour.AddtimeGTE(startAddTime))
  112. predicates = append(predicates, usagestatistichour.AddtimeLTE(nextDayAddTime))
  113. usageStatisticHour, err := l.svcCtx.DB.UsageStatisticHour.Query().Where(predicates...).All(l.ctx)
  114. if err != nil {
  115. return nil, err
  116. }
  117. for _, hourData := range usageStatisticHour {
  118. addtimeLastTwoDigits := hourData.Addtime % 100
  119. aiResponse.Count += hourData.AiResponse
  120. aiResponse.Val = append(aiResponse.Val, hourData.AiResponse)
  121. aiResponse.Label = append(aiResponse.Label, fmt.Sprintf("%02d点", addtimeLastTwoDigits))
  122. sopRun.Count += hourData.SopRun
  123. sopRun.Val = append(sopRun.Val, hourData.SopRun)
  124. sopRun.Label = append(sopRun.Label, fmt.Sprintf("%02d点", addtimeLastTwoDigits))
  125. totalFriend.Count = hourData.TotalFriend
  126. totalFriend.Val = append(totalFriend.Val, hourData.TotalFriend)
  127. totalFriend.Label = append(totalFriend.Label, fmt.Sprintf("%02d点", addtimeLastTwoDigits))
  128. totalGroup.Count = hourData.TotalGroup
  129. totalGroup.Val = append(totalGroup.Val, hourData.TotalGroup)
  130. totalGroup.Label = append(totalGroup.Label, fmt.Sprintf("%02d点", addtimeLastTwoDigits))
  131. consumeToken.Count += hourData.ConsumeToken
  132. consumeToken.Val = append(consumeToken.Val, hourData.ConsumeToken)
  133. consumeToken.Label = append(consumeToken.Label, fmt.Sprintf("%02d点", addtimeLastTwoDigits))
  134. activeUser.Count = hourData.ActiveUser
  135. activeUser.Val = append(activeUser.Val, hourData.ActiveUser)
  136. activeUser.Label = append(activeUser.Label, fmt.Sprintf("%02d点", addtimeLastTwoDigits))
  137. newUser.Count += hourData.NewUser
  138. newUser.Val = append(newUser.Val, hourData.NewUser)
  139. newUser.Label = append(newUser.Label, fmt.Sprintf("%02d点", addtimeLastTwoDigits))
  140. }
  141. hourLen := len(usageStatisticHour)
  142. if hourLen > 0 {
  143. if usageStatisticHour[0].TotalFriend > 0 {
  144. totalFriend.Rate = float32((usageStatisticHour[hourLen-1].TotalFriend - usageStatisticHour[0].TotalFriend) / usageStatisticHour[0].TotalFriend)
  145. }
  146. if usageStatisticHour[0].TotalGroup > 0 {
  147. totalGroup.Rate = float32((usageStatisticHour[hourLen-1].TotalGroup - usageStatisticHour[0].TotalGroup) / usageStatisticHour[0].TotalGroup)
  148. }
  149. if usageStatisticHour[0].ActiveUser > 0 {
  150. activeUser.Rate = float32((usageStatisticHour[hourLen-1].ActiveUser - usageStatisticHour[0].ActiveUser) / usageStatisticHour[0].ActiveUser)
  151. }
  152. if usageStatisticHour[0].NewUser > 0 {
  153. newUser.Rate = float32((usageStatisticHour[hourLen-1].NewUser - usageStatisticHour[0].NewUser) / usageStatisticHour[0].NewUser)
  154. }
  155. labelDists = usageStatisticHour[hourLen-1].LabelDist
  156. }
  157. } else {
  158. // 从天表统计数据
  159. startAddTimeString := startTime.Format("20060102")
  160. startAddTime, err := strconv.ParseUint(startAddTimeString, 10, 64)
  161. if err != nil {
  162. fmt.Println("转换开始时间失败:", err)
  163. return nil, err
  164. }
  165. endAddTimeString := endTime.Format("20060102")
  166. endAddTime, err := strconv.ParseUint(endAddTimeString, 10, 64)
  167. if err != nil {
  168. fmt.Println("转换截止时间失败:", err)
  169. return nil, err
  170. }
  171. var predicatesDay []predicate.UsageStatisticDay
  172. predicatesDay = append(predicatesDay, usagestatisticday.OrganizationID(organizationId))
  173. predicatesDay = append(predicatesDay, usagestatisticday.BotID(""))
  174. predicatesDay = append(predicatesDay, usagestatisticday.AddtimeGTE(startAddTime))
  175. predicatesDay = append(predicatesDay, usagestatisticday.AddtimeLTE(endAddTime))
  176. usageStatisticDay, err := l.svcCtx.DB.UsageStatisticDay.Query().Where(predicatesDay...).All(l.ctx)
  177. if err != nil {
  178. return nil, err
  179. }
  180. for _, dayData := range usageStatisticDay {
  181. aiResponse.Count = aiResponse.Count + dayData.AiResponse
  182. aiResponse.Val = append(aiResponse.Val, dayData.AiResponse)
  183. aiResponse.Label = append(aiResponse.Label, fmt.Sprintf("%d", dayData.Addtime))
  184. sopRun.Count += dayData.SopRun
  185. sopRun.Val = append(sopRun.Val, dayData.SopRun)
  186. sopRun.Label = append(sopRun.Label, fmt.Sprintf("%d", dayData.Addtime))
  187. totalFriend.Count = dayData.TotalFriend
  188. totalFriend.Val = append(totalFriend.Val, dayData.TotalFriend)
  189. totalFriend.Label = append(totalFriend.Label, fmt.Sprintf("%d", dayData.Addtime))
  190. totalGroup.Count = dayData.TotalGroup
  191. totalGroup.Val = append(totalGroup.Val, dayData.TotalGroup)
  192. totalGroup.Label = append(totalGroup.Label, fmt.Sprintf("%d", dayData.Addtime))
  193. consumeToken.Count += dayData.ConsumeToken
  194. consumeToken.Val = append(consumeToken.Val, dayData.ConsumeToken)
  195. consumeToken.Label = append(consumeToken.Label, fmt.Sprintf("%d", dayData.Addtime))
  196. activeUser.Count = dayData.ActiveUser
  197. activeUser.Val = append(activeUser.Val, dayData.ActiveUser)
  198. activeUser.Label = append(activeUser.Label, fmt.Sprintf("%d", dayData.Addtime))
  199. newUser.Count += dayData.NewUser
  200. newUser.Val = append(newUser.Val, dayData.NewUser)
  201. newUser.Label = append(newUser.Label, fmt.Sprintf("%d", dayData.Addtime))
  202. }
  203. dayLen := len(usageStatisticDay)
  204. if dayLen > 0 {
  205. if usageStatisticDay[0].TotalFriend > 0 {
  206. totalFriend.Rate = float32((usageStatisticDay[dayLen-1].TotalFriend - usageStatisticDay[0].TotalFriend) / usageStatisticDay[0].TotalFriend)
  207. }
  208. if usageStatisticDay[0].TotalGroup > 0 {
  209. totalGroup.Rate = float32((usageStatisticDay[dayLen-1].TotalGroup - usageStatisticDay[0].TotalGroup) / usageStatisticDay[0].TotalGroup)
  210. }
  211. if usageStatisticDay[0].ActiveUser > 0 {
  212. activeUser.Rate = float32((usageStatisticDay[dayLen-1].ActiveUser - usageStatisticDay[0].ActiveUser) / usageStatisticDay[0].ActiveUser)
  213. }
  214. if usageStatisticDay[0].NewUser > 0 {
  215. newUser.Rate = float32((usageStatisticDay[dayLen-1].NewUser - usageStatisticDay[0].NewUser) / usageStatisticDay[0].NewUser)
  216. }
  217. labelDists = usageStatisticDay[dayLen-1].LabelDist
  218. }
  219. if isCurrentDay {
  220. // 从小时表统计当天数据
  221. startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
  222. startOfDayAddTimeString := startOfDay.Format("2006010200")
  223. startOfDayAddTime, err := strconv.ParseUint(startOfDayAddTimeString, 10, 64)
  224. if err != nil {
  225. fmt.Println("转换开始时间失败:", err)
  226. return nil, err
  227. }
  228. var predicates []predicate.UsageStatisticHour
  229. predicates = append(predicates, usagestatistichour.OrganizationID(organizationId))
  230. predicates = append(predicates, usagestatistichour.BotID(""))
  231. predicates = append(predicates, usagestatistichour.AddtimeGTE(startOfDayAddTime))
  232. usageStatisticHour, err := l.svcCtx.DB.UsageStatisticHour.Query().Where(predicates...).All(l.ctx)
  233. if err != nil {
  234. return nil, err
  235. }
  236. hourLen := len(usageStatisticHour)
  237. if hourLen > 0 {
  238. var aiResponseOfDay uint64
  239. var sopRunOfDay uint64
  240. var totalFriendOfDay uint64
  241. var totalGroupOfDay uint64
  242. var consumeTokenOfDay uint64
  243. var activeUserOfDay uint64
  244. var newUserOfDay int64
  245. for _, hourData := range usageStatisticHour {
  246. aiResponseOfDay += hourData.AiResponse
  247. sopRunOfDay += hourData.SopRun
  248. consumeTokenOfDay += hourData.ConsumeToken
  249. }
  250. totalFriendOfDay = usageStatisticHour[hourLen-1].TotalFriend
  251. totalGroupOfDay = usageStatisticHour[hourLen-1].TotalGroup
  252. activeUserOfDay = usageStatisticHour[hourLen-1].ActiveUser
  253. newUserOfDay = usageStatisticHour[hourLen-1].NewUser
  254. aiResponse.Count = aiResponse.Count + aiResponseOfDay
  255. aiResponse.Val = append(aiResponse.Val, aiResponseOfDay)
  256. aiResponse.Label = append(aiResponse.Label, "今日")
  257. sopRun.Count = sopRun.Count + sopRunOfDay
  258. sopRun.Val = append(sopRun.Val, sopRunOfDay)
  259. sopRun.Label = append(sopRun.Label, "今日")
  260. totalFriend.Count = totalFriendOfDay
  261. totalFriend.Val = append(totalFriend.Val, totalFriendOfDay)
  262. totalFriend.Label = append(totalFriend.Label, "今日")
  263. tfLen := len(totalFriend.Val)
  264. if tfLen > 0 && totalFriend.Val[0] > 0 {
  265. totalFriend.Rate = float32((totalFriend.Val[tfLen-1] - totalFriend.Val[0]) / totalFriend.Val[0])
  266. }
  267. totalGroup.Count = totalGroupOfDay
  268. totalGroup.Val = append(totalGroup.Val, totalGroupOfDay)
  269. totalGroup.Label = append(totalGroup.Label, "今日")
  270. tgLen := len(totalGroup.Val)
  271. if tgLen > 0 && totalGroup.Val[0] > 0 {
  272. totalGroup.Rate = float32((totalGroup.Val[tgLen-1] - totalGroup.Val[0]) / totalGroup.Val[0])
  273. }
  274. consumeToken.Count = consumeToken.Count + consumeTokenOfDay
  275. consumeToken.Val = append(consumeToken.Val, consumeTokenOfDay)
  276. consumeToken.Label = append(consumeToken.Label, "今日")
  277. activeUser.Count = activeUserOfDay
  278. activeUser.Val = append(activeUser.Val, activeUserOfDay)
  279. activeUser.Label = append(activeUser.Label, "今日")
  280. auLen := len(activeUser.Val)
  281. if auLen > 0 && activeUser.Val[0] > 0 {
  282. activeUser.Rate = float32((activeUser.Val[auLen-1] - activeUser.Val[0]) / activeUser.Val[0])
  283. }
  284. newUser.Count = newUserOfDay
  285. newUser.Val = append(newUser.Val, newUserOfDay)
  286. newUser.Label = append(newUser.Label, "今日")
  287. nuLen := len(newUser.Val)
  288. if nuLen > 0 && newUser.Val[0] > 0 {
  289. newUser.Rate = float32((newUser.Val[nuLen-1] - newUser.Val[0]) / newUser.Val[0])
  290. }
  291. labelDists = usageStatisticHour[hourLen-1].LabelDist
  292. }
  293. }
  294. }
  295. var labelIds []uint64
  296. var labelsData []types.LabelsData
  297. labelSet := make(map[uint64]uint64)
  298. for _, labelDist := range labelDists {
  299. if labelDist.Count != 0 {
  300. labelIds = append(labelIds, labelDist.LabelID)
  301. labelSet[labelDist.LabelID] = labelDist.Count
  302. }
  303. }
  304. labelInfos, err := l.svcCtx.DB.Label.Query().Where(label.IDIn(labelIds...)).All(l.ctx)
  305. for _, labelInfo := range labelInfos {
  306. labelsData = append(labelsData, types.LabelsData{
  307. Value: labelSet[labelInfo.ID],
  308. Name: labelInfo.Name,
  309. })
  310. }
  311. chartsData := types.ChartsData{
  312. AiResponse: &aiResponse,
  313. SopRun: &sopRun,
  314. TotalFriend: &totalFriend,
  315. TotalGroup: &totalGroup,
  316. AccountBalance: &accountBalance,
  317. ConsumeToken: &consumeToken,
  318. ActiveUser: &activeUser,
  319. NewUser: &newUser,
  320. LabelDist: labelsData,
  321. }
  322. return &types.ChartsResp{BaseDataInfo: types.BaseDataInfo{Msg: errormsg.UpdateSuccess}, Data: &chartsData}, nil
  323. }