neck_ring_warning.go 13 KB

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