get_charts_logic.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 isCurrentDay && layoutsType == 1 && *req.StartDate == *req.EndDate {
  95. // 返回当日每小时的数据
  96. startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
  97. startAddTimeString := startOfDay.Format("2006010200")
  98. startAddTime, err := strconv.ParseUint(startAddTimeString, 10, 64)
  99. if err != nil {
  100. fmt.Println("转换开始时间失败:", err)
  101. return nil, err
  102. }
  103. var predicates []predicate.UsageStatisticHour
  104. predicates = append(predicates, usagestatistichour.OrganizationID(organizationId))
  105. predicates = append(predicates, usagestatistichour.BotID(""))
  106. predicates = append(predicates, usagestatistichour.AddtimeGTE(startAddTime))
  107. usageStatisticHour, err := l.svcCtx.DB.UsageStatisticHour.Query().Where(predicates...).All(l.ctx)
  108. if err != nil {
  109. return nil, err
  110. }
  111. for _, hourData := range usageStatisticHour {
  112. addtimeLastTwoDigits := hourData.Addtime % 100
  113. aiResponse.Count += hourData.AiResponse
  114. aiResponse.Val = append(aiResponse.Val, hourData.AiResponse)
  115. sopRun.Count += hourData.SopRun
  116. sopRun.Val = append(sopRun.Val, hourData.SopRun)
  117. totalFriend.Count = hourData.TotalFriend
  118. totalFriend.Val = append(totalFriend.Val, hourData.TotalFriend)
  119. totalGroup.Count = hourData.TotalGroup
  120. totalGroup.Val = append(totalGroup.Val, hourData.TotalGroup)
  121. consumeToken.Count += hourData.ConsumeToken
  122. consumeToken.Val = append(consumeToken.Val, hourData.ConsumeToken)
  123. consumeToken.Label = append(consumeToken.Label, fmt.Sprintf("%02d", addtimeLastTwoDigits))
  124. activeUser.Count = hourData.ActiveUser
  125. activeUser.Val = append(activeUser.Val, hourData.ActiveUser)
  126. newUser.Count += hourData.NewUser
  127. newUser.Val = append(newUser.Val, hourData.NewUser)
  128. newUser.Label = append(newUser.Label, fmt.Sprintf("%02d", addtimeLastTwoDigits))
  129. }
  130. hourLen := len(usageStatisticHour)
  131. if hourLen > 0 {
  132. if usageStatisticHour[0].TotalFriend > 0 {
  133. totalFriend.Rate = float32((usageStatisticHour[hourLen-1].TotalFriend - usageStatisticHour[0].TotalFriend) / usageStatisticHour[0].TotalFriend)
  134. }
  135. if usageStatisticHour[0].TotalGroup > 0 {
  136. totalGroup.Rate = float32((usageStatisticHour[hourLen-1].TotalGroup - usageStatisticHour[0].TotalGroup) / usageStatisticHour[0].TotalGroup)
  137. }
  138. if usageStatisticHour[0].ActiveUser > 0 {
  139. activeUser.Rate = float32((usageStatisticHour[hourLen-1].ActiveUser - usageStatisticHour[0].ActiveUser) / usageStatisticHour[0].ActiveUser)
  140. }
  141. if usageStatisticHour[0].NewUser > 0 {
  142. newUser.Rate = float32((usageStatisticHour[hourLen-1].NewUser - usageStatisticHour[0].NewUser) / usageStatisticHour[0].NewUser)
  143. }
  144. labelDists = usageStatisticHour[hourLen-1].LabelDist
  145. }
  146. } else {
  147. // 从天表统计数据
  148. startAddTimeString := startTime.Format("20060102")
  149. startAddTime, err := strconv.ParseUint(startAddTimeString, 10, 64)
  150. if err != nil {
  151. fmt.Println("转换开始时间失败:", err)
  152. return nil, err
  153. }
  154. endAddTimeString := endTime.Format("20060102")
  155. endAddTime, err := strconv.ParseUint(endAddTimeString, 10, 64)
  156. if err != nil {
  157. fmt.Println("转换截止时间失败:", err)
  158. return nil, err
  159. }
  160. var predicatesDay []predicate.UsageStatisticDay
  161. predicatesDay = append(predicatesDay, usagestatisticday.OrganizationID(organizationId))
  162. predicatesDay = append(predicatesDay, usagestatisticday.BotID(""))
  163. predicatesDay = append(predicatesDay, usagestatisticday.AddtimeGTE(startAddTime))
  164. predicatesDay = append(predicatesDay, usagestatisticday.AddtimeLTE(endAddTime))
  165. usageStatisticDay, err := l.svcCtx.DB.UsageStatisticDay.Query().Where(predicatesDay...).All(l.ctx)
  166. if err != nil {
  167. return nil, err
  168. }
  169. for _, dayData := range usageStatisticDay {
  170. aiResponse.Count = aiResponse.Count + dayData.AiResponse
  171. aiResponse.Val = append(aiResponse.Val, dayData.AiResponse)
  172. sopRun.Count += dayData.SopRun
  173. sopRun.Val = append(sopRun.Val, dayData.SopRun)
  174. totalFriend.Count = dayData.TotalFriend
  175. totalFriend.Val = append(totalFriend.Val, dayData.TotalFriend)
  176. totalGroup.Count = dayData.TotalGroup
  177. totalGroup.Val = append(totalGroup.Val, dayData.TotalGroup)
  178. consumeToken.Count += dayData.ConsumeToken
  179. consumeToken.Val = append(consumeToken.Val, dayData.ConsumeToken)
  180. consumeToken.Label = append(consumeToken.Label, fmt.Sprintf("%d", dayData.Addtime))
  181. activeUser.Count = dayData.ActiveUser
  182. activeUser.Val = append(activeUser.Val, dayData.ActiveUser)
  183. newUser.Count += dayData.NewUser
  184. newUser.Val = append(newUser.Val, dayData.NewUser)
  185. newUser.Label = append(newUser.Label, fmt.Sprintf("%d", dayData.Addtime))
  186. }
  187. dayLen := len(usageStatisticDay)
  188. if dayLen > 0 {
  189. if usageStatisticDay[0].TotalFriend > 0 {
  190. totalFriend.Rate = float32((usageStatisticDay[dayLen-1].TotalFriend - usageStatisticDay[0].TotalFriend) / usageStatisticDay[0].TotalFriend)
  191. }
  192. if usageStatisticDay[0].TotalGroup > 0 {
  193. totalGroup.Rate = float32((usageStatisticDay[dayLen-1].TotalGroup - usageStatisticDay[0].TotalGroup) / usageStatisticDay[0].TotalGroup)
  194. }
  195. if usageStatisticDay[0].ActiveUser > 0 {
  196. activeUser.Rate = float32((usageStatisticDay[dayLen-1].ActiveUser - usageStatisticDay[0].ActiveUser) / usageStatisticDay[0].ActiveUser)
  197. }
  198. if usageStatisticDay[0].NewUser > 0 {
  199. newUser.Rate = float32((usageStatisticDay[dayLen-1].NewUser - usageStatisticDay[0].NewUser) / usageStatisticDay[0].NewUser)
  200. }
  201. labelDists = usageStatisticDay[dayLen-1].LabelDist
  202. }
  203. if isCurrentDay {
  204. // 从小时表统计当天数据
  205. startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
  206. startOfDayAddTimeString := startOfDay.Format("2006010200")
  207. startOfDayAddTime, err := strconv.ParseUint(startOfDayAddTimeString, 10, 64)
  208. if err != nil {
  209. fmt.Println("转换开始时间失败:", err)
  210. return nil, err
  211. }
  212. var predicates []predicate.UsageStatisticHour
  213. predicates = append(predicates, usagestatistichour.OrganizationID(organizationId))
  214. predicates = append(predicates, usagestatistichour.BotID(""))
  215. predicates = append(predicates, usagestatistichour.AddtimeGTE(startOfDayAddTime))
  216. usageStatisticHour, err := l.svcCtx.DB.UsageStatisticHour.Query().Where(predicates...).All(l.ctx)
  217. if err != nil {
  218. return nil, err
  219. }
  220. hourLen := len(usageStatisticHour)
  221. if hourLen > 0 {
  222. var aiResponseOfDay uint64
  223. var sopRunOfDay uint64
  224. var totalFriendOfDay uint64
  225. var totalGroupOfDay uint64
  226. var consumeTokenOfDay uint64
  227. var activeUserOfDay uint64
  228. var newUserOfDay int64
  229. for _, hourData := range usageStatisticHour {
  230. aiResponseOfDay += hourData.AiResponse
  231. sopRunOfDay += hourData.SopRun
  232. consumeTokenOfDay += hourData.ConsumeToken
  233. }
  234. totalFriendOfDay = usageStatisticHour[hourLen-1].TotalFriend
  235. totalGroupOfDay = usageStatisticHour[hourLen-1].TotalGroup
  236. activeUserOfDay = usageStatisticHour[hourLen-1].ActiveUser
  237. newUserOfDay = usageStatisticHour[hourLen-1].NewUser
  238. aiResponse.Count = aiResponse.Count + aiResponseOfDay
  239. aiResponse.Val = append(aiResponse.Val, aiResponseOfDay)
  240. sopRun.Count = sopRun.Count + sopRunOfDay
  241. sopRun.Val = append(sopRun.Val, sopRunOfDay)
  242. totalFriend.Count = totalFriendOfDay
  243. totalFriend.Val = append(totalFriend.Val, totalFriendOfDay)
  244. tfLen := len(totalFriend.Val)
  245. if tfLen > 0 && totalFriend.Val[0] > 0 {
  246. totalFriend.Rate = float32((totalFriend.Val[tfLen-1] - totalFriend.Val[0]) / totalFriend.Val[0])
  247. }
  248. totalGroup.Count = totalGroupOfDay
  249. totalGroup.Val = append(totalGroup.Val, totalGroupOfDay)
  250. tgLen := len(totalGroup.Val)
  251. if tgLen > 0 && totalGroup.Val[0] > 0 {
  252. totalGroup.Rate = float32((totalGroup.Val[tgLen-1] - totalGroup.Val[0]) / totalGroup.Val[0])
  253. }
  254. consumeToken.Count = consumeToken.Count + consumeTokenOfDay
  255. consumeToken.Val = append(consumeToken.Val, consumeTokenOfDay)
  256. consumeToken.Label = append(consumeToken.Label, "今日")
  257. activeUser.Count = activeUserOfDay
  258. activeUser.Val = append(activeUser.Val, activeUserOfDay)
  259. auLen := len(activeUser.Val)
  260. if auLen > 0 && activeUser.Val[0] > 0 {
  261. activeUser.Rate = float32((activeUser.Val[auLen-1] - activeUser.Val[0]) / activeUser.Val[0])
  262. }
  263. newUser.Count = newUserOfDay
  264. newUser.Val = append(newUser.Val, newUserOfDay)
  265. newUser.Label = append(newUser.Label, "今日")
  266. nuLen := len(newUser.Val)
  267. if nuLen > 0 && newUser.Val[0] > 0 {
  268. newUser.Rate = float32((newUser.Val[nuLen-1] - newUser.Val[0]) / newUser.Val[0])
  269. }
  270. labelDists = usageStatisticHour[hourLen-1].LabelDist
  271. }
  272. }
  273. }
  274. var labelIds []uint64
  275. var labelsData []types.LabelsData
  276. labelSet := make(map[uint64]uint64)
  277. for _, labelDist := range labelDists {
  278. if labelDist.Count != 0 {
  279. labelIds = append(labelIds, labelDist.LabelID)
  280. labelSet[labelDist.LabelID] = labelDist.Count
  281. }
  282. }
  283. labelInfos, err := l.svcCtx.DB.Label.Query().Where(label.IDIn(labelIds...)).All(l.ctx)
  284. for _, labelInfo := range labelInfos {
  285. labelsData = append(labelsData, types.LabelsData{
  286. Value: labelSet[labelInfo.ID],
  287. Name: labelInfo.Name,
  288. })
  289. }
  290. chartsData := types.ChartsData{
  291. AiResponse: &aiResponse,
  292. SopRun: &sopRun,
  293. TotalFriend: &totalFriend,
  294. TotalGroup: &totalGroup,
  295. AccountBalance: &accountBalance,
  296. ConsumeToken: &consumeToken,
  297. ActiveUser: &activeUser,
  298. NewUser: &newUser,
  299. LabelDist: labelsData,
  300. }
  301. return &types.ChartsResp{BaseDataInfo: types.BaseDataInfo{Msg: errormsg.UpdateSuccess}, Data: &chartsData}, nil
  302. }