event_base.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. package backend
  2. import (
  3. "context"
  4. "fmt"
  5. "kpt-pasture/model"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  10. "go.uber.org/zap"
  11. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  12. "gitee.com/xuyiping_admin/pkg/xerr"
  13. "gorm.io/gorm"
  14. )
  15. func (s *StoreEntry) ParseCowIds(ctx context.Context, pastureId int64, cowIds string) ([]*model.Cow, error) {
  16. if len(cowIds) == 0 {
  17. return nil, xerr.Custom("cow id is required")
  18. }
  19. cowIdStr := strings.Split(cowIds, ",")
  20. var cowIdInts = make([]int64, 0)
  21. for _, v := range cowIdStr {
  22. cowId, err := strconv.ParseInt(v, 10, 64)
  23. if err != nil {
  24. return nil, xerr.Customf("错误的牛号: %s", v)
  25. }
  26. cowIdInts = append(cowIdInts, cowId)
  27. }
  28. cowList, err := s.GetCowInfoByCowIds(ctx, pastureId, cowIdInts)
  29. if err != nil {
  30. return nil, xerr.WithStack(err)
  31. }
  32. return cowList, nil
  33. }
  34. func (s *StoreEntry) EnterList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchEnterEventResponse, error) {
  35. userModel, err := s.GetUserModel(ctx)
  36. if err != nil {
  37. return nil, xerr.WithStack(err)
  38. }
  39. eventEnterList := make([]*model.EventEnter, 0)
  40. var count int64 = 0
  41. pref := s.DB.Model(new(model.EventEnter)).
  42. Where("pasture_id = ?", userModel.AppPasture.Id)
  43. if len(req.CowId) > 0 {
  44. cowIds := strings.Split(req.CowId, ",")
  45. pref.Where("cow_id IN ?", cowIds)
  46. }
  47. if err = pref.Order("id desc").
  48. Count(&count).Limit(int(pagination.PageSize)).
  49. Offset(int(pagination.PageOffset)).
  50. Find(&eventEnterList).Error; err != nil {
  51. return nil, xerr.WithStack(err)
  52. }
  53. penMap := s.PenMap(ctx, userModel.AppPasture.Id)
  54. breedStatusMap := s.CowBreedStatusMap()
  55. cowSourceMap := s.CowSourceMap()
  56. cowTypeMap := s.CowTypeMap()
  57. cowKindMap := s.CowKindMap()
  58. return &pasturePb.SearchEnterEventResponse{
  59. Code: http.StatusOK,
  60. Msg: "ok",
  61. Data: &pasturePb.SearchEnterEventData{
  62. List: model.EventEnterSlice(eventEnterList).ToPB(penMap, breedStatusMap, cowSourceMap, cowTypeMap, cowKindMap),
  63. Total: int32(count),
  64. PageSize: pagination.PageSize,
  65. Page: pagination.Page,
  66. },
  67. }, nil
  68. }
  69. func (s *StoreEntry) CreateEnter(ctx context.Context, req *pasturePb.EventEnterRequest) error {
  70. userModel, err := s.GetUserModel(ctx)
  71. if err != nil {
  72. return xerr.WithStack(err)
  73. }
  74. req.MessengerId = int32(userModel.SystemUser.Id)
  75. req.MessengerName = userModel.SystemUser.Name
  76. if req.OperationId > 0 {
  77. systemUser, _ := s.GetSystemUserById(ctx, int64(req.OperationId))
  78. req.OperationName = systemUser.Name
  79. }
  80. newCowData := model.NewCow(userModel.AppPasture.Id, userModel.SystemUser, req)
  81. newEventEnter := model.NewEventEnter(userModel.AppPasture.Id, newCowData.Id, req)
  82. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  83. if err = tx.Create(newCowData).Error; err != nil {
  84. return xerr.WithStack(err)
  85. }
  86. if err = tx.Create(newEventEnter).Error; err != nil {
  87. return xerr.WithStack(err)
  88. }
  89. eventWeight := model.NewEventWeight(
  90. userModel.AppPasture.Id,
  91. newCowData,
  92. userModel.SystemUser,
  93. int32(req.Weight*1000),
  94. 0,
  95. &pasturePb.EventWeight{
  96. WeightAt: req.EnterAt,
  97. Remarks: "入场体重",
  98. OperationId: req.OperationId,
  99. OperationName: req.OperationName,
  100. })
  101. if err = tx.Create(eventWeight).Error; err != nil {
  102. return xerr.WithStack(err)
  103. }
  104. return nil
  105. }); err != nil {
  106. return xerr.WithStack(err)
  107. }
  108. return nil
  109. }
  110. func (s *StoreEntry) GroupTransferList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchTransferGroupEventResponse, error) {
  111. eventGroupTransferList := make([]*pasturePb.EventTransferGroupData, 0)
  112. var count int64 = 0
  113. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventTransferGroup).TableName())).
  114. Select(`a.id,a.cow_id,a.pen_in_id as transfer_in_pen_id,a.pen_out_id as transfer_out_pen_id,a.lact,a.remarks,a.transfer_reason_id,a.transfer_reason_name,
  115. a.transfer_date,a.created_at,a.operation_id,a.operation_name,b.name as transfer_in_pen_name,c.name as transfer_out_pen_name,
  116. f.lact,f.ear_number`).
  117. Joins(fmt.Sprintf("JOIN %s AS b ON a.pen_in_id = b.id", new(model.Pen).TableName())).
  118. Joins(fmt.Sprintf("JOIN %s AS c on a.pen_out_id = c.id", new(model.Pen).TableName())).
  119. Joins(fmt.Sprintf("JOIN %s AS f ON a.cow_id = f.id", new(model.Cow).TableName()))
  120. if len(req.CowId) > 0 {
  121. cowIds := strings.Split(req.CowId, ",")
  122. pref.Where("a.cow_id IN ?", cowIds)
  123. }
  124. if err := pref.Order("a.id desc").Group("a.id").
  125. Count(&count).Limit(int(pagination.PageSize)).
  126. Offset(int(pagination.PageOffset)).
  127. Find(&eventGroupTransferList).Error; err != nil {
  128. return nil, xerr.WithStack(err)
  129. }
  130. return &pasturePb.SearchTransferGroupEventResponse{
  131. Code: http.StatusOK,
  132. Msg: "ok",
  133. Data: &pasturePb.SearchTransferGroupEventData{
  134. List: eventGroupTransferList,
  135. Total: int32(count),
  136. PageSize: pagination.PageSize,
  137. Page: pagination.Page,
  138. },
  139. }, nil
  140. }
  141. func (s *StoreEntry) CreateGroupTransfer(ctx context.Context, req *pasturePb.TransferGroupEventRequest) (err error) {
  142. userModel, err := s.GetUserModel(ctx)
  143. if err != nil {
  144. return xerr.WithStack(err)
  145. }
  146. newEventTransferGroupModelList := make([]*model.EventTransferGroupModel, 0)
  147. transferPenMap := s.TransferPenMap()
  148. for _, v := range req.Body {
  149. cow, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(v.CowId))
  150. if err != nil {
  151. return xerr.WithStack(err)
  152. }
  153. // 转去栏舍和当前栏舍相同,则不处理
  154. if cow.PenId == v.TransferInPenId {
  155. continue
  156. }
  157. operationUser, err := s.GetSystemUserById(ctx, int64(v.OperationId))
  158. if err != nil {
  159. return xerr.WithStack(err)
  160. }
  161. newEventTransferGroup := model.NewEventTransferGroup(userModel.AppPasture.Id, cow, v, transferPenMap, userModel.SystemUser, operationUser)
  162. newEventTransferGroupModelList = append(newEventTransferGroupModelList, &model.EventTransferGroupModel{
  163. Cow: cow,
  164. EventTransferGroup: newEventTransferGroup,
  165. })
  166. }
  167. if len(newEventTransferGroupModelList) <= 0 {
  168. return nil
  169. }
  170. defer func() {
  171. if err != nil {
  172. for _, etg := range newEventTransferGroupModelList {
  173. cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, etg.Cow, pasturePb.EventType_Transfer_Ben, pasturePb.ExposeEstrusType_Invalid, etg.EventTransferGroup)
  174. s.DB.Table(cowLogs.TableName()).Create(cowLogs)
  175. }
  176. }
  177. }()
  178. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  179. for _, v := range newEventTransferGroupModelList {
  180. if err = tx.Create(v.EventTransferGroup).Error; err != nil {
  181. return xerr.WithStack(err)
  182. }
  183. if err = tx.Model(v.Cow).Update("pen_id", v.EventTransferGroup.PenInId).Error; err != nil {
  184. return xerr.WithStack(err)
  185. }
  186. }
  187. return nil
  188. }); err != nil {
  189. return xerr.WithStack(err)
  190. }
  191. return nil
  192. }
  193. func (s *StoreEntry) BodyScoreList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchBodyScoreEventResponse, error) {
  194. bodyScoreList := make([]*pasturePb.BodyScoreList, 0)
  195. var count int64 = 0
  196. pref := s.DB.Model(new(model.EventBodyScore)).Select("*,score as body_score")
  197. if len(req.CowId) > 0 {
  198. cowIds := strings.Split(req.CowId, ",")
  199. pref.Where("cow_id IN ?", cowIds)
  200. }
  201. if err := pref.Order("id desc").
  202. Count(&count).Limit(int(pagination.PageSize)).
  203. Offset(int(pagination.PageOffset)).
  204. Find(&bodyScoreList).Error; err != nil {
  205. return nil, xerr.WithStack(err)
  206. }
  207. return &pasturePb.SearchBodyScoreEventResponse{
  208. Code: http.StatusOK,
  209. Msg: "ok",
  210. Data: &pasturePb.SearchBodyScoreData{
  211. List: bodyScoreList,
  212. Total: int32(count),
  213. PageSize: pagination.PageSize,
  214. Page: pagination.Page,
  215. },
  216. }, nil
  217. }
  218. func (s *StoreEntry) CreateBodyScore(ctx context.Context, req *pasturePb.BodyScoreEventRequest) error {
  219. if len(req.CowId) <= 0 {
  220. return xerr.Custom("请选择相关牛只")
  221. }
  222. userModel, err := s.GetUserModel(ctx)
  223. if err != nil {
  224. return xerr.WithStack(err)
  225. }
  226. operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
  227. if err != nil {
  228. return xerr.WithStack(err)
  229. }
  230. req.OperationName = operationUser.Name
  231. bodyScourEvent := make([]*model.EventBodyScore, 0)
  232. cowList, err := s.ParseCowIds(ctx, userModel.AppPasture.Id, req.CowId)
  233. if err != nil {
  234. return xerr.WithStack(err)
  235. }
  236. for _, cow := range cowList {
  237. bodyScourEvent = append(bodyScourEvent, model.NewEventBodyScore(cow, userModel.AppPasture.Id, userModel.SystemUser, req))
  238. }
  239. if len(bodyScourEvent) <= 0 {
  240. return nil
  241. }
  242. return s.DB.Create(bodyScourEvent).Error
  243. }
  244. func (s *StoreEntry) WeightList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchWeightEventResponse, error) {
  245. weightList := make([]*pasturePb.SearchWeightList, 0)
  246. var count int64 = 0
  247. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventWeight).TableName())).
  248. Select(`a.id,a.cow_id,a.ear_number,a.weight / 100 as weight,a.lact,a.day_age,a.weight_at,a.remarks,a.created_at,
  249. a.updated_at,a.message_id,a.operation_id,a.message_name,a.operation_name`)
  250. if len(req.CowId) > 0 {
  251. cowIds := strings.Split(req.CowId, ",")
  252. pref.Where("a.cow_id IN ?", cowIds)
  253. }
  254. if err := pref.Order("a.id desc").
  255. Count(&count).Limit(int(pagination.PageSize)).
  256. Offset(int(pagination.PageOffset)).
  257. Find(&weightList).Error; err != nil {
  258. return nil, xerr.WithStack(err)
  259. }
  260. return &pasturePb.SearchWeightEventResponse{
  261. Code: http.StatusOK,
  262. Msg: "ok",
  263. Data: &pasturePb.SearchWeightData{
  264. List: weightList,
  265. Total: int32(count),
  266. PageSize: pagination.PageSize,
  267. Page: pagination.Page,
  268. },
  269. }, nil
  270. }
  271. func (s *StoreEntry) WeightBatch(ctx context.Context, req *pasturePb.EventWeight) (err error) {
  272. if len(req.WeightItems) <= 0 {
  273. return xerr.Custom("请选择相关牛只")
  274. }
  275. userModel, err := s.GetUserModel(ctx)
  276. if err != nil {
  277. return xerr.WithStack(err)
  278. }
  279. operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
  280. if err != nil {
  281. return xerr.WithStack(err)
  282. }
  283. req.OperationName = operationUser.Name
  284. defer func() {
  285. if err == nil {
  286. // 记录事件日志
  287. for _, item := range req.WeightItems {
  288. cow, _ := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(item.CowId))
  289. cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, cow, pasturePb.EventType_Weight, pasturePb.ExposeEstrusType_Invalid, req)
  290. s.DB.Table(cowLogs.TableName()).Create(cowLogs)
  291. }
  292. }
  293. }()
  294. cow := &model.Cow{}
  295. for _, item := range req.WeightItems {
  296. cow, err = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(item.CowId))
  297. if err != nil {
  298. return xerr.WithStack(err)
  299. }
  300. item.WeightAt = req.WeightAt
  301. // 更新牛只信息
  302. cow.EventWeightUpdate(int64(item.Weight), int64(req.WeightAt))
  303. if err = s.DB.Model(new(model.Cow)).
  304. Select("last_second_weight_at", "last_second_weight", "last_weight_at", "current_weight").
  305. Where("id = ?", cow.Id).
  306. Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
  307. Updates(cow).Error; err != nil {
  308. return xerr.WithStack(err)
  309. }
  310. // 创建牛只的体重记录
  311. eventWeight := model.NewEventWeight(userModel.AppPasture.Id, cow, userModel.SystemUser, int32(item.Weight*1000), item.Height, req)
  312. if err = s.DB.Create(eventWeight).Error; err != nil {
  313. return xerr.WithStack(err)
  314. }
  315. }
  316. return err
  317. }
  318. func (s *StoreEntry) DepartureBatch(ctx context.Context, req *pasturePb.EventDepartureBatch) (err error) {
  319. if len(req.Item) <= 0 {
  320. return xerr.Custom("请选择相关牛只")
  321. }
  322. userModel, err := s.GetUserModel(ctx)
  323. if err != nil {
  324. return xerr.WithStack(err)
  325. }
  326. newEventDepartureModelList := make([]*model.EventDepartureModel, 0)
  327. cow := &model.Cow{}
  328. for _, item := range req.Item {
  329. cow, err = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(item.CowId))
  330. if err != nil {
  331. zaplog.Error("DepartureBatch", zap.Any("item", item), zap.Any("err", err))
  332. return xerr.Customf("获取牛只信息失败: %d", item.CowId)
  333. }
  334. operationUser, err := s.GetSystemUserById(ctx, int64(item.OperationId))
  335. if err != nil {
  336. zaplog.Error("DepartureBatch", zap.Any("item", item), zap.Any("err", err))
  337. return xerr.Customf("获取操作人员信息失败: %d", item.OperationId)
  338. }
  339. reasonName := ""
  340. switch item.DepartureType {
  341. case pasturePb.DepartureType_Death:
  342. reasonName = s.DeadReasonMap()[pasturePb.DeadReason_Kind(item.DepartureReasonKind)]
  343. case pasturePb.DepartureType_Out:
  344. reasonName = s.OutReasonMap()[pasturePb.OutReason_Kind(item.DepartureReasonKind)]
  345. default:
  346. return xerr.Custom("未知的离场类型")
  347. }
  348. newEventDeparture := model.NewEventDeparture(userModel.AppPasture.Id, cow, item, reasonName, userModel.SystemUser, operationUser)
  349. newEventDepartureModelList = append(newEventDepartureModelList, &model.EventDepartureModel{
  350. EventDeparture: newEventDeparture,
  351. Cow: cow,
  352. DepartureAt: int64(item.DepartureAt),
  353. })
  354. }
  355. if len(newEventDepartureModelList) <= 0 {
  356. return nil
  357. }
  358. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  359. // 记录事件日志
  360. for _, item := range newEventDepartureModelList {
  361. eventType := pasturePb.EventType_Death
  362. if item.EventDeparture.DepartureType == pasturePb.DepartureType_Out {
  363. eventType = pasturePb.EventType_Out
  364. }
  365. if err = tx.Create(item.EventDeparture).Error; err != nil {
  366. return xerr.WithStack(err)
  367. }
  368. cow.EventDepartureUpdate(item.DepartureAt, item.EventDeparture.DepartureType)
  369. if err = tx.Model(cow).
  370. Select("admission_status", "health_status", "departure_at").
  371. Where("id = ?", cow.Id).
  372. Updates(cow).Error; err != nil {
  373. return xerr.WithStack(err)
  374. }
  375. // 记录事件日志
  376. cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, item.Cow, eventType, pasturePb.ExposeEstrusType_Invalid, item)
  377. tx.Table(cowLogs.TableName()).Create(cowLogs)
  378. }
  379. return nil
  380. }); err != nil {
  381. return xerr.WithStack(err)
  382. }
  383. return nil
  384. }
  385. func (s *StoreEntry) CowEarNumberUpdate(ctx context.Context, req *pasturePb.EventReplaceEarNumber) (err error) {
  386. userModel, err := s.GetUserModel(ctx)
  387. if err != nil {
  388. return xerr.WithStack(err)
  389. }
  390. cow, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(req.CowId))
  391. if err != nil {
  392. return xerr.Custom("未找到该牛只信息")
  393. }
  394. cow.EventEarNumberUpdate(req.EarNumber)
  395. if err = s.DB.Model(cow).
  396. Select("ear_number", "ear_old_number").
  397. Where("id = ?", cow.Id).
  398. Updates(cow).Error; err != nil {
  399. return xerr.WithStack(err)
  400. }
  401. return nil
  402. }