neck_ring_warning.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. package backend
  2. import (
  3. "context"
  4. "fmt"
  5. "kpt-pasture/model"
  6. "kpt-pasture/util"
  7. "net/http"
  8. "sort"
  9. "time"
  10. "go.uber.org/zap"
  11. "gorm.io/gorm"
  12. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  13. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  14. "gitee.com/xuyiping_admin/pkg/xerr"
  15. )
  16. func (s *StoreEntry) NeckRingWarningEstrusOrAbortionCowList(ctx context.Context, req *pasturePb.WarningItemsRequest, pagination *pasturePb.PaginationModel) (*pasturePb.EstrusResponse, error) {
  17. userModel, err := s.GetUserModel(ctx)
  18. if err != nil {
  19. return nil, xerr.WithStack(err)
  20. }
  21. var count int32
  22. neckRingEstrusList := make([]*model.NeckRingEstrusWarning, 0)
  23. var pref *gorm.DB
  24. switch req.Kind {
  25. case "abortion":
  26. pref, err = s.AbortionWarningQuery(ctx, userModel.AppPasture.Id)
  27. if err != nil {
  28. return nil, xerr.WithStack(err)
  29. }
  30. default:
  31. pref, err = s.EstrusWarningQuery(ctx, userModel.AppPasture.Id)
  32. if err != nil {
  33. return nil, xerr.WithStack(err)
  34. }
  35. }
  36. if len(req.EarNumber) > 0 {
  37. pref.Where("a.ear_number = ?", req.EarNumber)
  38. }
  39. if req.Level > 0 {
  40. pref.Where("a.level = ?", req.Level)
  41. }
  42. if len(req.PenIds) > 0 {
  43. pref.Where("b.pen_id IN ?", req.PenIds)
  44. }
  45. // 按照发情时间和发情等级倒叙排序
  46. if req.MatingWindowPeriod > 0 {
  47. if err = pref.Group("a.cow_id").
  48. Find(&neckRingEstrusList).Error; err != nil {
  49. return nil, xerr.WithStack(err)
  50. }
  51. } else {
  52. if err = pref.Group("a.cow_id").
  53. Find(&neckRingEstrusList).Error; err != nil {
  54. return nil, xerr.WithStack(err)
  55. }
  56. }
  57. cowMap := make(map[int64]*model.Cow)
  58. eventLogMap := make(map[int64]string)
  59. cowIds := make([]int64, 0)
  60. for _, v := range neckRingEstrusList {
  61. cowIds = append(cowIds, v.CowId)
  62. }
  63. if len(cowIds) > 0 {
  64. lastEventLogList := s.GetCowLastEventByCowIds(userModel.AppPasture.Id, cowIds, pasturePb.EventCategory_Breed)
  65. for _, log := range lastEventLogList {
  66. eventLogMap[log.CowId] = log.EventDescription
  67. }
  68. cowList, _ := s.GetCowInfoByCowIds(ctx, userModel.AppPasture.Id, cowIds)
  69. for _, cow := range cowList {
  70. cowMap[cow.Id] = cow
  71. }
  72. }
  73. list := model.NeckRingEstrusWarningSlice(neckRingEstrusList).ToPB(cowMap, eventLogMap, req.MatingWindowPeriod)
  74. // 排序 先按照高峰时间正序排,然后再按照发情等级倒叙排
  75. sort.Slice(list, func(i, j int) bool {
  76. if list[i].PostPeakTimeForHours != list[j].PostPeakTimeForHours {
  77. return list[i].PostPeakTimeForHours < list[j].PostPeakTimeForHours
  78. }
  79. return list[i].Level > list[j].Level
  80. })
  81. // 分页
  82. count = int32(len(list))
  83. if count > pagination.PageOffset {
  84. end := pagination.PageOffset + pagination.PageSize
  85. if end > count {
  86. end = count
  87. }
  88. list = list[pagination.PageOffset:end]
  89. } else {
  90. // 如果偏移量已超过列表长度,返回空列表
  91. list = list[:0]
  92. }
  93. return &pasturePb.EstrusResponse{
  94. Code: http.StatusOK,
  95. Msg: "ok",
  96. Data: &pasturePb.EstrusData{
  97. List: list,
  98. Total: count,
  99. PageSize: pagination.PageSize,
  100. Page: pagination.Page,
  101. },
  102. }, nil
  103. }
  104. func (s *StoreEntry) NeckRingWarningHealthCowList(ctx context.Context, req *pasturePb.HealthWarningRequest, pagination *pasturePb.PaginationModel) (*pasturePb.HealthWarningResponse, error) {
  105. userModel, err := s.GetUserModel(ctx)
  106. if err != nil {
  107. return nil, xerr.WithStack(err)
  108. }
  109. neckWaringHealthList := make([]*model.NeckRingHealthWarning, 0)
  110. var count int64
  111. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.NeckRingHealthWarning).TableName())).
  112. Select(`MAX(a.id) as id,a.cow_id,a.ear_number,a.neck_ring_number,a.score,a.heat_date,a.min_high,a.min_intake,
  113. a.min_chew,a.chew_sum,a.before_three_sum_chew,a.level`).
  114. Joins(fmt.Sprintf("JOIN cow AS b on a.cow_id = b.id")).
  115. Where("a.score >= ?", 0).
  116. Where("a.is_show = ?", pasturePb.IsShow_Ok).
  117. Where("a.pasture_id = ?", userModel.AppPasture.Id)
  118. if len(req.PenIds) > 0 {
  119. pref.Where("b.pen_id IN ?", req.PenIds)
  120. }
  121. if len(req.EarNumber) > 0 {
  122. pref.Where("a.ear_number = ?", req.EarNumber)
  123. }
  124. if req.Level > 0 {
  125. pref.Where("a.level = ?", req.Level)
  126. }
  127. if err = pref.Order("a.level DESC").
  128. Group("a.cow_id").
  129. Count(&count).
  130. Limit(int(pagination.PageSize)).
  131. Offset(int(pagination.PageOffset)).
  132. Find(&neckWaringHealthList).Error; err != nil {
  133. return nil, xerr.WithStack(err)
  134. }
  135. warningHealthLevelMap := s.WarningHealthLevelMap()
  136. healthStatusMap := s.HealthStatusMap()
  137. cowMap := make(map[int64]*model.Cow)
  138. eventLogMap := make(map[int64]string)
  139. cowIds := make([]int64, 0)
  140. for _, v := range neckWaringHealthList {
  141. cowIds = append(cowIds, v.CowId)
  142. lastEventLog := s.GetCowLastEvent(userModel.AppPasture.Id, v.CowId, pasturePb.EventCategory_Breed)
  143. if lastEventLog != nil {
  144. eventLogMap[v.CowId] = lastEventLog.EventDescription
  145. }
  146. }
  147. if len(cowIds) > 0 {
  148. cowList, _ := s.GetCowInfoByCowIds(ctx, userModel.AppPasture.Id, cowIds)
  149. for _, cow := range cowList {
  150. cowMap[cow.Id] = cow
  151. }
  152. }
  153. return &pasturePb.HealthWarningResponse{
  154. Code: http.StatusOK,
  155. Msg: "ok",
  156. Data: &pasturePb.HealthWarningData{
  157. Total: int32(count),
  158. Page: pagination.Page,
  159. PageSize: pagination.PageSize,
  160. List: model.NeckRingHealthWarningSlice(neckWaringHealthList).ToPB(warningHealthLevelMap, cowMap, eventLogMap, healthStatusMap),
  161. },
  162. }, nil
  163. }
  164. func (s *StoreEntry) NeckRingNoEstrusBatch(ctx context.Context, req *pasturePb.NeckRingNoEstrusBatchRequest) error {
  165. userModel, err := s.GetUserModel(ctx)
  166. if err != nil {
  167. return xerr.WithStack(err)
  168. }
  169. if len(req.EarNumbers) <= 0 {
  170. return xerr.Custom("请选择牛号")
  171. }
  172. nowTime := time.Now().Local()
  173. startTime := nowTime.AddDate(0, 0, -1).Format(model.LayoutDate2)
  174. endTime := nowTime.AddDate(0, 0, 1).Format(model.LayoutDate2)
  175. startTimeUnix := util.TimeParseLocalUnix(startTime)
  176. endTimeUnix := util.TimeParseLocalUnix(endTime)
  177. startTime = time.Unix(startTimeUnix, 0).Local().Format(model.LayoutTime)
  178. endTime = time.Unix(endTimeUnix, 0).Local().Format(model.LayoutTime)
  179. neckRingEstrusWarningList := make([]*model.NeckRingEstrusWarning, 0)
  180. if err = s.DB.Model(new(model.NeckRingEstrusWarning)).
  181. Where("pasture_id = ?", userModel.AppPasture.Id).
  182. Where("date_time BETWEEN ? AND ?", startTime, endTime).
  183. Where("ear_number IN ?", req.EarNumbers).
  184. Where("is_show = ?", pasturePb.IsShow_Ok).
  185. Find(&neckRingEstrusWarningList).Error; err != nil {
  186. return xerr.WithStack(err)
  187. }
  188. if len(neckRingEstrusWarningList) <= 0 {
  189. return nil
  190. }
  191. neckRingEstrusIds := make([]int64, 0)
  192. for _, v := range neckRingEstrusWarningList {
  193. neckRingEstrus := &model.NeckRingEstrus{}
  194. if err = s.DB.Model(new(model.NeckRingEstrus)).
  195. Where("pasture_id = ?", userModel.AppPasture.Id).
  196. Where("id = ?", v.NeckRingEstrusId).
  197. Where("is_show = ?", pasturePb.IsShow_Ok).
  198. First(neckRingEstrus).Error; err != nil {
  199. zaplog.Error("NeckRingNoEstrusBatch", zap.Any("err", err), zap.Any("neckRingEstrusWarning", v))
  200. return xerr.Customf("数据异常: %s", v.EarNumber)
  201. }
  202. neckRingEstrusIds = append(neckRingEstrusIds, neckRingEstrus.Id)
  203. }
  204. if len(neckRingEstrusIds) <= 0 {
  205. return nil
  206. }
  207. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  208. for _, id := range neckRingEstrusIds {
  209. if err = tx.Model(new(model.NeckRingEstrus)).
  210. Where("id = ?", id).
  211. Updates(map[string]interface{}{
  212. "check_result": pasturePb.CheckResult_Fail,
  213. "check_user_id": userModel.SystemUser.Id,
  214. "check_user_name": userModel.SystemUser.Name,
  215. "check_at": time.Now().Local().Unix(),
  216. "is_show": pasturePb.IsShow_No,
  217. }).Error; err != nil {
  218. return xerr.WithStack(err)
  219. }
  220. if err = tx.Model(new(model.NeckRingEstrusWarning)).
  221. Where("neck_ring_estrus_id = ?", id).
  222. Updates(map[string]interface{}{
  223. "is_show": pasturePb.IsShow_No,
  224. }).Error; err != nil {
  225. return xerr.WithStack(err)
  226. }
  227. }
  228. return nil
  229. }); err != nil {
  230. return xerr.WithStack(err)
  231. }
  232. return nil
  233. }
  234. func (s *StoreEntry) NeckRingNoDiseaseBatch(ctx context.Context, req *pasturePb.NeckRingNoEstrusBatchRequest) error {
  235. userModel, err := s.GetUserModel(ctx)
  236. if err != nil {
  237. return xerr.WithStack(err)
  238. }
  239. if len(req.EarNumbers) <= 0 {
  240. return xerr.Custom("请选择牛号")
  241. }
  242. nowTime := time.Now().Local()
  243. startTime := nowTime.AddDate(0, 0, -1).Format(model.LayoutDate2)
  244. endTime := nowTime.Format(model.LayoutDate2)
  245. neckRingHealthWarningList := make([]*model.NeckRingHealthWarning, 0)
  246. if err = s.DB.Model(new(model.NeckRingHealthWarning)).
  247. Where("pasture_id = ?", userModel.AppPasture.Id).
  248. Where("heat_date BETWEEN ? AND ?", startTime, endTime).
  249. Where("ear_number IN ?", req.EarNumbers).
  250. Where("is_show = ?", pasturePb.IsShow_Ok).
  251. Find(&neckRingHealthWarningList).Error; err != nil {
  252. return xerr.WithStack(err)
  253. }
  254. if len(neckRingHealthWarningList) <= 0 {
  255. return nil
  256. }
  257. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  258. for _, v := range neckRingHealthWarningList {
  259. if err = tx.Model(new(model.NeckRingHealth)).
  260. Where("pasture_id = ?", userModel.AppPasture.Id).
  261. Where("heat_date = ?", v.HeatDate).
  262. Where("cow_id = ?", v.CowId).
  263. Updates(map[string]interface{}{
  264. "check_result": pasturePb.CheckResult_Fail,
  265. "check_user_id": userModel.SystemUser.Id,
  266. "check_user_name": userModel.SystemUser.Name,
  267. "check_at": time.Now().Local().Unix(),
  268. "is_show": pasturePb.IsShow_No,
  269. }).Error; err != nil {
  270. return xerr.WithStack(err)
  271. }
  272. if err = tx.Model(new(model.NeckRingHealthWarning)).
  273. Where("neck_ring_health_id = ?", v.NeckRingHealthId).
  274. Updates(map[string]interface{}{
  275. "is_show": pasturePb.IsShow_No,
  276. }).Error; err != nil {
  277. return xerr.WithStack(err)
  278. }
  279. }
  280. return nil
  281. }); err != nil {
  282. return xerr.WithStack(err)
  283. }
  284. return nil
  285. }
  286. func (s *StoreEntry) EstrusWarningQuery(ctx context.Context, pastureId int64) (*gorm.DB, error) {
  287. nowTime := time.Now().Local()
  288. startTime := time.Unix(util.TimeParseLocalUnix(nowTime.AddDate(0, 0, -1).Format(model.LayoutDate2)), 0).Format(model.LayoutTime)
  289. entTime := time.Unix(util.TimeParseLocalEndUnix(nowTime.Format(model.LayoutDate2)), 0).Format(model.LayoutTime)
  290. systemBasic, err := s.FindSystemBasic(ctx, pastureId, model.EstrusWaringDays)
  291. if err != nil {
  292. return nil, xerr.WithStack(err)
  293. }
  294. return s.DB.Table(fmt.Sprintf("%s as a", new(model.NeckRingEstrusWarning).TableName())).
  295. Joins(fmt.Sprintf("JOIN %s AS b on a.cow_id = b.id", new(model.Cow).TableName())).
  296. Where("b.last_mating_at < UNIX_TIMESTAMP(a.date_time)").
  297. Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
  298. Where("b.is_forbidden_mating = ?", pasturePb.IsShow_No).
  299. Where("a.level >= ?", pasturePb.EstrusLevel_Low).
  300. Where("a.pasture_id = ?", pastureId).
  301. Where("a.date_time BETWEEN ? AND ?", startTime, entTime).
  302. Where(s.DB.Where("b.last_mating_at < UNIX_TIMESTAMP(a.first_time)").
  303. Or(s.DB.Where("b.last_mating_at = ?", 0).
  304. Where("b.calving_age > ?", systemBasic.MinValue).
  305. Or("b.lact = ?", 0))).
  306. Where("a.is_show = ?", pasturePb.IsShow_Ok), nil
  307. }
  308. func (s *StoreEntry) AbortionWarningQuery(ctx context.Context, pastureId int64) (*gorm.DB, error) {
  309. return s.DB.Table(fmt.Sprintf("%s as a", new(model.NeckRingEstrusWarning).TableName())).
  310. Joins(fmt.Sprintf("JOIN %s AS b on a.cow_id = b.id", new(model.Cow).TableName())).
  311. Where("b.pregnancy_age BETWEEN ? AND ?", 1, 260).
  312. Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
  313. Where("b.is_pregnant = ?", pasturePb.IsShow_Ok).
  314. Where("a.level >= ?", pasturePb.EstrusLevel_Middle).
  315. Where("a.pasture_id = ?", pastureId).
  316. Where("a.is_show = ?", pasturePb.IsShow_Ok), nil
  317. }
  318. func (s *StoreEntry) DataNoticeDetail(ctx context.Context) *model.DataNoticeResponse {
  319. res := &model.DataNoticeResponse{
  320. Code: http.StatusOK,
  321. Msg: "ok",
  322. Data: make([]*model.NoticeContent, 0),
  323. }
  324. userModel, err := s.GetUserModel(ctx)
  325. if err != nil {
  326. return res
  327. }
  328. pastureId := userModel.AppPasture.Id
  329. nowTime := time.Now().Local().Format(model.LayoutDate2)
  330. noticeList := make([]*model.DataNotice, 0)
  331. if err = s.DB.Model(new(model.DataNotice)).
  332. Where("pasture_id = ?", pastureId).
  333. Where("is_show = ?", pasturePb.IsShow_Ok).
  334. Where("start_date >= ? AND end_date <= ?", nowTime, nowTime).
  335. Order("id desc").
  336. Group("notice_kind").
  337. Find(&noticeList).Error; err != nil {
  338. return res
  339. }
  340. res.Data = model.DataNoticeSlice(noticeList).ToPB(userModel.SystemUser.Id)
  341. return res
  342. }
  343. func (s *StoreEntry) DataNoticeKnown(ctx context.Context, dataNoticeId int64) error {
  344. userModel, err := s.GetUserModel(ctx)
  345. if err != nil {
  346. return xerr.WithStack(err)
  347. }
  348. pastureId := userModel.AppPasture.Id
  349. dataNotice := model.DataNotice{}
  350. if err = s.DB.Model(new(model.DataNotice)).
  351. Where("id = ? and pasture_id = ?", dataNoticeId, pastureId).
  352. First(&dataNotice).Error; err != nil {
  353. return xerr.WithStack(err)
  354. }
  355. newKnownUsers := ""
  356. if len(dataNotice.KnownUsers) > 0 {
  357. newKnownUsers = fmt.Sprintf("%s,%d", dataNotice.KnownUsers, userModel.SystemUser.Id)
  358. } else {
  359. newKnownUsers = fmt.Sprintf("%d", userModel.SystemUser.Id)
  360. }
  361. if err = s.DB.Model(new(model.DataNotice)).
  362. Where("id = ?", dataNotice.Id).
  363. Select("known_users").
  364. Update("known_users", newKnownUsers).Error; err != nil {
  365. return xerr.WithStack(err)
  366. }
  367. return nil
  368. }