event_base.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. package backend
  2. import (
  3. "context"
  4. "fmt"
  5. "kpt-pasture/model"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  10. "gitee.com/xuyiping_admin/pkg/xerr"
  11. "gorm.io/gorm"
  12. )
  13. func (s *StoreEntry) ParseCowIds(ctx context.Context, pastureId int64, cowIds string) ([]*model.Cow, error) {
  14. if len(cowIds) == 0 {
  15. return nil, xerr.Custom("cow id is required")
  16. }
  17. cowIdStr := strings.Split(cowIds, ",")
  18. var cowIdInts = make([]int64, 0)
  19. for _, v := range cowIdStr {
  20. cowId, err := strconv.ParseInt(v, 10, 64)
  21. if err != nil {
  22. return nil, xerr.Customf("错误的牛号: %s", v)
  23. }
  24. cowIdInts = append(cowIdInts, cowId)
  25. }
  26. cowList, err := s.GetCowInfoByCowIds(ctx, pastureId, cowIdInts)
  27. if err != nil {
  28. return nil, xerr.WithStack(err)
  29. }
  30. return cowList, nil
  31. }
  32. func (s *StoreEntry) EnterList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchEnterEventResponse, error) {
  33. userModel, err := s.GetUserModel(ctx)
  34. if err != nil {
  35. return nil, xerr.WithStack(err)
  36. }
  37. eventEnterList := make([]*model.EventEnter, 0)
  38. var count int64 = 0
  39. pref := s.DB.Model(new(model.EventEnter)).
  40. Where("pasture_id = ?", userModel.AppPasture.Id)
  41. if len(req.CowId) > 0 {
  42. cowIds := strings.Split(req.CowId, ",")
  43. pref.Where("cow_id IN ?", cowIds)
  44. }
  45. if err = pref.Order("id desc").
  46. Count(&count).Limit(int(pagination.PageSize)).
  47. Offset(int(pagination.PageOffset)).
  48. Find(&eventEnterList).Error; err != nil {
  49. return nil, xerr.WithStack(err)
  50. }
  51. penMap := s.PenMap(ctx, userModel.AppPasture.Id)
  52. breedStatusMap := s.CowBreedStatusMap()
  53. cowSourceMap := s.CowSourceMap()
  54. cowTypeMap := s.CowTypeMap()
  55. cowKindMap := s.CowKindMap()
  56. return &pasturePb.SearchEnterEventResponse{
  57. Code: http.StatusOK,
  58. Msg: "ok",
  59. Data: &pasturePb.SearchEnterEventData{
  60. List: model.EventEnterSlice(eventEnterList).ToPB(penMap, breedStatusMap, cowSourceMap, cowTypeMap, cowKindMap),
  61. Total: int32(count),
  62. PageSize: pagination.PageSize,
  63. Page: pagination.Page,
  64. },
  65. }, nil
  66. }
  67. func (s *StoreEntry) CreateEnter(ctx context.Context, req *pasturePb.EventEnterRequest) (err error) {
  68. userModel, err := s.GetUserModel(ctx)
  69. if err != nil {
  70. return xerr.WithStack(err)
  71. }
  72. if err = s.EnterCheck(ctx, req); err != nil {
  73. return xerr.WithStack(err)
  74. }
  75. req.MessengerId = int32(userModel.SystemUser.Id)
  76. req.MessengerName = userModel.SystemUser.Name
  77. if req.OperationId > 0 {
  78. systemUser, _ := s.GetSystemUserById(ctx, int64(req.OperationId))
  79. req.OperationName = systemUser.Name
  80. }
  81. penMap := s.PenMap(ctx, userModel.AppPasture.Id)
  82. newCow := model.NewEnterCow(userModel.AppPasture.Id, req, penMap)
  83. defer func() {
  84. if err == nil {
  85. cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, newCow, pasturePb.EventType_Enter, pasturePb.ExposeEstrusType_Invalid, req)
  86. s.DB.Table(cowLogs.TableName()).Create(cowLogs)
  87. }
  88. }()
  89. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  90. if err = tx.Create(newCow).Error; err != nil {
  91. return xerr.WithStack(err)
  92. }
  93. newEventEnter := model.NewEventEnter(userModel.AppPasture.Id, newCow.Id, req)
  94. if err = tx.Create(newEventEnter).Error; err != nil {
  95. return xerr.WithStack(err)
  96. }
  97. eventWeight := model.NewEventWeight(
  98. userModel.AppPasture.Id,
  99. newCow,
  100. userModel.SystemUser,
  101. &pasturePb.EventWeight{
  102. WeightAt: req.EnterAt,
  103. Remarks: "入场体重",
  104. OperationId: req.OperationId,
  105. OperationName: req.OperationName,
  106. Weight: req.Weight,
  107. })
  108. if err = tx.Create(eventWeight).Error; err != nil {
  109. return xerr.WithStack(err)
  110. }
  111. return nil
  112. }); err != nil {
  113. return xerr.WithStack(err)
  114. }
  115. return nil
  116. }
  117. func (s *StoreEntry) GroupTransferList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchTransferGroupEventResponse, error) {
  118. eventGroupTransferList := make([]*pasturePb.EventTransferGroupData, 0)
  119. var count int64 = 0
  120. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventTransferGroup).TableName())).
  121. 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,
  122. a.transfer_reason_id,a.transfer_reason_name,a.transfer_date,a.created_at,a.operation_id,a.operation_name,
  123. b.name as transfer_in_pen_name,c.name as transfer_out_pen_name,f.lact,f.ear_number`).
  124. Joins(fmt.Sprintf("JOIN %s AS b ON a.pen_in_id = b.id", new(model.Pen).TableName())).
  125. Joins(fmt.Sprintf("JOIN %s AS c on a.pen_out_id = c.id", new(model.Pen).TableName())).
  126. Joins(fmt.Sprintf("JOIN %s AS f ON a.cow_id = f.id", new(model.Cow).TableName()))
  127. if len(req.CowId) > 0 {
  128. cowIds := strings.Split(req.CowId, ",")
  129. pref.Where("a.cow_id IN ?", cowIds)
  130. }
  131. if err := pref.Order("a.id desc").Group("a.id").
  132. Count(&count).Limit(int(pagination.PageSize)).
  133. Offset(int(pagination.PageOffset)).
  134. Find(&eventGroupTransferList).Error; err != nil {
  135. return nil, xerr.WithStack(err)
  136. }
  137. return &pasturePb.SearchTransferGroupEventResponse{
  138. Code: http.StatusOK,
  139. Msg: "ok",
  140. Data: &pasturePb.SearchTransferGroupEventData{
  141. List: eventGroupTransferList,
  142. Total: int32(count),
  143. PageSize: pagination.PageSize,
  144. Page: pagination.Page,
  145. },
  146. }, nil
  147. }
  148. func (s *StoreEntry) CreateGroupTransfer(ctx context.Context, req *pasturePb.TransferGroupEventRequest) (err error) {
  149. userModel, err := s.GetUserModel(ctx)
  150. if err != nil {
  151. return xerr.WithStack(err)
  152. }
  153. newEventTransferGroupModelList := make([]*model.EventTransferGroupModel, 0)
  154. transferPenMap := s.TransferPenMap()
  155. for _, v := range req.Body {
  156. cow, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(v.CowId))
  157. if err != nil {
  158. return xerr.WithStack(err)
  159. }
  160. // 转去栏舍和当前栏舍相同,则不处理
  161. if cow.PenId == v.TransferInPenId {
  162. return xerr.Custom("转入栏舍和牛只当前栏舍不能一致")
  163. }
  164. operationUser, err := s.GetSystemUserById(ctx, int64(v.OperationId))
  165. if err != nil {
  166. return xerr.WithStack(err)
  167. }
  168. newEventTransferGroup := model.NewEventTransferGroup(userModel.AppPasture.Id, cow, v, transferPenMap, userModel.SystemUser, operationUser)
  169. newEventTransferGroupModelList = append(newEventTransferGroupModelList, &model.EventTransferGroupModel{
  170. Cow: cow,
  171. EventTransferGroup: newEventTransferGroup,
  172. })
  173. }
  174. if len(newEventTransferGroupModelList) <= 0 {
  175. return nil
  176. }
  177. if err = s.DB.Transaction(func(tx *gorm.DB) error {
  178. for _, etg := range newEventTransferGroupModelList {
  179. if err = tx.Create(etg.EventTransferGroup).Error; err != nil {
  180. return xerr.WithStack(err)
  181. }
  182. if err = tx.Model(etg.Cow).Update("pen_id", etg.EventTransferGroup.PenInId).Error; err != nil {
  183. return xerr.WithStack(err)
  184. }
  185. // 事件日志
  186. cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, etg.Cow, pasturePb.EventType_Transfer_Ben, pasturePb.ExposeEstrusType_Invalid, etg.EventTransferGroup)
  187. if err = tx.Table(cowLogs.TableName()).Create(cowLogs).Error; err != nil {
  188. return xerr.WithStack(err)
  189. }
  190. }
  191. return nil
  192. }); err != nil {
  193. return xerr.WithStack(err)
  194. }
  195. return nil
  196. }
  197. func (s *StoreEntry) BodyScoreList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchBodyScoreEventResponse, error) {
  198. bodyScoreList := make([]*pasturePb.BodyScoreList, 0)
  199. var count int64 = 0
  200. pref := s.DB.Model(new(model.EventBodyScore)).Select("*,score as body_score")
  201. if len(req.CowId) > 0 {
  202. cowIds := strings.Split(req.CowId, ",")
  203. pref.Where("cow_id IN ?", cowIds)
  204. }
  205. if err := pref.Order("id desc").
  206. Count(&count).Limit(int(pagination.PageSize)).
  207. Offset(int(pagination.PageOffset)).
  208. Find(&bodyScoreList).Error; err != nil {
  209. return nil, xerr.WithStack(err)
  210. }
  211. return &pasturePb.SearchBodyScoreEventResponse{
  212. Code: http.StatusOK,
  213. Msg: "ok",
  214. Data: &pasturePb.SearchBodyScoreData{
  215. List: bodyScoreList,
  216. Total: int32(count),
  217. PageSize: pagination.PageSize,
  218. Page: pagination.Page,
  219. },
  220. }, nil
  221. }
  222. func (s *StoreEntry) CreateBodyScore(ctx context.Context, req *pasturePb.BodyScoreEventRequest) error {
  223. if len(req.CowId) <= 0 {
  224. return xerr.Custom("请选择相关牛只")
  225. }
  226. userModel, err := s.GetUserModel(ctx)
  227. if err != nil {
  228. return xerr.WithStack(err)
  229. }
  230. operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
  231. if err != nil {
  232. return xerr.WithStack(err)
  233. }
  234. req.OperationName = operationUser.Name
  235. bodyScourEvent := make([]*model.EventBodyScore, 0)
  236. cowList, err := s.ParseCowIds(ctx, userModel.AppPasture.Id, req.CowId)
  237. if err != nil {
  238. return xerr.WithStack(err)
  239. }
  240. for _, cow := range cowList {
  241. bodyScourEvent = append(bodyScourEvent, model.NewEventBodyScore(cow, userModel.AppPasture.Id, userModel.SystemUser, req))
  242. }
  243. if len(bodyScourEvent) <= 0 {
  244. return nil
  245. }
  246. return s.DB.Create(bodyScourEvent).Error
  247. }
  248. func (s *StoreEntry) WeightList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchWeightEventResponse, error) {
  249. weightList := make([]*pasturePb.SearchWeightList, 0)
  250. var count int64 = 0
  251. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventWeight).TableName())).
  252. Select(`a.id,a.cow_id,a.ear_number,ROUND(a.weight/1000, 2) as weight,a.height,a.lact,a.day_age,a.weight_at,a.remarks,a.created_at,
  253. a.updated_at,a.message_id,a.operation_id,a.message_name,a.operation_name`)
  254. if len(req.CowId) > 0 {
  255. cowIds := strings.Split(req.CowId, ",")
  256. pref.Where("a.cow_id IN ?", cowIds)
  257. }
  258. if err := pref.Order("a.id desc").
  259. Count(&count).Limit(int(pagination.PageSize)).
  260. Offset(int(pagination.PageOffset)).
  261. Find(&weightList).Error; err != nil {
  262. return nil, xerr.WithStack(err)
  263. }
  264. return &pasturePb.SearchWeightEventResponse{
  265. Code: http.StatusOK,
  266. Msg: "ok",
  267. Data: &pasturePb.SearchWeightData{
  268. List: weightList,
  269. Total: int32(count),
  270. PageSize: pagination.PageSize,
  271. Page: pagination.Page,
  272. },
  273. }, nil
  274. }
  275. func (s *StoreEntry) WeightBatch(ctx context.Context, req *pasturePb.BatchEventWeight) (err error) {
  276. if len(req.Items) <= 0 {
  277. return xerr.Custom("称重数据不能为空")
  278. }
  279. userModel, err := s.GetUserModel(ctx)
  280. if err != nil {
  281. return xerr.WithStack(err)
  282. }
  283. defer func() {
  284. if err == nil {
  285. // 记录事件日志
  286. for _, item := range req.Items {
  287. cow, _ := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(item.CowId))
  288. cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, cow, pasturePb.EventType_Weight, pasturePb.ExposeEstrusType_Invalid, item)
  289. s.DB.Table(cowLogs.TableName()).Create(cowLogs)
  290. }
  291. }
  292. }()
  293. cow := &model.Cow{}
  294. for _, item := range req.Items {
  295. cow, err = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(item.CowId))
  296. if err != nil {
  297. return xerr.WithStack(err)
  298. }
  299. // 更新牛只信息
  300. cow.EventWeightUpdate(int64(item.Weight*1000), int64(item.WeightAt))
  301. if err = s.DB.Model(new(model.Cow)).
  302. Select("last_second_weight_at", "last_second_weight", "last_weight_at", "current_weight").
  303. Where("id = ?", cow.Id).
  304. Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
  305. Updates(cow).Error; err != nil {
  306. return xerr.WithStack(err)
  307. }
  308. operationUser, _ := s.GetSystemUserById(ctx, int64(item.OperationId))
  309. item.OperationName = operationUser.Name
  310. // 创建牛只的体重记录
  311. eventWeight := model.NewEventWeight(userModel.AppPasture.Id, cow, userModel.SystemUser, item)
  312. if err = s.DB.Create(eventWeight).Error; err != nil {
  313. return xerr.WithStack(err)
  314. }
  315. }
  316. return err
  317. }