dashboard.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. package backend
  2. import (
  3. "context"
  4. "kpt-pasture/model"
  5. "kpt-pasture/util"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "gorm.io/gorm"
  11. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  12. "gitee.com/xuyiping_admin/pkg/xerr"
  13. "go.uber.org/zap"
  14. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  15. )
  16. func (s *StoreEntry) NeckRingWarning(ctx context.Context) (*pasturePb.IndexNeckRingResponse, error) {
  17. userModel, err := s.GetUserModel(ctx)
  18. if err != nil {
  19. return nil, xerr.WithStack(err)
  20. }
  21. estrusWarningCowList := make([]*model.NeckRingEstrus, 0)
  22. estrusWarningLevelItems := map[int32]int32{
  23. int32(pasturePb.EstrusLevel_Low): 0,
  24. int32(pasturePb.EstrusLevel_Middle): 0,
  25. int32(pasturePb.EstrusLevel_High): 0,
  26. }
  27. if err = s.DB.Model(new(model.EventEstrus)).
  28. Where("pasture_id = ?", userModel.AppPasture.Id).
  29. Where("is_show = ?", pasturePb.IsShow_Ok).
  30. Group("cow_id").Find(&estrusWarningCowList).Error; err != nil {
  31. zaplog.Error("NeckRingWarning", zap.Any("estrusWarningNumber", err))
  32. }
  33. for _, v := range estrusWarningCowList {
  34. estrusWarningLevelItems[int32(v.ActiveLevel)] += estrusWarningLevelItems[int32(v.ActiveLevel)]
  35. }
  36. healthWarningNumber := int64(0)
  37. if err = s.DB.Model(new(model.NeckRingHealthWarning)).
  38. Where("pasture_id = ?", userModel.AppPasture.Id).
  39. Where("is_show = ?", pasturePb.IsShow_Ok).
  40. Group("cow_id").
  41. Count(&healthWarningNumber).Error; err != nil {
  42. zaplog.Error("NeckRingWarning", zap.Any("estrusWarningNumber", err))
  43. }
  44. return &pasturePb.IndexNeckRingResponse{
  45. Code: http.StatusOK,
  46. Msg: "ok",
  47. Data: &pasturePb.NeckRingData{
  48. EstrusWarningNumber: int32(len(estrusWarningCowList)),
  49. HealthWarningNumber: int32(healthWarningNumber),
  50. AbortionWarningNumber: 0,
  51. StressWarningNumber: 0,
  52. EstrusWarningLevelItems: estrusWarningLevelItems,
  53. },
  54. }, nil
  55. }
  56. func (s *StoreEntry) FocusIndicatorsList(ctx context.Context, dimension string) (*pasturePb.IndexFocusIndicatorsResponse, error) {
  57. userModel, err := s.GetUserModel(ctx)
  58. if err != nil {
  59. return nil, xerr.WithStack(err)
  60. }
  61. userFocusIndicators := userModel.SystemUser.IndicatorsKinds
  62. if len(userFocusIndicators) <= 0 {
  63. userFocusIndicators = model.DefaultFocusIndicators
  64. }
  65. userFocusIndicatorsList := strings.Split(userFocusIndicators, ",")
  66. indicatorsDataList := make([]*model.IndicatorsData, 0)
  67. pref := s.DB.Model(new(model.IndicatorsData)).
  68. Where("pasture_id = ?", userModel.AppPasture.Id).
  69. Where("kind in (?)", userFocusIndicatorsList)
  70. /*if dimension == "Year" {
  71. pref.Where("date = ?", time.Now().Format(model.LayoutMonth))
  72. }*/
  73. nowTime := time.Now()
  74. if dimension == "Month" {
  75. pref.Where("date = ?", nowTime.Format(model.LayoutMonth))
  76. }
  77. if err = pref.Find(&indicatorsDataList).Error; err != nil {
  78. zaplog.Error("FocusIndicators", zap.Any("err", err))
  79. }
  80. indicatorsDetailsMap, _, err := s.GetIndicatorsDetailsMap(ctx)
  81. if err != nil {
  82. return nil, xerr.WithStack(err)
  83. }
  84. focusIndicatorsList := make([]*pasturePb.FocusIndicators, 0)
  85. for _, v := range indicatorsDataList {
  86. indicatorsDetails, ok := indicatorsDetailsMap[v.Kind]
  87. if !ok {
  88. continue
  89. }
  90. onYear, onMonth := "", ""
  91. isUp := pasturePb.IsShow_Ok
  92. if dimension == "Year" {
  93. return nil, xerr.Custom("暂不支持该维度")
  94. }
  95. if dimension == "Month" {
  96. lastMonth := nowTime.AddDate(0, -1, 0).Format(model.LayoutMonth)
  97. oldIndicators, _ := s.GetIndicatorsDataByDate(userModel.AppPasture.Id, v.Kind, lastMonth)
  98. if oldIndicators != nil {
  99. if oldIndicators.Value != "" && oldIndicators.Value != "0" {
  100. oldValue, _ := strconv.ParseFloat(oldIndicators.Value, 64)
  101. currValue, _ := strconv.ParseFloat(v.Value, 64)
  102. onMonthValue := (oldValue - currValue) / oldValue * 100
  103. omv := util.RoundToTwoDecimals(onMonthValue)
  104. if omv < 0 {
  105. isUp = pasturePb.IsShow_No
  106. }
  107. onMonth = strconv.FormatFloat(omv, 'f', 2, 64) + "%"
  108. }
  109. }
  110. }
  111. focusIndicatorsList = append(focusIndicatorsList, &pasturePb.FocusIndicators{
  112. Kind: indicatorsDetails.Kind,
  113. Name: indicatorsDetails.Name,
  114. Value: v.Value,
  115. Describe: indicatorsDetails.Zh,
  116. UnitName: indicatorsDetails.Unit,
  117. OnMonth: onMonth,
  118. OnYear: onYear,
  119. IsUp: isUp,
  120. })
  121. }
  122. indicatorsDetailsList, _ := s.FindIndicatorsDetailsList(ctx)
  123. return &pasturePb.IndexFocusIndicatorsResponse{
  124. Code: http.StatusOK,
  125. Msg: "ok",
  126. Data: &pasturePb.FocusData{
  127. FocusIndicators: focusIndicatorsList,
  128. IndicatorsSet: model.IndicatorsDetailsSlice(indicatorsDetailsList).ToPB(userFocusIndicatorsList),
  129. },
  130. }, err
  131. }
  132. func (s *StoreEntry) FocusIndicatorsSet(ctx context.Context, req *pasturePb.IndexFocusIndicatorsSetRequest) error {
  133. userModel, err := s.GetUserModel(ctx)
  134. if err != nil {
  135. return xerr.WithStack(err)
  136. }
  137. if len(req.IndicatorsKind) <= 0 {
  138. return nil
  139. }
  140. userFocusIndicators := strings.Join(req.IndicatorsKind, ",")
  141. if err = s.DB.Model(new(model.SystemUser)).
  142. Where("id = ?", userModel.SystemUser.Id).
  143. Update("indicators_kinds", userFocusIndicators).Error; err != nil {
  144. return xerr.WithStack(err)
  145. }
  146. return nil
  147. }
  148. func (s *StoreEntry) DataWarningSet(ctx context.Context, req *pasturePb.IndexDataWarningSetRequest) error {
  149. userModel, err := s.GetUserModel(ctx)
  150. if err != nil {
  151. return xerr.WithStack(err)
  152. }
  153. if len(req.WarningDataSet) <= 0 {
  154. return xerr.Custom("请选择预警数据")
  155. }
  156. defaultDataWarning, _ := s.FindDataWarning(ctx, model.DefaultUserId)
  157. if len(defaultDataWarning) <= 0 {
  158. return xerr.Custom("默认预警数据不存在,请联系管理员!")
  159. }
  160. userDataWarningList, err := s.FindDataWarning(ctx, userModel.SystemUser.Id)
  161. if err != nil {
  162. return xerr.WithStack(err)
  163. }
  164. if len(userDataWarningList) <= 0 { // 新增
  165. return s.addUserDataWarning(ctx, userModel.SystemUser.Id, defaultDataWarning, req.WarningDataSet)
  166. }
  167. return s.updateUserDataWarning(ctx, userModel.SystemUser.Id, userDataWarningList, req.WarningDataSet)
  168. }
  169. func (s *StoreEntry) DataWarningList(ctx context.Context) (*pasturePb.IndexDataWarningResponse, error) {
  170. userModel, err := s.GetUserModel(ctx)
  171. if err != nil {
  172. return nil, xerr.WithStack(err)
  173. }
  174. defaultDataWarning, _ := s.FindDataWarning(ctx, model.DefaultUserId)
  175. if len(defaultDataWarning) <= 0 {
  176. return nil, xerr.Custom("默认预警数据有误,请联系管理员!")
  177. }
  178. var isExist bool // 判断是否存在自己的设置的数据
  179. userDataWarning, _ := s.FindDataWarning(ctx, userModel.SystemUser.Id)
  180. if len(userDataWarning) == 0 {
  181. // 如果用户没有配置自己的预警数据,则使用默认数据
  182. isExist = true
  183. userDataWarning = defaultDataWarning
  184. }
  185. newTime := time.Now().Unix()
  186. needUpdateWarningIds := make([]int64, 0)
  187. for _, warningData := range userDataWarning {
  188. // 如果预警数据更新时间大于预警条件更新时间,并且更新时间距离当前时间小于2小时,则跳过
  189. if warningData.DataUpdateAt > warningData.ConditionUpdateAt && newTime-warningData.DataUpdateAt < int64(2*time.Hour) {
  190. continue
  191. }
  192. needUpdateWarningIds = append(needUpdateWarningIds, warningData.Id)
  193. }
  194. // 需要重新计算更新的warningId
  195. if len(needUpdateWarningIds) > 0 {
  196. s.UpdateWarningData(ctx, needUpdateWarningIds)
  197. }
  198. userDataWarningItems := make([]*model.DataWarningItems, 0)
  199. // 计算过后重新获取数据
  200. if isExist {
  201. userDataWarning, _ = s.FindDataWarning(ctx, model.DefaultUserId)
  202. userDataWarningItems, _ = s.FindDataWarningItems(ctx, model.DefaultUserId)
  203. } else {
  204. userDataWarning, _ = s.FindDataWarning(ctx, userModel.SystemUser.Id)
  205. userDataWarningItems, _ = s.FindDataWarningItems(ctx, userModel.SystemUser.Id)
  206. }
  207. return &pasturePb.IndexDataWarningResponse{
  208. Code: http.StatusOK,
  209. Msg: "ok",
  210. Data: &pasturePb.DataWarning{
  211. DataSet: model.DataWarningItemsSlice(userDataWarningItems).ToPB(userDataWarning),
  212. DataShow: model.DataWarningSlice(userDataWarning).ToPB(),
  213. },
  214. }, nil
  215. }
  216. // 新增用户预警数据
  217. func (s *StoreEntry) addUserDataWarning(ctx context.Context, userId int64, defaultDataWarning []*model.DataWarning, warningDataSet []*pasturePb.WarningDataSet) error {
  218. // 将默认预警数据按 Kind 映射
  219. defaultDataWarningMap := make(map[string]*model.DataWarning)
  220. for _, v := range defaultDataWarning {
  221. defaultDataWarningMap[v.Kind] = v
  222. }
  223. // 在事务中执行新增操作
  224. return s.DB.Transaction(func(tx *gorm.DB) error {
  225. addedKinds := make(map[string]bool) // 记录已添加的 Kind
  226. for _, set := range warningDataSet {
  227. dataWarning := model.NewDataWarning(userId, set.Kind, pasturePb.IsShow_Ok, defaultDataWarningMap[set.Kind])
  228. // 如果该 Kind 已添加,跳过
  229. if !addedKinds[set.Kind] {
  230. // 创建新的预警数据
  231. if err := tx.Create(dataWarning).Error; err != nil {
  232. return xerr.WithStack(err)
  233. }
  234. } else {
  235. oldDataWarning := &model.DataWarning{}
  236. if err := tx.Model(new(model.DataWarning)).
  237. Where("user_id = ?", userId).
  238. Where("kind = ?", set.Kind).
  239. First(oldDataWarning).Error; err != nil {
  240. return xerr.WithStack(err)
  241. }
  242. dataWarning.Id = oldDataWarning.Id
  243. }
  244. // 创建预警项数据
  245. if err := tx.Create(model.NewDataWarningItems(userId, dataWarning, set)).Error; err != nil {
  246. return xerr.WithStack(err)
  247. }
  248. addedKinds[set.Kind] = true
  249. }
  250. return nil
  251. })
  252. }
  253. // 更新用户预警数据
  254. func (s *StoreEntry) updateUserDataWarning(ctx context.Context, userId int64, userDataWarningList []*model.DataWarning, warningDataSet []*pasturePb.WarningDataSet) error {
  255. // 将请求数据按 WarningId 和 Id 映射
  256. warningIsShowMap := make(map[int32]pasturePb.IsShow_Kind)
  257. warningItemDataMap := make(map[int32]*pasturePb.WarningDataSet)
  258. for _, set := range warningDataSet {
  259. warningIsShowMap[set.WarningId] = set.IsShow
  260. warningItemDataMap[set.Id] = set
  261. }
  262. // 获取用户预警项数据
  263. userDataWarningItems, err := s.FindDataWarningItems(ctx, userId)
  264. if err != nil {
  265. return xerr.WithStack(err)
  266. }
  267. if len(userDataWarningItems) == 0 {
  268. return xerr.Custom("预警数据有误,请联系管理员!")
  269. }
  270. // 在事务中执行更新操作
  271. return s.DB.Transaction(func(tx *gorm.DB) error {
  272. // 更新预警数据的 IsShow 字段
  273. for _, warning := range userDataWarningList {
  274. if isShow, ok := warningIsShowMap[int32(warning.Id)]; ok {
  275. if err = tx.Model(&model.DataWarning{}).
  276. Where("id = ?", warning.Id).
  277. Update("is_show", isShow).Error; err != nil {
  278. return xerr.WithStack(err)
  279. }
  280. }
  281. }
  282. // 更新预警项数据的 IsShow 和 Value 字段
  283. for _, item := range userDataWarningItems {
  284. if set, ok := warningItemDataMap[int32(item.Id)]; ok {
  285. if err = tx.Model(&model.DataWarningItems{}).
  286. Where("id = ?", item.Id).
  287. Updates(map[string]interface{}{
  288. "is_show": set.IsShow,
  289. "value": set.Value,
  290. }).Error; err != nil {
  291. return xerr.WithStack(err)
  292. }
  293. }
  294. }
  295. return nil
  296. })
  297. }
  298. func (s *StoreEntry) FindDataWarning(ctx context.Context, userId int64) ([]*model.DataWarning, error) {
  299. dataWarningList := make([]*model.DataWarning, 0)
  300. if err := s.DB.Model(new(model.DataWarning)).
  301. Where("user_id = ?", userId).
  302. Find(&dataWarningList).Error; err != nil {
  303. return nil, xerr.WithStack(err)
  304. }
  305. return dataWarningList, nil
  306. }
  307. func (s *StoreEntry) FindDataWarningItems(ctx context.Context, userId int64) ([]*model.DataWarningItems, error) {
  308. dataWarningItemsList := make([]*model.DataWarningItems, 0)
  309. if err := s.DB.Model(new(model.DataWarningItems)).
  310. Where("user_id = ?", userId).
  311. Find(&dataWarningItemsList).Error; err != nil {
  312. return nil, xerr.WithStack(err)
  313. }
  314. return dataWarningItemsList, nil
  315. }
  316. func (s *StoreEntry) FindDataWarningMap(ctx context.Context, userId int64) (map[int64]*model.DataWarning, error) {
  317. dataWarning, err := s.FindDataWarning(ctx, userId)
  318. if err != nil {
  319. return nil, xerr.Custom("默认预警数据有误,请联系管理员!")
  320. }
  321. dataWarningMap := make(map[int64]*model.DataWarning)
  322. for _, v := range dataWarning {
  323. dataWarningMap[v.Id] = v
  324. }
  325. return dataWarningMap, nil
  326. }
  327. func (s *StoreEntry) FindDataWarningItemsMap(ctx context.Context, userId int64) (map[int64]*model.DataWarningItems, error) {
  328. dataWarningItemsList := make([]*model.DataWarningItems, 0)
  329. if err := s.DB.Model(new(model.DataWarningItems)).
  330. Where("user_id = ?", userId).
  331. Find(&dataWarningItemsList).Error; err != nil {
  332. return nil, xerr.WithStack(err)
  333. }
  334. dataWarningItemsMap := make(map[int64]*model.DataWarningItems)
  335. for _, v := range dataWarningItemsList {
  336. dataWarningItemsMap[v.Id] = v
  337. }
  338. return dataWarningItemsMap, nil
  339. }
  340. // UpdateWarningData 更新计算数据
  341. func (s *StoreEntry) UpdateWarningData(ctx context.Context, needUpdateWarningIds []int64) {
  342. if len(needUpdateWarningIds) <= 0 {
  343. return
  344. }
  345. for _, warningId := range needUpdateWarningIds {
  346. query, params, err := s.BuildQuery(warningId)
  347. if err != nil {
  348. zaplog.Error("UpdateWarningData", zap.Any("BuildQuery", err), zap.Any("warningId", warningId))
  349. }
  350. if len(query) == 0 || len(params) == 0 {
  351. continue
  352. }
  353. var count int64
  354. if err = s.DB.Model(new(model.Cow)).Where(query, params...).Count(&count).Error; err != nil {
  355. zaplog.Error("UpdateWarningData", zap.Any("err", err), zap.Any("query", query), zap.Any("params", params))
  356. }
  357. if err = s.DB.Model(new(model.DataWarning)).
  358. Where("id = ?", warningId).
  359. Updates(map[string]interface{}{
  360. "data_value": count,
  361. "data_update_at": time.Now().Unix(),
  362. }).Error; err != nil {
  363. zaplog.Error("UpdateWarningData", zap.Any("update", err))
  364. }
  365. }
  366. }