event_breed.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. package backend
  2. import (
  3. "context"
  4. "fmt"
  5. "kpt-pasture/model"
  6. "kpt-pasture/util"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  12. "go.uber.org/zap"
  13. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  14. "gitee.com/xuyiping_admin/pkg/xerr"
  15. "gorm.io/gorm"
  16. )
  17. func (s *StoreEntry) CalvingList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchLavingEventResponse, error) {
  18. userModel, err := s.GetUserModel(ctx)
  19. if err != nil {
  20. return nil, xerr.WithStack(err)
  21. }
  22. lavingList := make([]*model.EventCalvingList, 0)
  23. var count int64 = 0
  24. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventCalving).TableName())).
  25. Select(`a.*,b.name as pen_name,c.name as staff_member_name`).
  26. Joins(fmt.Sprintf("JOIN %s AS b on a.pen_id = b.id", new(model.Pen).TableName())).
  27. Joins(fmt.Sprintf("JOIN %s AS c on a.operation_id = c.id", new(model.SystemUser).TableName())).
  28. Where("a.pasture_id = ?", userModel.AppPasture.Id).Where("a.status = ?", pasturePb.IsShow_No)
  29. if len(req.CowId) > 0 {
  30. cowIds := strings.Split(req.CowId, ",")
  31. pref.Where("a.cow_id IN ?", cowIds)
  32. }
  33. if err = pref.Order("a.id desc").
  34. Count(&count).Limit(int(pagination.PageSize)).
  35. Offset(int(pagination.PageOffset)).
  36. Find(&lavingList).Error; err != nil {
  37. return nil, xerr.WithStack(err)
  38. }
  39. calvingIds := make([]int64, 0)
  40. for _, v := range lavingList {
  41. calvingIds = append(calvingIds, v.Id)
  42. }
  43. calvingCalfList := make([]*model.CalvingCalf, 0)
  44. if err = s.DB.Model(new(model.CalvingCalf)).
  45. Where("calving_id IN ?", calvingIds).
  46. Find(&calvingCalfList).Error; err != nil {
  47. return nil, xerr.WithStack(err)
  48. }
  49. return &pasturePb.SearchLavingEventResponse{
  50. Code: http.StatusOK,
  51. Msg: "ok",
  52. Data: &pasturePb.SearchLavingData{
  53. List: model.EventCalvingListSlice(lavingList).ToPB(calvingCalfList),
  54. Total: int32(count),
  55. PageSize: pagination.PageSize,
  56. Page: pagination.Page,
  57. },
  58. }, nil
  59. }
  60. func (s *StoreEntry) CalvingCreate(ctx context.Context, req *pasturePb.EventCalving) (err error) {
  61. userModel, err := s.GetUserModel(ctx)
  62. if err != nil {
  63. return xerr.WithStack(err)
  64. }
  65. cow, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(req.CowId))
  66. if err != nil {
  67. zaplog.Error("CalvingCreate", zap.Any("cow_id", req.CowId), zap.Any("err", err))
  68. return xerr.Custom("请选择相关牛只")
  69. }
  70. operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
  71. if err != nil {
  72. return xerr.Customf("获取操作人员信息失败: %s", err.Error())
  73. }
  74. req.OperationName = operationUser.Name
  75. penMap := s.PenMap(ctx, userModel.AppPasture.Id)
  76. // 记录牛只事件日志
  77. defer func() {
  78. if err == nil {
  79. // 母牛事件日志
  80. cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, cow, pasturePb.EventType_Calving, pasturePb.ExposeEstrusType_Invalid, req)
  81. s.DB.Table(cowLogs.TableName()).Create(cowLogs)
  82. // 犊牛事件日志
  83. for _, v := range req.CalfItemList {
  84. if v.IsLive == pasturePb.IsShow_No || v.IsAdoption == pasturePb.IsShow_No {
  85. continue
  86. }
  87. cow, _ = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(v.CowId))
  88. cowLogs = s.SubmitEventLog(ctx, userModel.AppPasture.Id, cow, pasturePb.EventType_Birth, pasturePb.ExposeEstrusType_Invalid, v)
  89. s.DB.Table(cowLogs.TableName()).Create(cowLogs)
  90. }
  91. }
  92. }()
  93. newEventCalving := &model.EventCalving{}
  94. if err = s.DB.Model(new(model.EventCalving)).
  95. Where("cow_id = ?", cow.Id).
  96. Where("lact = ?", cow.Lact).
  97. First(newEventCalving).Error; err != nil {
  98. return xerr.Custom("该母牛信息不存在")
  99. }
  100. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  101. // 更新产犊事件表
  102. newEventCalving.EventUpdate(operationUser, req, cow)
  103. if err = tx.Model(new(model.EventCalving)).
  104. Select("operation_id", "operation_name", "reality_day", "day_age", "pregnancy_age", "bull_number",
  105. "calving_level", "child_number", "status", "is_inducing_childbirth", "pen_id", "dystocia_reason", "remarks").
  106. Where("id = ?", newEventCalving.Id).
  107. Updates(newEventCalving).Error; err != nil {
  108. return xerr.WithStack(err)
  109. }
  110. for _, v := range req.CalfItemList {
  111. if v.IsLive == pasturePb.IsShow_No || v.IsAdoption == pasturePb.IsShow_No {
  112. continue
  113. }
  114. // 犊牛信息
  115. newCalvingCalf := model.NewEventCalvingCalf(userModel.AppPasture.Id, int64(req.CowId), newEventCalving.Id, int64(req.CalvingAt), penMap, v)
  116. // 留养犊牛
  117. newCow := model.NewCalfCow(cow.Id, cow.LastBullNumber, newCalvingCalf)
  118. if err = tx.Create(newCow).Error; err != nil {
  119. return xerr.WithStack(err)
  120. }
  121. v.CowId = int32(newCow.Id)
  122. if err = tx.Create(newCalvingCalf).Error; err != nil {
  123. return xerr.WithStack(err)
  124. }
  125. }
  126. // 更新母牛信息
  127. cow.EventCalvingUpdate(int64(req.CalvingAt))
  128. if err = tx.Model(cow).
  129. Select("calving_age", "mating_times", "pregnancy_age", "lact", "breed_status", "is_pregnant", "last_calving_at").
  130. Where("id = ?", cow.Id).
  131. Updates(cow).Error; err != nil {
  132. return xerr.WithStack(err)
  133. }
  134. return nil
  135. }); err != nil {
  136. return xerr.WithStack(err)
  137. }
  138. return nil
  139. }
  140. func (s *StoreEntry) SameTimeCreate(ctx context.Context, req *pasturePb.EventSameTime) (err error) {
  141. userModel, err := s.GetUserModel(ctx)
  142. if err != nil {
  143. return xerr.WithStack(err)
  144. }
  145. operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
  146. if err != nil {
  147. return xerr.WithStack(err)
  148. }
  149. eventCowSameTime, err := s.GetEventCowSameTimeByCowId(ctx, userModel.AppPasture.Id, int64(req.CowId))
  150. if err != nil {
  151. zaplog.Error("SameTimeCreate", zap.Any("err", err), zap.Any("req", req))
  152. return xerr.Customf("异常数据")
  153. }
  154. drugs := &model.Drugs{}
  155. if drugs, err = s.GetDrugsById(ctx, userModel.AppPasture.Id, int64(req.DrugsId)); err != nil {
  156. zaplog.Error("SameTimeCreate", zap.Any("err", err), zap.Any("req", req))
  157. return xerr.Customf("该药品不存在: %d", req.DrugsId)
  158. }
  159. req.DrugsName = drugs.Name
  160. eventCowSameTime.EventUpdate(drugs, req.Usage, req.Remarks, operationUser, userModel.SystemUser)
  161. defer func() {
  162. if err == nil {
  163. // 记录牛只事件日志
  164. cow, _ := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, eventCowSameTime.CowId)
  165. cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, cow, pasturePb.EventType_Seme_Time, pasturePb.ExposeEstrusType_Same_Time, req)
  166. s.DB.Table(cowLogs.TableName()).Create(cowLogs)
  167. }
  168. }()
  169. if err = s.DB.Model(new(model.EventCowSameTime)).
  170. Select("status", "drugs_id", "unit", "usage", "remarks", "operation_id", "operation_name").
  171. Where("id = ?", eventCowSameTime.Id).
  172. Updates(eventCowSameTime).Error; err != nil {
  173. return xerr.WithStack(err)
  174. }
  175. return nil
  176. }
  177. func (s *StoreEntry) SameTimeBatch(ctx context.Context, req *pasturePb.EventSameTimeBatch) (err error) {
  178. userModel, err := s.GetUserModel(ctx)
  179. if err != nil {
  180. return xerr.WithStack(err)
  181. }
  182. operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
  183. if err != nil {
  184. return xerr.Customf("异常数据")
  185. }
  186. req.OperationName = operationUser.Name
  187. drugs := &model.Drugs{}
  188. if drugs, err = s.GetDrugsById(ctx, userModel.AppPasture.Id, int64(req.DrugsId)); err != nil {
  189. zaplog.Error("SameTimeBatch", zap.Any("err", err), zap.Any("req", req))
  190. return xerr.Customf("该药物不存在: %d", req.DrugsId)
  191. }
  192. req.DrugsName = drugs.Name
  193. eventCowSameTimeList := make([]*model.EventCowSameTime, 0)
  194. for _, v := range req.CowIds {
  195. eventCowSameTime, err := s.GetEventCowSameTimeByCowId(ctx, userModel.AppPasture.Id, int64(v))
  196. if err != nil {
  197. zaplog.Error("SameTimeCreate", zap.Any("err", err), zap.Any("req", req))
  198. return xerr.WithStack(err)
  199. }
  200. eventCowSameTimeList = append(eventCowSameTimeList, eventCowSameTime)
  201. }
  202. defer func() {
  203. // 记录牛只事件日志
  204. if err == nil {
  205. for _, v := range eventCowSameTimeList {
  206. cow, _ := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, v.CowId)
  207. cowLogs := s.SubmitEventLog(
  208. ctx,
  209. userModel.AppPasture.Id,
  210. cow,
  211. pasturePb.EventType_Seme_Time,
  212. pasturePb.ExposeEstrusType_Same_Time,
  213. &pasturePb.EventSameTime{
  214. Id: int32(v.Id),
  215. CowId: int32(v.CowId),
  216. SameTimeId: int32(v.SameTimeId),
  217. SameTimeType: v.SameTimeType,
  218. SameTimeTypeName: v.SameTimeName,
  219. DrugsId: int32(v.DrugsId),
  220. DrugsName: drugs.Name,
  221. Usage: req.Usage,
  222. OperationId: int32(operationUser.Id),
  223. OperationName: operationUser.Name,
  224. SameTimeAt: req.SameTimeAt,
  225. })
  226. s.DB.Table(cowLogs.TableName()).Create(cowLogs)
  227. }
  228. }
  229. }()
  230. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  231. for _, v := range eventCowSameTimeList {
  232. // 更新SameTime
  233. v.EventUpdate(drugs, req.Usage, req.Remarks, userModel.SystemUser, operationUser)
  234. if err = tx.Model(new(model.EventCowSameTime)).
  235. Select("status", "drugs_id", "unit", "usage", "remarks", "operation_id", "operation_name").
  236. Where("id = ?", v.Id).
  237. Updates(v).Error; err != nil {
  238. return xerr.WithStack(err)
  239. }
  240. }
  241. return nil
  242. }); err != nil {
  243. return xerr.WithStack(err)
  244. }
  245. return nil
  246. }
  247. func (s *StoreEntry) SameTimeList(
  248. ctx context.Context,
  249. req *pasturePb.SearchEventRequest,
  250. pagination *pasturePb.PaginationModel,
  251. ) (*pasturePb.SearchSameTimeResponse, error) {
  252. userModel, err := s.GetUserModel(ctx)
  253. if err != nil {
  254. return nil, xerr.WithStack(err)
  255. }
  256. cowSameTimeList := make([]*model.EventCowSameTime, 0)
  257. var count int64 = 0
  258. pref := s.DB.Table(new(model.EventCowSameTime).TableName()).Where("pasture_id = ?", userModel.AppPasture.Id)
  259. if req.CowId != "" {
  260. cowIds := strings.Split(req.CowId, ",")
  261. pref.Where("cow_id IN ?", cowIds)
  262. }
  263. if err = pref.Count(&count).
  264. Limit(int(pagination.PageSize)).
  265. Offset(int(pagination.PageOffset)).
  266. Find(&cowSameTimeList).Error; err != nil {
  267. return nil, xerr.WithStack(err)
  268. }
  269. sameTimeTypeMap := s.SameTimeTypeMap()
  270. return &pasturePb.SearchSameTimeResponse{
  271. Code: http.StatusOK,
  272. Msg: "ok",
  273. Data: &pasturePb.SameTimeData{
  274. List: model.EventCowSameTimeSlice(cowSameTimeList).ToPB(sameTimeTypeMap),
  275. Total: int32(count),
  276. PageSize: pagination.PageSize,
  277. Page: pagination.Page,
  278. },
  279. }, nil
  280. }
  281. func (s *StoreEntry) EstrusList(ctx context.Context, req *pasturePb.EstrusItemsRequest, pagination *pasturePb.PaginationModel) (*pasturePb.EventEstrusResponse, error) {
  282. userModel, err := s.GetUserModel(ctx)
  283. if err != nil {
  284. return nil, xerr.WithStack(err)
  285. }
  286. estrusList := make([]*model.EventEstrus, 0)
  287. var count int64 = 0
  288. pref := s.DB.Table(new(model.EventEstrus).TableName()).
  289. Where("is_show = ?", pasturePb.IsShow_Ok).
  290. Where("pasture_id = ?", userModel.AppPasture.Id).
  291. Where("expose_estrus_type = ?", pasturePb.ExposeEstrusType_Natural_Estrus)
  292. if len(req.CowIds) > 0 {
  293. cowIds := strings.Split(util.ArrayInt32ToStrings(req.CowIds, ","), ",")
  294. pref.Where("cow_id IN ?", cowIds)
  295. }
  296. if req.Level > 0 {
  297. pref.Where("level = ?", req.Level)
  298. }
  299. if len(req.PenIds) > 0 {
  300. penIds := strings.Split(util.ArrayInt32ToStrings(req.PenIds, ","), ",")
  301. pref.Where("pen_id IN ?", penIds)
  302. }
  303. if err = pref.Order("id desc").
  304. Count(&count).Limit(int(pagination.PageSize)).
  305. Offset(int(pagination.PageOffset)).
  306. Find(&estrusList).Error; err != nil {
  307. return nil, xerr.WithStack(err)
  308. }
  309. getCowInfoByCowId := GetCowInfoByCowId
  310. getCowLastEvent := GetCowLastEvent
  311. return &pasturePb.EventEstrusResponse{
  312. Code: http.StatusOK,
  313. Msg: "ok",
  314. Data: &pasturePb.EstrusItemsData{
  315. List: model.EstrusSlice(estrusList).ToPB(s.DB, getCowInfoByCowId, getCowLastEvent),
  316. Total: int32(count),
  317. PageSize: pagination.PageSize,
  318. Page: pagination.Page,
  319. },
  320. }, nil
  321. }
  322. func (s *StoreEntry) EstrusBatchMating(ctx context.Context, req *pasturePb.EventEstrus) (err error) {
  323. userModel, err := s.GetUserModel(ctx)
  324. if err != nil {
  325. return xerr.WithStack(err)
  326. }
  327. operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
  328. if err != nil {
  329. return xerr.Customf("该用户不存在: %d", req.OperationId)
  330. }
  331. req.OperationName = operationUser.Name
  332. eventEstrusIds := make([]string, 0)
  333. eventMatingList := make([]*model.EventMating, 0)
  334. cowIds := make([]int32, 0)
  335. for _, cowId := range req.CowIds {
  336. cowInfo := GetCowInfoByCowId(s.DB, int64(cowId))
  337. if cowInfo == nil {
  338. return xerr.Custom("牛只信息不存在")
  339. }
  340. newEventMating := model.NewEventMating(userModel.AppPasture.Id, cowInfo, time.Now().Unix(), pasturePb.ExposeEstrusType_Neck_Ring)
  341. eventEstrus, ok, err := s.FindEventEstrusByCowId(ctx, userModel.AppPasture.Id, int64(cowId))
  342. if err != nil {
  343. return xerr.WithStack(err)
  344. }
  345. if !ok {
  346. continue
  347. }
  348. newEventMating.EventEstrusId = eventEstrus.Id
  349. eventEstrusIds = append(eventEstrusIds, strconv.FormatInt(eventEstrus.Id, 10))
  350. eventMatingList = append(eventMatingList, newEventMating)
  351. cowIds = append(cowIds, cowId)
  352. }
  353. if len(eventMatingList) <= 0 {
  354. return nil
  355. }
  356. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  357. if len(eventEstrusIds) > 0 {
  358. if err = tx.Model(new(model.EventEstrus)).
  359. Where("id IN ?", eventEstrusIds).
  360. Updates(map[string]interface{}{
  361. "is_show": pasturePb.IsShow_No,
  362. "check_result": pasturePb.CheckResult_Correct,
  363. }).Error; err != nil {
  364. return xerr.WithStack(err)
  365. }
  366. }
  367. if len(eventMatingList) > 0 {
  368. if err = tx.Create(eventMatingList).Error; err != nil {
  369. return xerr.WithStack(err)
  370. }
  371. }
  372. return nil
  373. }); err != nil {
  374. return xerr.WithStack(err)
  375. }
  376. // 配种信息
  377. eventMating := &pasturePb.EventMating{
  378. CowIds: cowIds,
  379. FrozenSemenNumber: req.BullNumber,
  380. FrozenSemenCount: req.Quantity,
  381. OperationId: req.OperationId,
  382. Remarks: req.Remarks,
  383. MatingAt: req.MatingAt,
  384. ExposeEstrusType: pasturePb.ExposeEstrusType_Neck_Ring,
  385. }
  386. if err = s.MatingCreate(ctx, eventMating); err != nil {
  387. zaplog.Error("EstrusBatchMating", zap.Any("MatingCreate", err), zap.Any("eventMating", eventMating))
  388. return xerr.WithStack(err)
  389. }
  390. return nil
  391. }
  392. func (s *StoreEntry) MatingList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.EventMatingResponse, error) {
  393. userModel, err := s.GetUserModel(ctx)
  394. if err != nil {
  395. return nil, xerr.WithStack(err)
  396. }
  397. matingList := make([]*model.EventMating, 0)
  398. var count int64 = 0
  399. pref := s.DB.Model(new(model.EventMating)).
  400. Where("mating_result > ?", pasturePb.MatingResult_Invalid).
  401. Where("status = ?", pasturePb.IsShow_Ok).
  402. Where("pasture_id = ?", userModel.AppPasture.Id)
  403. if len(req.CowId) > 0 {
  404. cowIds := strings.Split(req.CowId, ",")
  405. pref.Where("cow_id IN ?", cowIds)
  406. }
  407. if err = pref.Order("id desc").
  408. Count(&count).Limit(int(pagination.PageSize)).
  409. Offset(int(pagination.PageOffset)).
  410. Find(&matingList).Error; err != nil {
  411. return nil, xerr.WithStack(err)
  412. }
  413. exposeEstrusTypeMap := s.ExposeEstrusTypeMap()
  414. return &pasturePb.EventMatingResponse{
  415. Code: http.StatusOK,
  416. Msg: "ok",
  417. Data: &pasturePb.SearchMatingData{
  418. List: model.EventMatingSlice(matingList).ToPB(exposeEstrusTypeMap),
  419. Total: int32(count),
  420. PageSize: pagination.PageSize,
  421. Page: pagination.Page,
  422. },
  423. }, nil
  424. }
  425. // MatingCreate 牛只配种
  426. func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMating) (err error) {
  427. eventCheckModel, err := s.MatingCreateCheck(ctx, req)
  428. if err != nil {
  429. return xerr.WithStack(err)
  430. }
  431. req.OperationName = eventCheckModel.OperationUser.Name
  432. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  433. for _, cow := range eventCheckModel.CowList {
  434. // 获取牛只最近一次配种信息
  435. lastEventMating, ok, err := s.FindLastEventMatingByCowId(ctx, eventCheckModel.UserModel.AppPasture.Id, cow.Id)
  436. if err != nil {
  437. return xerr.WithStack(err)
  438. }
  439. // 1. 没有配种信息,(第一次参加配种的牛只,并且没有参与同期的牛只 )
  440. if !ok {
  441. newMating := model.NewEventMatingNaturalEstrus(eventCheckModel.UserModel.AppPasture.Id, cow, req, eventCheckModel.UserModel.SystemUser)
  442. if err = tx.Create(newMating).Error; err != nil {
  443. return xerr.WithStack(err)
  444. }
  445. if err = s.MatingCowUpdate(ctx, eventCheckModel.UserModel.AppPasture.Id, cow, req, false); err != nil {
  446. return xerr.WithStack(err)
  447. }
  448. continue
  449. }
  450. // 2. 所有有配种数据的牛只
  451. if lastEventMating == nil || lastEventMating.Id <= 0 {
  452. zaplog.Error("MatingCreate", zap.Any("cow", cow), zap.Any("UserModel", eventCheckModel.UserModel))
  453. return xerr.Customf("异常牛数据: %d", cow.Id)
  454. }
  455. // 2.1 复配 => 本胎次配次不加1
  456. isReMating := lastEventMating.IsReMating(cow, int64(req.MatingAt))
  457. if isReMating {
  458. lastEventMating.EventReMatingUpdate(int64(req.MatingAt))
  459. if err = tx.Model(lastEventMating).
  460. Select("mating_result", "mating_result_at", "status").
  461. Where("id = ?", lastEventMating.Id).
  462. Updates(lastEventMating).Error; err != nil {
  463. }
  464. }
  465. // 2.2. 同期初配
  466. IsMatingUpdate := lastEventMating.IsMatingUpdate()
  467. if IsMatingUpdate {
  468. lastEventMating.EventUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating, eventCheckModel.OperationUser, eventCheckModel.UserModel.SystemUser)
  469. if err = tx.Model(lastEventMating).
  470. Select("mating_at", "status", "reality_day", "frozen_semen_number", "operation_id", "operation_name", "message_id", "message_name").
  471. Where("id = ?", lastEventMating.Id).
  472. Updates(lastEventMating).Error; err != nil {
  473. return xerr.WithStack(err)
  474. }
  475. }
  476. // 2.3. 提交的配种数据中,定位出空怀的牛只,
  477. isEmptyMating := lastEventMating.IsEmptyMating(cow, int64(req.MatingAt))
  478. if isEmptyMating {
  479. // 把上次配种结果信息更新成空怀
  480. lastEventMating.EventMatingResultUpdate(pasturePb.MatingResult_Empty, int64(req.MatingAt))
  481. if err = tx.Model(lastEventMating).
  482. Select("mating_result", "mating_result_at").
  483. Where("id = ?", lastEventMating.Id).
  484. Updates(lastEventMating).Error; err != nil {
  485. return xerr.WithStack(err)
  486. }
  487. // 先创建一条新的配种数据
  488. newMating := model.NewEventMating(eventCheckModel.UserModel.AppPasture.Id, cow, int64(req.MatingAt), req.ExposeEstrusType)
  489. newMating.EventUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating, eventCheckModel.OperationUser, eventCheckModel.UserModel.SystemUser)
  490. if err = tx.Model(newMating).Create(newMating).Error; err != nil {
  491. return xerr.WithStack(err)
  492. }
  493. // 更新牛只配种结果日志
  494. if err = s.UpdateMatingResultEventCowLogByCowId(ctx, cow.Id, s.MatingResultMap()[pasturePb.MatingResult_Empty]); err != nil {
  495. zaplog.Error("MatingCreate", zap.Any("UpdateEventCowLogByCowId", err), zap.Any("cow", cow))
  496. }
  497. }
  498. // 牛只基本中配种信息更新
  499. if err = s.MatingCowUpdate(ctx, eventCheckModel.UserModel.AppPasture.Id, cow, req, isReMating); err != nil {
  500. return xerr.WithStack(err)
  501. }
  502. }
  503. // 创建冻精使用记录日志
  504. itemFrozenSemenLog := model.NewEventFrozenSemenLog(eventCheckModel.FrozenSemen.PastureId, req)
  505. if err = tx.Create(itemFrozenSemenLog).Error; err != nil {
  506. return xerr.WithStack(err)
  507. }
  508. // 减去精液的数量
  509. eventCheckModel.FrozenSemen.EventQuantityUpdate(req.FrozenSemenCount)
  510. if err = tx.Model(eventCheckModel.FrozenSemen).
  511. Select("quantity").
  512. Where("id = ?", eventCheckModel.FrozenSemen.Id).
  513. Updates(eventCheckModel.FrozenSemen).Error; err != nil {
  514. return xerr.WithStack(err)
  515. }
  516. return nil
  517. }); err != nil {
  518. return xerr.WithStack(err)
  519. }
  520. return nil
  521. }
  522. func (s *StoreEntry) MatingCowUpdate(ctx context.Context, pastureId int64, cow *model.Cow, req *pasturePb.EventMating, isReMating bool) error {
  523. // 牛只基本中配种信息更新
  524. cow.EventMatingUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating)
  525. if err := s.DB.Model(cow).
  526. Select("last_mating_at", "mating_times", "last_bull_number", "first_mating_at", "is_pregnant", "breed_status").
  527. Where("id = ?", cow.Id).
  528. Updates(cow).Error; err != nil {
  529. return xerr.WithStack(err)
  530. }
  531. // 记录日志
  532. cowLogs := s.SubmitEventLog(ctx, pastureId, cow, pasturePb.EventType_Mating, req.ExposeEstrusType, req)
  533. if err := s.DB.Table(cowLogs.TableName()).Create(cowLogs).Error; err != nil {
  534. return xerr.WithStack(err)
  535. }
  536. return nil
  537. }
  538. func (s *StoreEntry) WeaningBatch(ctx context.Context, req *pasturePb.EventWeaningBatchRequest) (err error) {
  539. userModel, err := s.GetUserModel(ctx)
  540. if err != nil {
  541. return xerr.WithStack(err)
  542. }
  543. if len(req.Item) <= 0 {
  544. return nil
  545. }
  546. cowIds := make([]int64, 0)
  547. cowWeightMap := make(map[int64]float64)
  548. for _, item := range req.Item {
  549. cowIds = append(cowIds, int64(item.CowId))
  550. cowWeightMap[int64(item.CowId)] = float64(item.Weight)
  551. }
  552. eventWeaningList := make([]*model.EventWeaning, 0)
  553. if err = s.DB.Model(new(model.EventWeaning)).
  554. Where("cow_id IN ?", cowIds).
  555. Where("status = ?", pasturePb.IsShow_No).
  556. Find(&eventWeaningList).Error; err != nil {
  557. return xerr.WithStack(err)
  558. }
  559. operation, err := s.GetSystemUserById(ctx, int64(req.OperationId))
  560. if err != nil {
  561. return xerr.WithStack(err)
  562. }
  563. defer func() {
  564. if err != nil {
  565. for _, cowId := range cowIds {
  566. cow, _ := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, cowId)
  567. cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, cow, pasturePb.EventType_Weaning, pasturePb.ExposeEstrusType_Invalid, req)
  568. s.DB.Table(cowLogs.TableName()).Create(cowLogs)
  569. }
  570. }
  571. }()
  572. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  573. cowInfo := &model.Cow{}
  574. for _, v := range eventWeaningList {
  575. v.EventUpdate(int64(req.WeaningAt), req.Remarks, req.PenId, operation, userModel.SystemUser)
  576. if err = tx.Model(new(model.EventWeaning)).
  577. Select("status", "reality_day", "operation_id", "operation_name", "message_id", "message_name", "remarks", "after_pen_id").
  578. Where("id = ?", v.Id).
  579. Updates(v).Error; err != nil {
  580. return xerr.WithStack(err)
  581. }
  582. cowInfo, err = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, v.CowId)
  583. if err != nil {
  584. return xerr.WithStack(err)
  585. }
  586. cowInfo.EventWeaningUpdate(int64(req.WeaningAt), req.PenId, int64(cowWeightMap[cowInfo.Id]*1000))
  587. if err = tx.Model(new(model.Cow)).
  588. Select("pen_id", "current_weight", "weaning_at", "last_weight_at").
  589. Where("id = ?", v.CowId).
  590. Updates(cowInfo).Error; err != nil {
  591. return xerr.WithStack(err)
  592. }
  593. // 创建牛只的体重记录
  594. newEventWeight := model.NewEventWeight(
  595. userModel.AppPasture.Id,
  596. cowInfo,
  597. userModel.SystemUser,
  598. &pasturePb.EventWeight{
  599. WeightAt: req.WeaningAt,
  600. OperationId: req.OperationId,
  601. OperationName: req.OperationName,
  602. Remarks: req.Remarks,
  603. Weight: float32(cowWeightMap[cowInfo.Id]),
  604. Height: 0,
  605. })
  606. if err = tx.Create(newEventWeight).Error; err != nil {
  607. return xerr.WithStack(err)
  608. }
  609. }
  610. return nil
  611. }); err != nil {
  612. return xerr.WithStack(err)
  613. }
  614. return nil
  615. }