event_base.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. currentUser, err := s.GetCurrentSystemUser(ctx)
  36. if err != nil || currentUser.Id <= 0 {
  37. return nil, xerr.Customf("当前用户信息错误,请退出重新登录")
  38. }
  39. eventEnterList := make([]*model.EventEnter, 0)
  40. var count int64 = 0
  41. pref := s.DB.Model(new(model.EventEnter)).
  42. Where("pasture_id = ?", currentUser.PastureId)
  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, currentUser.PastureId)
  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. Message: "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. currentUser, err := s.GetCurrentSystemUser(ctx)
  71. if err != nil || currentUser.Id <= 0 {
  72. return xerr.Customf("当前用户信息错误,请退出重新登录")
  73. }
  74. req.MessengerId = int32(currentUser.Id)
  75. req.MessengerName = currentUser.Name
  76. if req.OperationId > 0 {
  77. systemUser, _ := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
  78. req.OperationName = systemUser.Name
  79. }
  80. newCowData := model.NewCow(req)
  81. newEventEnter := model.NewEventEnter(currentUser.PastureId, 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. return nil
  90. }); err != nil {
  91. return xerr.WithStack(err)
  92. }
  93. return nil
  94. }
  95. func (s *StoreEntry) GroupTransferList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchTransferGroupEventResponse, error) {
  96. eventGroupTransferList := make([]*pasturePb.EventTransferGroupData, 0)
  97. var count int64 = 0
  98. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventTransferGroup).TableName())).
  99. 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,
  100. 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,
  101. f.lact,f.ear_number`).
  102. Joins(fmt.Sprintf("JOIN %s AS b ON a.pen_in_id = b.id", new(model.Pen).TableName())).
  103. Joins(fmt.Sprintf("JOIN %s AS c on a.pen_out_id = c.id", new(model.Pen).TableName())).
  104. Joins(fmt.Sprintf("JOIN %s AS f ON a.cow_id = f.id", new(model.Cow).TableName()))
  105. if len(req.CowId) > 0 {
  106. cowIds := strings.Split(req.CowId, ",")
  107. pref.Where("a.cow_id IN ?", cowIds)
  108. }
  109. if err := pref.Order("a.id desc").Group("a.id").
  110. Count(&count).Limit(int(pagination.PageSize)).
  111. Offset(int(pagination.PageOffset)).
  112. Find(&eventGroupTransferList).Error; err != nil {
  113. return nil, xerr.WithStack(err)
  114. }
  115. return &pasturePb.SearchTransferGroupEventResponse{
  116. Code: http.StatusOK,
  117. Message: "ok",
  118. Data: &pasturePb.SearchTransferGroupEventData{
  119. List: eventGroupTransferList,
  120. Total: int32(count),
  121. PageSize: pagination.PageSize,
  122. Page: pagination.Page,
  123. },
  124. }, nil
  125. }
  126. func (s *StoreEntry) CreateGroupTransfer(ctx context.Context, req *pasturePb.TransferGroupEventRequest) (err error) {
  127. currentUser, err := s.GetCurrentSystemUser(ctx)
  128. if err != nil || currentUser.Id <= 0 {
  129. return xerr.Customf("当前用户信息错误,请退出重新登录")
  130. }
  131. newEventTransferGroupModelList := make([]*model.EventTransferGroupModel, 0)
  132. for _, v := range req.Body {
  133. cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(v.CowId))
  134. if err != nil {
  135. return xerr.WithStack(err)
  136. }
  137. // 转去栏舍和当前栏舍相同,则不处理
  138. if cow.PenId == v.TransferInPenId {
  139. continue
  140. }
  141. operationUser, err := s.GetSystemUserById(ctx, cow.PastureId, int64(v.OperationId))
  142. if err != nil {
  143. return xerr.WithStack(err)
  144. }
  145. newEventTransferGroup := model.NewEventTransferGroup(cow, v, currentUser, operationUser)
  146. newEventTransferGroupModelList = append(newEventTransferGroupModelList, &model.EventTransferGroupModel{
  147. Cow: cow,
  148. EventTransferGroup: newEventTransferGroup,
  149. })
  150. }
  151. if len(newEventTransferGroupModelList) <= 0 {
  152. return nil
  153. }
  154. defer func() {
  155. if err != nil {
  156. for _, etg := range newEventTransferGroupModelList {
  157. cowLogs := s.SubmitEventLog(ctx, currentUser, etg.Cow, pasturePb.EventType_Transfer_Ben, pasturePb.ExposeEstrusType_Invalid, etg.EventTransferGroup)
  158. s.DB.Table(cowLogs.TableName()).Create(cowLogs)
  159. }
  160. }
  161. }()
  162. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  163. for _, v := range newEventTransferGroupModelList {
  164. if err = tx.Create(v.EventTransferGroup).Error; err != nil {
  165. return xerr.WithStack(err)
  166. }
  167. if err = tx.Model(v.Cow).Update("pen_id", v.EventTransferGroup.PenInId).Error; err != nil {
  168. return xerr.WithStack(err)
  169. }
  170. }
  171. return nil
  172. }); err != nil {
  173. return xerr.WithStack(err)
  174. }
  175. return nil
  176. }
  177. func (s *StoreEntry) BodyScoreList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchBodyScoreEventResponse, error) {
  178. bodyScoreList := make([]*pasturePb.BodyScoreList, 0)
  179. var count int64 = 0
  180. pref := s.DB.Model(new(model.EventBodyScore)).Select("*,score as body_score")
  181. if len(req.CowId) > 0 {
  182. cowIds := strings.Split(req.CowId, ",")
  183. pref.Where("cow_id IN ?", cowIds)
  184. }
  185. if err := pref.Order("id desc").
  186. Count(&count).Limit(int(pagination.PageSize)).
  187. Offset(int(pagination.PageOffset)).
  188. Find(&bodyScoreList).Error; err != nil {
  189. return nil, xerr.WithStack(err)
  190. }
  191. return &pasturePb.SearchBodyScoreEventResponse{
  192. Code: http.StatusOK,
  193. Message: "ok",
  194. Data: &pasturePb.SearchBodyScoreData{
  195. List: bodyScoreList,
  196. Total: int32(count),
  197. PageSize: pagination.PageSize,
  198. Page: pagination.Page,
  199. },
  200. }, nil
  201. }
  202. func (s *StoreEntry) CreateBodyScore(ctx context.Context, req *pasturePb.BodyScoreEventRequest) error {
  203. if len(req.CowId) <= 0 {
  204. return xerr.Custom("请选择相关牛只")
  205. }
  206. currentUser, err := s.GetCurrentSystemUser(ctx)
  207. if err != nil {
  208. return xerr.Custom("获取当前用户失败,请退出重新登录")
  209. }
  210. operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
  211. if err != nil {
  212. return xerr.WithStack(err)
  213. }
  214. req.OperationName = operationUser.Name
  215. bodyScourEvent := make([]*model.EventBodyScore, 0)
  216. cowList, err := s.ParseCowIds(ctx, currentUser.PastureId, req.CowId)
  217. if err != nil {
  218. return xerr.WithStack(err)
  219. }
  220. for _, cow := range cowList {
  221. bodyScourEvent = append(bodyScourEvent, model.NewEventBodyScore(cow, currentUser, req))
  222. }
  223. if len(bodyScourEvent) <= 0 {
  224. return nil
  225. }
  226. return s.DB.Create(bodyScourEvent).Error
  227. }
  228. func (s *StoreEntry) WeightList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchWeightEventResponse, error) {
  229. weightList := make([]*pasturePb.SearchWeightList, 0)
  230. var count int64 = 0
  231. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventWeight).TableName())).
  232. 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,
  233. a.updated_at,a.message_id,a.operation_id,a.message_name,a.operation_name`)
  234. if len(req.CowId) > 0 {
  235. cowIds := strings.Split(req.CowId, ",")
  236. pref.Where("a.cow_id IN ?", cowIds)
  237. }
  238. if err := pref.Order("a.id desc").
  239. Count(&count).Limit(int(pagination.PageSize)).
  240. Offset(int(pagination.PageOffset)).
  241. Find(&weightList).Error; err != nil {
  242. return nil, xerr.WithStack(err)
  243. }
  244. return &pasturePb.SearchWeightEventResponse{
  245. Code: http.StatusOK,
  246. Message: "ok",
  247. Data: &pasturePb.SearchWeightData{
  248. List: weightList,
  249. Total: int32(count),
  250. PageSize: pagination.PageSize,
  251. Page: pagination.Page,
  252. },
  253. }, nil
  254. }
  255. func (s *StoreEntry) WeightBatch(ctx context.Context, req *pasturePb.EventWeight) (err error) {
  256. if len(req.WeightItems) <= 0 {
  257. return xerr.Custom("请选择相关牛只")
  258. }
  259. currentUser, err := s.GetCurrentSystemUser(ctx)
  260. if err != nil {
  261. return xerr.Custom("当前登录用户失败,请退出重新登录")
  262. }
  263. operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
  264. if err != nil {
  265. return xerr.WithStack(err)
  266. }
  267. req.OperationName = operationUser.Name
  268. defer func() {
  269. if err == nil {
  270. // 记录事件日志
  271. for _, item := range req.WeightItems {
  272. cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(item.CowId))
  273. cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Weight, pasturePb.ExposeEstrusType_Invalid, req)
  274. s.DB.Table(cowLogs.TableName()).Create(cowLogs)
  275. }
  276. }
  277. }()
  278. cow := &model.Cow{}
  279. for _, item := range req.WeightItems {
  280. cow, err = s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(item.CowId))
  281. if err != nil {
  282. return xerr.WithStack(err)
  283. }
  284. item.WeightAt = req.WeightAt
  285. // 更新牛只信息
  286. cow.EventWeightUpdate(int64(item.Weight), int64(req.WeightAt))
  287. if err = s.DB.Model(new(model.Cow)).
  288. Select("last_second_weight_at", "last_second_weight", "last_weight_at", "current_weight").
  289. Where("id = ?", cow.Id).
  290. Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
  291. Updates(cow).Error; err != nil {
  292. return xerr.WithStack(err)
  293. }
  294. // 创建牛只的体重记录
  295. eventWeight := model.NewEventWeight(cow, currentUser, int32(item.Weight*1000), item.Height, req)
  296. if err = s.DB.Create(eventWeight).Error; err != nil {
  297. return xerr.WithStack(err)
  298. }
  299. }
  300. return err
  301. }
  302. func (s *StoreEntry) DepartureBatch(ctx context.Context, req *pasturePb.EventDepartureBatch) (err error) {
  303. if len(req.Item) <= 0 {
  304. return xerr.Custom("请选择相关牛只")
  305. }
  306. currentUser, err := s.GetCurrentSystemUser(ctx)
  307. if err != nil {
  308. return xerr.Custom("当前登录用户失败,请退出重新登录")
  309. }
  310. newEventDepartureModelList := make([]*model.EventDepartureModel, 0)
  311. cow := &model.Cow{}
  312. for _, item := range req.Item {
  313. cow, err = s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(item.CowId))
  314. if err != nil {
  315. zaplog.Error("DepartureBatch", zap.Any("item", item), zap.Any("err", err))
  316. return xerr.Customf("获取牛只信息失败: %d", item.CowId)
  317. }
  318. operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(item.OperationId))
  319. if err != nil {
  320. zaplog.Error("DepartureBatch", zap.Any("item", item), zap.Any("err", err))
  321. return xerr.Customf("获取操作人员信息失败: %d", item.OperationId)
  322. }
  323. reasonName := ""
  324. switch item.DepartureType {
  325. case pasturePb.DepartureType_Death:
  326. reasonName = s.DeadReasonMap()[pasturePb.DeadReason_Kind(item.DepartureReasonKind)]
  327. case pasturePb.DepartureType_Out:
  328. reasonName = s.OutReasonMap()[pasturePb.OutReason_Kind(item.DepartureReasonKind)]
  329. default:
  330. return xerr.Custom("未知的离场类型")
  331. }
  332. newEventDeparture := model.NewEventDeparture(currentUser.PastureId, cow, item, reasonName, currentUser, operationUser)
  333. newEventDepartureModelList = append(newEventDepartureModelList, &model.EventDepartureModel{
  334. EventDeparture: newEventDeparture,
  335. Cow: cow,
  336. DepartureAt: int64(item.DepartureAt),
  337. })
  338. }
  339. if len(newEventDepartureModelList) <= 0 {
  340. return nil
  341. }
  342. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  343. // 记录事件日志
  344. for _, item := range newEventDepartureModelList {
  345. eventType := pasturePb.EventType_Death
  346. if item.EventDeparture.DepartureType == pasturePb.DepartureType_Out {
  347. eventType = pasturePb.EventType_Out
  348. }
  349. if err = tx.Create(item.EventDeparture).Error; err != nil {
  350. return xerr.WithStack(err)
  351. }
  352. cow.EventDepartureUpdate(item.DepartureAt, item.EventDeparture.DepartureType)
  353. if err = tx.Model(cow).
  354. Select("admission_status", "health_status", "departure_at").
  355. Where("id = ?", cow.Id).
  356. Updates(cow).Error; err != nil {
  357. return xerr.WithStack(err)
  358. }
  359. // 记录事件日志
  360. cowLogs := s.SubmitEventLog(ctx, currentUser, item.Cow, eventType, pasturePb.ExposeEstrusType_Invalid, item)
  361. tx.Table(cowLogs.TableName()).Create(cowLogs)
  362. }
  363. return nil
  364. }); err != nil {
  365. return xerr.WithStack(err)
  366. }
  367. return nil
  368. }
  369. func (s *StoreEntry) CowEarNumberUpdate(ctx context.Context, req *pasturePb.EventReplaceEarNumber) (err error) {
  370. currentUser, err := s.GetCurrentSystemUser(ctx)
  371. if err != nil {
  372. return xerr.Custom("当前登录用户失败,请退出重新登录")
  373. }
  374. cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(req.CowId))
  375. if err != nil {
  376. return xerr.Custom("未找到该牛只信息")
  377. }
  378. cow.EventEarNumberUpdate(req.EarNumber)
  379. if err = s.DB.Model(cow).
  380. Select("ear_number", "ear_old_number").
  381. Where("id = ?", cow.Id).
  382. Updates(cow).Error; err != nil {
  383. return xerr.WithStack(err)
  384. }
  385. return nil
  386. }