event_breed.go 21 KB

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