get_charts_logic.go 12 KB

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