dashboard_more.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  12. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  13. "gitee.com/xuyiping_admin/pkg/xerr"
  14. "go.uber.org/zap"
  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. var count int64
  22. neckRingEstrusList := make([]*model.NeckRingEstrusWarning, 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. pref, err := s.EstrusWarningQuery(ctx, userModel.AppPasture.Id)
  29. if err != nil {
  30. return nil, xerr.Customf("系统错误!")
  31. }
  32. if err = pref.Group("a.cow_id").
  33. Order("a.level,a.id DESC").
  34. Count(&count).
  35. Find(&neckRingEstrusList).Error; err != nil {
  36. return nil, xerr.WithStack(err)
  37. }
  38. countEstrusWarning := 0
  39. nowTime := time.Now().Local()
  40. optimumMating := map[string]int32{
  41. "front": 0,
  42. "middle": 0,
  43. "behind": 0,
  44. }
  45. cowIds := make([]int64, 0)
  46. for _, v := range neckRingEstrusList {
  47. cowIds = append(cowIds, v.CowId)
  48. }
  49. cowList := make([]*model.Cow, 0)
  50. if err = s.DB.Model(new(model.Cow)).
  51. Where("pasture_id = ?", userModel.AppPasture.Id).
  52. Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
  53. Where("id IN ?", cowIds).
  54. Find(&cowList).Error; err != nil {
  55. zaplog.Error("NeckRingWarning", zap.Any("err", err))
  56. }
  57. cowByIdMap := map[int64]*model.Cow{}
  58. for _, v := range cowList {
  59. cowByIdMap[v.Id] = v
  60. }
  61. for _, v := range neckRingEstrusList {
  62. estrusWarningLevelItems[int32(v.Level)] += 1
  63. countEstrusWarning += 1
  64. cowInfo, ok := cowByIdMap[v.CowId]
  65. if !ok {
  66. zaplog.Info("NeckRingWarning", zap.Any("v", v), zap.Any("cowByIdMap", cowByIdMap))
  67. continue
  68. }
  69. pzHour := v.CalculatePzHour(cowInfo.Lact)
  70. optimumMatingStartTime := pzHour.Add(-4 * time.Hour)
  71. optimumMatingEndTime := pzHour.Add(4 * time.Hour)
  72. // 判断当前时间是否在 pzHour-4h 到 pzHour+4h 之间
  73. if nowTime.After(optimumMatingStartTime) && nowTime.Before(optimumMatingEndTime) {
  74. optimumMating["middle"] += 1
  75. }
  76. if nowTime.After(optimumMatingEndTime) {
  77. optimumMating["behind"] += 1
  78. }
  79. if nowTime.Before(optimumMatingStartTime) {
  80. optimumMating["front"] += 1
  81. }
  82. }
  83. abortionCount := int64(0)
  84. pref, err = s.AbortionWarningQuery(ctx, userModel.AppPasture.Id)
  85. if err != nil {
  86. return nil, xerr.Customf("系统错误!")
  87. }
  88. if err = pref.Group("cow_id").
  89. Count(&abortionCount).Error; err != nil {
  90. return nil, xerr.WithStack(err)
  91. }
  92. healthWarningNumber := int64(0)
  93. if err = s.DB.Model(new(model.NeckRingHealthWarning)).
  94. Where("pasture_id = ?", userModel.AppPasture.Id).
  95. Where("is_show = ?", pasturePb.IsShow_Ok).
  96. Group("cow_id").
  97. Count(&healthWarningNumber).Error; err != nil {
  98. zaplog.Error("NeckRingWarning", zap.Any("estrusWarningNumber", err))
  99. }
  100. return &pasturePb.IndexNeckRingResponse{
  101. Code: http.StatusOK,
  102. Msg: "ok",
  103. Data: &pasturePb.NeckRingData{
  104. EstrusWarningNumber: int32(countEstrusWarning),
  105. HealthWarningNumber: int32(healthWarningNumber),
  106. AbortionWarningNumber: int32(abortionCount),
  107. StressWarningNumber: 0,
  108. EstrusWarningLevelItems: estrusWarningLevelItems,
  109. OptimumMating: optimumMating,
  110. },
  111. }, nil
  112. }
  113. func (s *StoreEntry) FocusIndicatorsList(ctx context.Context, dimension string) (*pasturePb.IndexFocusIndicatorsResponse, error) {
  114. userModel, err := s.GetUserModel(ctx)
  115. if err != nil {
  116. return nil, xerr.WithStack(err)
  117. }
  118. userFocusIndicators := userModel.SystemUser.IndicatorsKinds
  119. if len(userFocusIndicators) <= 0 {
  120. userFocusIndicators = model.DefaultFocusIndicators
  121. }
  122. userFocusIndicatorsList := strings.Split(userFocusIndicators, ",")
  123. // 获取用户关注的指标
  124. userFocusIndicatorsDetailsList := make([]*model.IndicatorsDetails, 0)
  125. if err = s.DB.Model(new(model.IndicatorsDetails)).
  126. Where("kind in (?)", userFocusIndicatorsList).
  127. Find(&userFocusIndicatorsDetailsList).Error; err != nil {
  128. zaplog.Error("FocusIndicators", zap.Any("err", err))
  129. }
  130. nowTime := time.Now().Local()
  131. currentMonth := nowTime.Format(model.LayoutMonth)
  132. lastMonth := nowTime.AddDate(0, -1, 0).Format(model.LayoutMonth)
  133. lastYear := nowTime.AddDate(-1, 0, 0).Format(model.LayoutYear)
  134. indicatorsDataList := make([]*model.IndicatorsData, 0)
  135. if err = s.DB.Model(new(model.IndicatorsData)).
  136. Where("pasture_id = ?", userModel.AppPasture.Id).
  137. Where("kind in (?)", userFocusIndicatorsList).
  138. Where("date IN ?", []string{currentMonth, lastMonth, lastYear}).
  139. Order("kind,date").
  140. Find(&indicatorsDataList).Error; err != nil {
  141. zaplog.Error("FocusIndicators", zap.Any("err", err))
  142. }
  143. focusIndicatorsList := make([]*pasturePb.FocusIndicators, 0)
  144. indicatorsDataByKindMap := map[string][]*model.IndicatorsData{}
  145. for _, v := range indicatorsDataList {
  146. if indicatorsDataByKindMap[v.Kind] == nil {
  147. indicatorsDataByKindMap[v.Kind] = make([]*model.IndicatorsData, 0)
  148. }
  149. indicatorsDataByKindMap[v.Kind] = append(indicatorsDataByKindMap[v.Kind], v)
  150. }
  151. for _, indicatorsDetails := range userFocusIndicatorsDetailsList {
  152. indicatorsList := indicatorsDataByKindMap[indicatorsDetails.Kind]
  153. onYear, onMonth, currValue, onValue := "", "", float64(0), ""
  154. isUp := pasturePb.IsShow_Ok
  155. for _, v := range indicatorsList {
  156. if v.Date == currentMonth {
  157. currValue, _ = strconv.ParseFloat(v.Value, 64)
  158. }
  159. if v.Date == lastYear {
  160. onYear = v.Value
  161. }
  162. if v.Date == lastMonth {
  163. onMonth = v.Value
  164. }
  165. }
  166. oldValue := float64(0)
  167. if dimension == "Year" {
  168. oldValue, _ = strconv.ParseFloat(onYear, 64)
  169. }
  170. if dimension == "Month" {
  171. oldValue, _ = strconv.ParseFloat(onMonth, 64)
  172. }
  173. if currValue > 0 && oldValue > 0 {
  174. b := float64(0)
  175. if oldValue > 0 {
  176. b = (oldValue - currValue) / oldValue * 100
  177. }
  178. omv := util.RoundToTwoDecimals(b)
  179. if omv < 0 {
  180. isUp = pasturePb.IsShow_No
  181. }
  182. onValue = strconv.FormatFloat(omv, 'f', 2, 64) + "%"
  183. }
  184. focusIndicatorsList = append(focusIndicatorsList, &pasturePb.FocusIndicators{
  185. Kind: indicatorsDetails.Kind,
  186. Name: indicatorsDetails.Name,
  187. Value: fmt.Sprintf("%f", currValue),
  188. Describe: indicatorsDetails.Zh,
  189. UnitName: indicatorsDetails.Unit,
  190. IsUp: isUp,
  191. OnYear: onValue,
  192. OnMonth: onValue,
  193. })
  194. }
  195. indicatorsDetailsList, _ := s.FindIndicatorsDetailsList()
  196. return &pasturePb.IndexFocusIndicatorsResponse{
  197. Code: http.StatusOK,
  198. Msg: "ok",
  199. Data: &pasturePb.FocusData{
  200. FocusIndicators: focusIndicatorsList,
  201. IndicatorsSet: model.IndicatorsDetailsSlice(indicatorsDetailsList).ToPB(userFocusIndicatorsList),
  202. },
  203. }, err
  204. }
  205. func (s *StoreEntry) FocusIndicatorsSet(ctx context.Context, req *pasturePb.IndexFocusIndicatorsSetRequest) error {
  206. userModel, err := s.GetUserModel(ctx)
  207. if err != nil {
  208. return xerr.WithStack(err)
  209. }
  210. if len(req.IndicatorsKind) <= 0 {
  211. return nil
  212. }
  213. userFocusIndicators := strings.Join(req.IndicatorsKind, ",")
  214. if err = s.DB.Model(new(model.SystemUser)).
  215. Where("id = ?", userModel.SystemUser.Id).
  216. Update("indicators_kinds", userFocusIndicators).Error; err != nil {
  217. return xerr.WithStack(err)
  218. }
  219. return nil
  220. }
  221. func (s *StoreEntry) Equipment(ctx context.Context) (*pasturePb.EquipmentResponse, error) {
  222. userModel, err := s.GetUserModel(ctx)
  223. if err != nil {
  224. return nil, xerr.WithStack(err)
  225. }
  226. equipmentList := make([]*pasturePb.Equipment, 0)
  227. dashboardNeckRingList := make([]*model.DashboardNeckRing, 0)
  228. if err = s.DB.Model(new(model.NeckRing)).
  229. Select("status, count(*) as number").
  230. Where("pasture_id = ?", userModel.AppPasture.Id).
  231. Group("status").
  232. Find(&dashboardNeckRingList).Error; err != nil {
  233. }
  234. normalNumber, abnormalNumber := int32(0), int32(0)
  235. for _, v := range dashboardNeckRingList {
  236. if v.Status == pasturePb.NeckRingStatus_Normal {
  237. normalNumber = v.Number
  238. }
  239. if v.Status == pasturePb.NeckRingStatus_Abnormal {
  240. abnormalNumber = v.Number
  241. }
  242. }
  243. var receiverCount int64
  244. if err = s.DB.Model(new(model.AppPastureReceiver)).
  245. Where("pasture_id = ?", userModel.AppPasture.Id).
  246. Count(&receiverCount).Error; err != nil {
  247. }
  248. equipmentList = append(equipmentList, &pasturePb.Equipment{
  249. Name: "异常脖环数",
  250. Describe: "脖环",
  251. NormalNumber: normalNumber,
  252. AbnormalNumber: abnormalNumber,
  253. Icon: "/assets/welcome/ring@2x.png",
  254. Kind: pasturePb.EquipmentType_Neck_Ring,
  255. }, &pasturePb.Equipment{
  256. Name: "离线接收器",
  257. Describe: "接收器",
  258. NormalNumber: int32(receiverCount),
  259. AbnormalNumber: int32(0),
  260. Icon: "/assets/welcome/device@2x.png",
  261. Kind: pasturePb.EquipmentType_Receiver,
  262. })
  263. return &pasturePb.EquipmentResponse{
  264. Code: http.StatusOK,
  265. Msg: "ok",
  266. Data: &pasturePb.EquipmentData{EquipmentList: equipmentList},
  267. }, nil
  268. }