dashboard.go 13 KB

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