event_base.go 12 KB

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