neck_ring_warning.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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.PenIds) > 0 {
  44. pref.Where("b.pen_id IN ?", req.PenIds)
  45. }
  46. // 按照发情时间和发情等级倒叙排序
  47. if req.MatingWindowPeriod > 0 {
  48. if err = pref.Group("a.cow_id").
  49. Find(&neckRingEstrusList).Error; err != nil {
  50. return nil, xerr.WithStack(err)
  51. }
  52. } else {
  53. if err = pref.Group("a.cow_id").
  54. Find(&neckRingEstrusList).Error; err != nil {
  55. return nil, xerr.WithStack(err)
  56. }
  57. }
  58. cowMap := make(map[int64]*model.Cow)
  59. eventLogMap := make(map[int64]string)
  60. cowIds := make([]int64, 0)
  61. for _, v := range neckRingEstrusList {
  62. cowIds = append(cowIds, v.CowId)
  63. }
  64. if len(cowIds) > 0 {
  65. lastEventLogList := s.GetCowLastEventByCowIds(userModel.AppPasture.Id, cowIds, pasturePb.EventCategory_Breed)
  66. for _, log := range lastEventLogList {
  67. eventLogMap[log.CowId] = log.EventDescription
  68. }
  69. cowList, _ := s.GetCowInfoByCowIds(ctx, userModel.AppPasture.Id, cowIds)
  70. for _, cow := range cowList {
  71. cowMap[cow.Id] = cow
  72. }
  73. }
  74. list := model.NeckRingEstrusWarningSlice(neckRingEstrusList).ToPB(cowMap, eventLogMap, req.MatingWindowPeriod)
  75. // 排序 先按照高峰时间正序排,然后再按照发情等级倒叙排
  76. sort.Slice(list, func(i, j int) bool {
  77. if list[i].PostPeakTimeForHours != list[j].PostPeakTimeForHours {
  78. return list[i].PostPeakTimeForHours < list[j].PostPeakTimeForHours
  79. }
  80. return list[i].Level > list[j].Level
  81. })
  82. // 分页
  83. count = int32(len(list))
  84. if count > pagination.PageOffset {
  85. end := pagination.PageOffset + pagination.PageSize
  86. if end > count {
  87. end = count
  88. }
  89. list = list[pagination.PageOffset:end]
  90. } else {
  91. // 如果偏移量已超过列表长度,返回空列表
  92. list = list[:0]
  93. }
  94. return &pasturePb.EstrusResponse{
  95. Code: http.StatusOK,
  96. Msg: "ok",
  97. Data: &pasturePb.EstrusData{
  98. List: list,
  99. Total: 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. }
  155. return &pasturePb.HealthWarningResponse{
  156. Code: http.StatusOK,
  157. Msg: "ok",
  158. Data: &pasturePb.HealthWarningData{
  159. Total: int32(count),
  160. Page: pagination.Page,
  161. PageSize: pagination.PageSize,
  162. List: model.NeckRingHealthWarningSlice(neckWaringHealthList).ToPB(
  163. warningHealthLevelMap,
  164. cowMap,
  165. eventLogMap,
  166. healthStatusMap,
  167. ),
  168. },
  169. }, nil
  170. }
  171. func (s *StoreEntry) NeckRingNoEstrusBatch(ctx context.Context, req *pasturePb.NeckRingNoEstrusBatchRequest) error {
  172. userModel, err := s.GetUserModel(ctx)
  173. if err != nil {
  174. return xerr.WithStack(err)
  175. }
  176. if len(req.EarNumbers) <= 0 {
  177. messageId, _ := userModel.LanguageContent.Localize(&i18n.LocalizeConfig{
  178. MessageID: "cow.earNumber",
  179. })
  180. return xerr.Custom(messageId)
  181. }
  182. nowTime := time.Now().Local()
  183. startTime := nowTime.AddDate(0, 0, -1).Format(model.LayoutDate2)
  184. endTime := nowTime.AddDate(0, 0, 1).Format(model.LayoutDate2)
  185. startTimeUnix := util.TimeParseLocalUnix(startTime)
  186. endTimeUnix := util.TimeParseLocalUnix(endTime)
  187. startTime = time.Unix(startTimeUnix, 0).Local().Format(model.LayoutTime)
  188. endTime = time.Unix(endTimeUnix, 0).Local().Format(model.LayoutTime)
  189. neckRingEstrusWarningList := make([]*model.NeckRingEstrusWarning, 0)
  190. if err = s.DB.Model(new(model.NeckRingEstrusWarning)).
  191. Where("pasture_id = ?", userModel.AppPasture.Id).
  192. Where("date_time BETWEEN ? AND ?", startTime, endTime).
  193. Where("ear_number IN ?", req.EarNumbers).
  194. Where("is_show = ?", pasturePb.IsShow_Ok).
  195. Find(&neckRingEstrusWarningList).Error; err != nil {
  196. return xerr.WithStack(err)
  197. }
  198. if len(neckRingEstrusWarningList) <= 0 {
  199. return nil
  200. }
  201. neckRingEstrusIds := make([]int64, 0)
  202. for _, v := range neckRingEstrusWarningList {
  203. neckRingEstrus := &model.NeckRingEstrus{}
  204. if err = s.DB.Model(new(model.NeckRingEstrus)).
  205. Where("pasture_id = ?", userModel.AppPasture.Id).
  206. Where("id = ?", v.NeckRingEstrusId).
  207. Where("is_show = ?", pasturePb.IsShow_Ok).
  208. First(neckRingEstrus).Error; err != nil {
  209. zaplog.Error("NeckRingNoEstrusBatch", zap.Any("err", err), zap.Any("neckRingEstrusWarning", v))
  210. messageId, _ := userModel.LanguageContent.Localize(&i18n.LocalizeConfig{
  211. MessageID: "cow.dataError",
  212. TemplateData: map[string]interface{}{
  213. "earNumber": v.EarNumber,
  214. },
  215. })
  216. return xerr.Customf(messageId)
  217. }
  218. neckRingEstrusIds = append(neckRingEstrusIds, neckRingEstrus.Id)
  219. }
  220. if len(neckRingEstrusIds) <= 0 {
  221. return nil
  222. }
  223. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  224. for _, id := range neckRingEstrusIds {
  225. if err = tx.Model(new(model.NeckRingEstrus)).
  226. Where("id = ?", id).
  227. Updates(map[string]interface{}{
  228. "check_result": pasturePb.CheckResult_Fail,
  229. "check_user_id": userModel.SystemUser.Id,
  230. "check_user_name": userModel.SystemUser.Name,
  231. "check_at": time.Now().Local().Unix(),
  232. "is_show": pasturePb.IsShow_No,
  233. }).Error; err != nil {
  234. return xerr.WithStack(err)
  235. }
  236. if err = tx.Model(new(model.NeckRingEstrusWarning)).
  237. Where("neck_ring_estrus_id = ?", id).
  238. Updates(map[string]interface{}{
  239. "is_show": pasturePb.IsShow_No,
  240. }).Error; err != nil {
  241. return xerr.WithStack(err)
  242. }
  243. }
  244. return nil
  245. }); err != nil {
  246. return xerr.WithStack(err)
  247. }
  248. return nil
  249. }
  250. func (s *StoreEntry) NeckRingNoDiseaseBatch(ctx context.Context, req *pasturePb.NeckRingNoEstrusBatchRequest) error {
  251. userModel, err := s.GetUserModel(ctx)
  252. if err != nil {
  253. return xerr.WithStack(err)
  254. }
  255. if len(req.EarNumbers) <= 0 {
  256. messageId, _ := userModel.LanguageContent.Localize(&i18n.LocalizeConfig{
  257. MessageID: "cow.earNumber",
  258. })
  259. return xerr.Custom(messageId)
  260. }
  261. nowTime := time.Now().Local()
  262. startTime := nowTime.AddDate(0, 0, -1).Format(model.LayoutDate2)
  263. endTime := nowTime.Format(model.LayoutDate2)
  264. neckRingHealthWarningList := make([]*model.NeckRingHealthWarning, 0)
  265. if err = s.DB.Model(new(model.NeckRingHealthWarning)).
  266. Where("pasture_id = ?", userModel.AppPasture.Id).
  267. Where("heat_date BETWEEN ? AND ?", startTime, endTime).
  268. Where("ear_number IN ?", req.EarNumbers).
  269. Where("is_show = ?", pasturePb.IsShow_Ok).
  270. Find(&neckRingHealthWarningList).Error; err != nil {
  271. return xerr.WithStack(err)
  272. }
  273. if len(neckRingHealthWarningList) <= 0 {
  274. return nil
  275. }
  276. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  277. for _, v := range neckRingHealthWarningList {
  278. if err = tx.Model(new(model.NeckRingHealth)).
  279. Where("pasture_id = ?", userModel.AppPasture.Id).
  280. Where("heat_date = ?", v.HeatDate).
  281. Where("cow_id = ?", v.CowId).
  282. Updates(map[string]interface{}{
  283. "check_result": pasturePb.CheckResult_Fail,
  284. "check_user_id": userModel.SystemUser.Id,
  285. "check_user_name": userModel.SystemUser.Name,
  286. "check_at": time.Now().Local().Unix(),
  287. "is_show": pasturePb.IsShow_No,
  288. }).Error; err != nil {
  289. return xerr.WithStack(err)
  290. }
  291. if err = tx.Model(new(model.NeckRingHealthWarning)).
  292. Where("neck_ring_health_id = ?", v.NeckRingHealthId).
  293. Updates(map[string]interface{}{
  294. "is_show": pasturePb.IsShow_No,
  295. }).Error; err != nil {
  296. return xerr.WithStack(err)
  297. }
  298. }
  299. return nil
  300. }); err != nil {
  301. return xerr.WithStack(err)
  302. }
  303. return nil
  304. }
  305. func (s *StoreEntry) EstrusWarningQuery(ctx context.Context, pastureId int64) (*gorm.DB, error) {
  306. nowTime := time.Now().Local()
  307. startTime := time.Unix(util.TimeParseLocalUnix(nowTime.AddDate(0, 0, -1).Format(model.LayoutDate2)), 0).Format(model.LayoutTime)
  308. entTime := time.Unix(util.TimeParseLocalEndUnix(nowTime.Format(model.LayoutDate2)), 0).Format(model.LayoutTime)
  309. systemBasic, err := s.FindSystemBasic(ctx, pastureId, model.EstrusWaringDays)
  310. if err != nil {
  311. return nil, xerr.WithStack(err)
  312. }
  313. return s.DB.Table(fmt.Sprintf("%s as a", new(model.NeckRingEstrusWarning).TableName())).
  314. Joins(fmt.Sprintf("JOIN %s AS b on a.cow_id = b.id", new(model.Cow).TableName())).
  315. Where("b.last_mating_at < UNIX_TIMESTAMP(a.date_time)").
  316. Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
  317. Where("b.is_forbidden_mating = ?", pasturePb.IsShow_No).
  318. Where("a.level >= ?", pasturePb.EstrusLevel_Low).
  319. Where("a.pasture_id = ?", pastureId).
  320. Where("a.date_time BETWEEN ? AND ?", startTime, entTime).
  321. Where(s.DB.Where("b.last_mating_at < UNIX_TIMESTAMP(a.first_time)").
  322. Or(s.DB.Where("b.last_mating_at = ?", 0).
  323. Where("b.calving_age > ?", systemBasic.MinValue).
  324. Or("b.lact = ?", 0))).
  325. Where("a.is_show = ?", pasturePb.IsShow_Ok), nil
  326. }
  327. func (s *StoreEntry) AbortionWarningQuery(ctx context.Context, pastureId int64) (*gorm.DB, error) {
  328. return s.DB.Table(fmt.Sprintf("%s as a", new(model.NeckRingEstrusWarning).TableName())).
  329. Joins(fmt.Sprintf("JOIN %s AS b on a.cow_id = b.id", new(model.Cow).TableName())).
  330. Where("b.pregnancy_age BETWEEN ? AND ?", 1, 260).
  331. Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
  332. Where("b.is_pregnant = ?", pasturePb.IsShow_Ok).
  333. Where("a.level >= ?", pasturePb.EstrusLevel_Middle).
  334. Where("a.pasture_id = ?", pastureId).
  335. Where("a.is_show = ?", pasturePb.IsShow_Ok), nil
  336. }
  337. func (s *StoreEntry) DataNoticeDetail(ctx context.Context) *model.DataNoticeResponse {
  338. res := &model.DataNoticeResponse{
  339. Code: http.StatusOK,
  340. Msg: "ok",
  341. Data: make([]*model.NoticeContent, 0),
  342. }
  343. userModel, err := s.GetUserModel(ctx)
  344. if err != nil {
  345. return res
  346. }
  347. pastureId := userModel.AppPasture.Id
  348. nowTime := time.Now().Local().Format(model.LayoutDate2)
  349. noticeList := make([]*model.DataNotice, 0)
  350. if err = s.DB.Model(new(model.DataNotice)).
  351. Where("pasture_id = ?", pastureId).
  352. Where("is_show = ?", pasturePb.IsShow_Ok).
  353. Where("start_date >= ? AND end_date <= ?", nowTime, nowTime).
  354. Order("id desc").
  355. Group("notice_kind").
  356. Find(&noticeList).Error; err != nil {
  357. return res
  358. }
  359. res.Data = model.DataNoticeSlice(noticeList).ToPB(userModel.SystemUser.Id)
  360. return res
  361. }
  362. func (s *StoreEntry) DataNoticeKnown(ctx context.Context, dataNoticeId int64) error {
  363. userModel, err := s.GetUserModel(ctx)
  364. if err != nil {
  365. return xerr.WithStack(err)
  366. }
  367. pastureId := userModel.AppPasture.Id
  368. dataNotice := model.DataNotice{}
  369. if err = s.DB.Model(new(model.DataNotice)).
  370. Where("id = ? and pasture_id = ?", dataNoticeId, pastureId).
  371. First(&dataNotice).Error; err != nil {
  372. return xerr.WithStack(err)
  373. }
  374. newKnownUsers := ""
  375. if len(dataNotice.KnownUsers) > 0 {
  376. newKnownUsers = fmt.Sprintf("%s,%d", dataNotice.KnownUsers, userModel.SystemUser.Id)
  377. } else {
  378. newKnownUsers = fmt.Sprintf("%d", userModel.SystemUser.Id)
  379. }
  380. if err = s.DB.Model(new(model.DataNotice)).
  381. Where("id = ?", dataNotice.Id).
  382. Select("known_users").
  383. Update("known_users", newKnownUsers).Error; err != nil {
  384. return xerr.WithStack(err)
  385. }
  386. return nil
  387. }