neck_ring_warning.go 12 KB

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