neck_ring_warning.go 11 KB

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