event_breed.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. currentUser, err := s.GetCurrentSystemUser(ctx)
  19. if err != nil {
  20. return nil, xerr.Custom("用户信息错误,请退出重新登录")
  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 = ?", currentUser.PastureId)
  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. Message: "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. currentUser, err := s.GetCurrentSystemUser(ctx)
  62. if err != nil {
  63. return xerr.Custom("用户信息错误,请退出重新登录")
  64. }
  65. cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, 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, currentUser.PastureId, 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, currentUser, 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, currentUser.PastureId, int64(v.CowId))
  87. cowLogs = s.SubmitEventLog(ctx, currentUser, 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(currentUser.PastureId, 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. currentUser, err := s.GetCurrentSystemUser(ctx)
  141. if err != nil {
  142. return xerr.Custom("当前用户信息错误,请退出重新登录")
  143. }
  144. operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
  145. if err != nil {
  146. return xerr.WithStack(err)
  147. }
  148. eventCowSameTime, err := s.GetEventCowSameTimeByCowId(ctx, currentUser.PastureId, 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, currentUser.PastureId, 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, currentUser)
  160. defer func() {
  161. if err == nil {
  162. // 记录牛只事件日志
  163. cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, eventCowSameTime.CowId)
  164. cowLogs := s.SubmitEventLog(ctx, currentUser, 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. currentUser, err := s.GetCurrentSystemUser(ctx)
  178. if err != nil {
  179. return xerr.Custom("当前用户信息错误,请退出重新登录")
  180. }
  181. operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, 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, currentUser.PastureId, 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, currentUser.PastureId, 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, currentUser.PastureId, v.CowId)
  206. cowLogs := s.SubmitEventLog(
  207. ctx,
  208. currentUser,
  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, currentUser, 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. currentUser, err := s.GetCurrentSystemUser(ctx)
  252. if err != nil {
  253. return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
  254. }
  255. cowSameTimeList := make([]*model.EventCowSameTime, 0)
  256. var count int64 = 0
  257. pref := s.DB.Table(new(model.EventCowSameTime).TableName()).Where("pasture_id = ?", currentUser.PastureId)
  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. Message: "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. currentUser, err := s.GetCurrentSystemUser(ctx)
  282. if err != nil {
  283. return nil, xerr.Custom("用户信息错误,请退出重新登录")
  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 = ?", currentUser.PastureId)
  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. Message: "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. currentUser, err := s.GetCurrentSystemUser(ctx)
  322. if err != nil {
  323. return xerr.Custom("当前用户信息错误,请退出重新登录")
  324. }
  325. operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, 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(currentUser.PastureId, cowInfo, time.Now().Unix(), pasturePb.ExposeEstrusType_Neck_Ring)
  339. eventEstrus, ok, err := s.FindEventEstrusByCowId(ctx, currentUser.PastureId, 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. "result": pasturePb.EstrusResult_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. currentUser, err := s.GetCurrentSystemUser(ctx)
  392. if err != nil {
  393. return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
  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 = ?", currentUser.PastureId)
  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. Message: "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. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  430. for _, cow := range eventCheckModel.CowList {
  431. lastEventMating, ok, err := s.FindLastEventMatingByCowId(ctx, eventCheckModel.CurrentUser.PastureId, cow.Id)
  432. if err != nil {
  433. return xerr.WithStack(err)
  434. }
  435. var (
  436. newMating *model.EventMating
  437. isReMating = false
  438. isEmptyMating = false
  439. )
  440. // 1. 自然发情牛只,未经过同期的牛只和未佩戴脖环的牛只
  441. if !ok {
  442. newMating = model.NewEventMatingNaturalEstrus(cow, req, eventCheckModel.CurrentUser)
  443. if err = tx.Create(newMating).Error; err != nil {
  444. return xerr.WithStack(err)
  445. }
  446. } else {
  447. // 2. 所有有配种数据的牛只
  448. if lastEventMating == nil || lastEventMating.Id <= 0 {
  449. zaplog.Error("MatingCreate", zap.Any("cow", cow), zap.Any("CurrentUser", eventCheckModel.CurrentUser))
  450. continue
  451. }
  452. // 复配 => 本胎次配次不加1
  453. isReMating = lastEventMating.IsReMating(cow, int64(req.MatingAt))
  454. // 空怀
  455. isEmptyMating = lastEventMating.IsEmptyMating(cow, int64(req.MatingAt))
  456. // 2。1. 提交的配种数据中,定位出空怀的牛只,
  457. if isEmptyMating {
  458. // 把上次配种结果信息更新成空怀
  459. lastEventMating.EventMatingResultUpdate(pasturePb.MatingResult_Empty, int64(req.MatingAt))
  460. if err = tx.Model(lastEventMating).
  461. Select("mating_result", "mating_result_at").
  462. Where("id = ?", lastEventMating.Id).
  463. Updates(lastEventMating).Error; err != nil {
  464. return xerr.WithStack(err)
  465. }
  466. // 先创建一条新的配种数据
  467. newMating = model.NewEventMating(eventCheckModel.CurrentUser.PastureId, cow, int64(req.MatingAt), req.ExposeEstrusType)
  468. newMating.EventUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating, eventCheckModel.OperationUser, eventCheckModel.CurrentUser)
  469. if err = tx.Model(newMating).Create(newMating).Error; err != nil {
  470. return xerr.WithStack(err)
  471. }
  472. if err = s.UpdateMatingResultEventCowLogByCowId(ctx, cow.Id, s.MatingResultMap()[pasturePb.MatingResult_Empty]); err != nil {
  473. zaplog.Error("MatingCreate", zap.Any("UpdateEventCowLogByCowId", err), zap.Any("cow", cow))
  474. }
  475. }
  476. // 2.2. 同期初配
  477. if !isEmptyMating && !isReMating {
  478. lastEventMating.EventUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating, eventCheckModel.OperationUser, eventCheckModel.CurrentUser)
  479. if err = tx.Model(lastEventMating).
  480. Select("mating_at", "status", "reality_day", "frozen_semen_number", "operation_id", "operation_name", "message_id", "message_name").
  481. Where("id = ?", lastEventMating.Id).
  482. Updates(lastEventMating).Error; err != nil {
  483. return xerr.WithStack(err)
  484. }
  485. }
  486. }
  487. // 牛只基本中配种信息更新
  488. cow.EventMatingUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating)
  489. if err = tx.Model(cow).
  490. Select("last_mating_at", "mating_times", "last_bull_number", "first_mating_at", "is_pregnant", "breed_status").
  491. Where("id = ?", cow.Id).
  492. Updates(cow).Error; err != nil {
  493. return xerr.WithStack(err)
  494. }
  495. // 记录日志
  496. cowLogs := s.SubmitEventLog(ctx, eventCheckModel.CurrentUser, cow, pasturePb.EventType_Mating, req.ExposeEstrusType, req)
  497. tx.Table(cowLogs.TableName()).Create(cowLogs)
  498. }
  499. // 创建冻精使用记录日志
  500. itemFrozenSemenLog := model.NewEventFrozenSemenLog(eventCheckModel.FrozenSemen.PastureId, req)
  501. if err = tx.Create(itemFrozenSemenLog).Error; err != nil {
  502. return xerr.WithStack(err)
  503. }
  504. // 减去精液的数量
  505. eventCheckModel.FrozenSemen.EventQuantityUpdate(req.FrozenSemenCount)
  506. if err = tx.Model(eventCheckModel.FrozenSemen).
  507. Select("quantity").
  508. Where("id = ?", eventCheckModel.FrozenSemen.Id).
  509. Updates(eventCheckModel.FrozenSemen).Error; err != nil {
  510. return xerr.WithStack(err)
  511. }
  512. return nil
  513. }); err != nil {
  514. return xerr.WithStack(err)
  515. }
  516. return nil
  517. }
  518. func (s *StoreEntry) WeaningBatch(ctx context.Context, req *pasturePb.EventWeaningBatchRequest) (err error) {
  519. currentUser, err := s.GetCurrentSystemUser(ctx)
  520. if err != nil {
  521. return xerr.Custom("当前用户信息错误,请退出重新登录")
  522. }
  523. if len(req.Item) <= 0 {
  524. return nil
  525. }
  526. cowIds := make([]int64, 0)
  527. cowWeightMap := make(map[int64]float64)
  528. for _, item := range req.Item {
  529. cowIds = append(cowIds, int64(item.CowId))
  530. cowWeightMap[int64(item.CowId)] = float64(item.Weight)
  531. }
  532. eventWeaningList := make([]*model.EventWeaning, 0)
  533. if err = s.DB.Model(new(model.EventWeaning)).
  534. Where("cow_id IN ?", cowIds).
  535. Where("status = ?", pasturePb.IsShow_No).
  536. Find(&eventWeaningList).Error; err != nil {
  537. return xerr.WithStack(err)
  538. }
  539. operation, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
  540. if err != nil {
  541. return xerr.WithStack(err)
  542. }
  543. defer func() {
  544. if err != nil {
  545. for _, cowId := range cowIds {
  546. cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, cowId)
  547. cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Weaning, pasturePb.ExposeEstrusType_Invalid, req)
  548. s.DB.Table(cowLogs.TableName()).Create(cowLogs)
  549. }
  550. }
  551. }()
  552. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  553. cowInfo := &model.Cow{}
  554. for _, v := range eventWeaningList {
  555. v.EventUpdate(int64(req.WeaningAt), req.Remarks, req.PenId, operation, currentUser)
  556. if err = tx.Model(new(model.EventWeaning)).
  557. Select("status", "reality_day", "operation_id", "operation_name", "message_id", "message_name", "remarks", "after_pen_id").
  558. Where("id = ?", v.Id).
  559. Updates(v).Error; err != nil {
  560. return xerr.WithStack(err)
  561. }
  562. cowInfo, err = s.GetCowInfoByCowId(ctx, currentUser.PastureId, v.CowId)
  563. if err != nil {
  564. return xerr.WithStack(err)
  565. }
  566. cowInfo.EventWeaningUpdate(int64(req.WeaningAt), req.PenId, int64(cowWeightMap[cowInfo.Id]*1000))
  567. if err = tx.Model(new(model.Cow)).
  568. Select("pen_id", "current_weight", "weaning_at", "last_weight_at").
  569. Where("id = ?", v.CowId).
  570. Updates(cowInfo).Error; err != nil {
  571. return xerr.WithStack(err)
  572. }
  573. // 创建牛只的体重记录
  574. newEventWeight := model.NewEventWeight(
  575. cowInfo,
  576. currentUser,
  577. int32(cowWeightMap[v.CowId]*1000),
  578. 0,
  579. &pasturePb.EventWeight{
  580. WeightAt: req.WeaningAt,
  581. OperationId: req.OperationId,
  582. OperationName: req.OperationName,
  583. Remarks: req.Remarks,
  584. })
  585. if err = tx.Create(newEventWeight).Error; err != nil {
  586. return xerr.WithStack(err)
  587. }
  588. }
  589. return nil
  590. }); err != nil {
  591. return xerr.WithStack(err)
  592. }
  593. return nil
  594. }