event_breed.go 22 KB

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