event_breed.go 22 KB

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