neck_ring_warning.go 14 KB

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