feed_service.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. package backend
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "kpt-tmr-group/model"
  10. "net/http"
  11. "strconv"
  12. "sync"
  13. "time"
  14. operationPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/operation"
  15. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  16. "gitee.com/xuyiping_admin/pkg/xerr"
  17. "go.uber.org/multierr"
  18. "github.com/xuri/excelize/v2"
  19. "go.uber.org/zap"
  20. "gorm.io/gorm"
  21. )
  22. const EncodeNumberPrefix = "encode_number"
  23. var PastureDataLogType = map[string]int32{
  24. "FeedFormula_Distribute": 1,
  25. "FeedFormula_IsModify": 2,
  26. "FeedFormula_Cancel_Distribute": 3,
  27. }
  28. var EditRecodeMap = map[string]string{
  29. "forage_name": "饲料名称",
  30. "weight": "重量",
  31. "stir_delay": "搅拌延迟",
  32. "allow_error": "允许误差",
  33. "sort": "排序",
  34. }
  35. // CreateFeedFormula 添加数据
  36. func (s *StoreEntry) CreateFeedFormula(ctx context.Context, req *operationPb.AddFeedFormulaRequest) error {
  37. forage := model.NewFeedFormula(req)
  38. if err := s.DB.Create(forage).Error; err != nil {
  39. return xerr.WithStack(err)
  40. }
  41. return nil
  42. }
  43. // EditFeedFormula 编辑数据
  44. func (s *StoreEntry) EditFeedFormula(ctx context.Context, req *operationPb.AddFeedFormulaRequest) error {
  45. feedFormula := &model.FeedFormula{Id: int64(req.Id)}
  46. if err := s.DB.Where("is_delete = ?", operationPb.IsShow_OK).First(feedFormula).Error; err != nil {
  47. if errors.Is(err, gorm.ErrRecordNotFound) {
  48. return xerr.Custom("该数据不存在")
  49. }
  50. return xerr.WithStack(err)
  51. }
  52. // 更新版本号
  53. defer s.UpdateFeedFormalVersion(ctx, feedFormula)
  54. updateData := &model.FeedFormula{
  55. Name: req.Name,
  56. Colour: req.Colour,
  57. CattleCategoryId: req.CattleCategoryId,
  58. CattleCategoryName: req.CattleCategoryName,
  59. FormulaTypeId: req.FormulaTypeId,
  60. FormulaTypeName: req.FormulaTypeName,
  61. DataSourceId: req.DataSourceId,
  62. DataSourceName: req.DataSourceName,
  63. Remarks: req.Remarks,
  64. IsShow: req.IsShow,
  65. }
  66. if err := s.DB.Model(new(model.FeedFormula)).
  67. Omit("is_show", "is_delete", "encode_number", "formula_type_id", "formula_type_name", "data_source", "is_modify").
  68. Where("id = ?", req.Id).
  69. Updates(updateData).Error; err != nil {
  70. return xerr.WithStack(err)
  71. }
  72. return nil
  73. }
  74. // AddFeedByFeedFormula 配方添加饲料
  75. func (s *StoreEntry) AddFeedByFeedFormula(ctx context.Context, req *operationPb.GroupAddFeedFormulaDetail) error {
  76. feedFormulaData := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  77. if err := s.DB.Model(new(model.FeedFormula)).First(feedFormulaData).Error; err != nil {
  78. return xerr.WithStack(err)
  79. }
  80. // 更新修改记录
  81. defer s.addFeedFormulaDetailAddRecode(ctx, req)
  82. // 更新版本号
  83. defer s.UpdateFeedFormalVersion(ctx, feedFormulaData)
  84. insertData := make([]*model.FeedFormulaDetail, 0)
  85. for _, v := range req.List {
  86. feedData := &model.Forage{Id: int64(v.ForageId)}
  87. if err := s.DB.Model(new(model.Forage)).First(feedData).Error; err != nil {
  88. return xerr.WithStack(err)
  89. }
  90. if v.AllowError > v.StirDelay {
  91. return xerr.Customf("允许误差不能大于搅拌延迟")
  92. }
  93. insertData = append(insertData, &model.FeedFormulaDetail{
  94. PastureName: "集团",
  95. FeedFormulaId: int64(req.FeedFormulaId),
  96. ForageId: int64(v.ForageId),
  97. ForageName: v.ForageName,
  98. ForageGroupName: v.ForageGroupName,
  99. Weight: int32(v.Weight * 100),
  100. StirDelay: v.StirDelay,
  101. AllowError: v.AllowError,
  102. IsShow: operationPb.IsShow_OK,
  103. IsModify: v.IsModify,
  104. Sort: v.Sort,
  105. })
  106. }
  107. if err := s.DB.Model(new(model.FeedFormulaDetail)).Save(insertData).Error; err != nil {
  108. return xerr.WithStack(err)
  109. }
  110. return nil
  111. }
  112. // addFeedFormulaDetailAddRecode 添加配方记录
  113. func (s *StoreEntry) addFeedFormulaDetailAddRecode(ctx context.Context, req *operationPb.GroupAddFeedFormulaDetail) {
  114. editRecord, _ := s.GetEditRecordLastGroupId(ctx)
  115. editRecordList := make([]*model.FeedFormulaEditRecord, 0)
  116. for _, v := range req.List {
  117. editRecordList = append(editRecordList, &model.FeedFormulaEditRecord{
  118. FeedFormulaId: int64(req.FeedFormulaId),
  119. PastureName: "集团",
  120. ForageName: v.ForageName,
  121. Status: operationPb.FeedFormulaEditRecordType_INSERT,
  122. GroupId: editRecord.GroupId + 1,
  123. })
  124. }
  125. if err := s.CreateFeedFormulaEditRecord(ctx, editRecordList); err != nil {
  126. zaplog.Error("deleteFeedFormulaDetailAddRecode", zap.Any("CreateFeedFormulaEditRecord", err))
  127. }
  128. }
  129. // EditFeedByFeedFormula 配方饲料编辑
  130. func (s *StoreEntry) EditFeedByFeedFormula(ctx context.Context, req *operationPb.AddFeedFormulaDetail) error {
  131. feedFormulaData := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  132. if err := s.DB.Model(new(model.FeedFormula)).First(feedFormulaData).Error; err != nil {
  133. return xerr.WithStack(err)
  134. }
  135. feedFormulaDetail := &model.FeedFormulaDetail{Id: int64(req.Id)}
  136. if err := s.DB.Model(new(model.FeedFormulaDetail)).
  137. Where("is_show = ?", operationPb.IsShow_OK).
  138. First(feedFormulaDetail).Error; err != nil {
  139. return xerr.WithStack(err)
  140. }
  141. // 添加修改记录
  142. defer s.editFeedFormulaDetailAddRecode(ctx, req, feedFormulaDetail)
  143. // 更新版本号
  144. defer s.UpdateFeedFormalVersion(ctx, feedFormulaData)
  145. // 更新数据
  146. updateData := &model.FeedFormulaDetail{
  147. ForageId: int64(req.ForageId),
  148. ForageName: req.ForageName,
  149. ForageGroupName: req.ForageGroupName,
  150. Weight: int32(req.Weight * 100),
  151. StirDelay: req.StirDelay,
  152. AllowError: req.AllowError,
  153. Sort: req.Sort,
  154. }
  155. if err := s.DB.Model(new(model.FeedFormulaDetail)).Where("id = ?", req.Id).Updates(updateData).Error; err != nil {
  156. return xerr.WithStack(err)
  157. }
  158. return nil
  159. }
  160. // EditFeedFormulaDetailAddRecode 更新饲料配方修改记录
  161. func (s *StoreEntry) editFeedFormulaDetailAddRecode(ctx context.Context, req *operationPb.AddFeedFormulaDetail, feedFormulaDetail *model.FeedFormulaDetail) {
  162. editRecordList := make([]*model.FeedFormulaEditRecord, 0)
  163. editRecordData := &model.FeedFormulaEditRecord{
  164. FeedFormulaId: int64(req.FeedFormulaId),
  165. PastureName: "集团",
  166. ForageName: req.ForageName,
  167. Status: operationPb.FeedFormulaEditRecordType_UPDATE,
  168. }
  169. if operationName, err := s.GetCurrentUserName(ctx); err != nil {
  170. zaplog.Error("EditFeedByFeedFormula", zap.Any("GetCurrentUserName", err))
  171. } else {
  172. editRecordData.OperationName = operationName
  173. }
  174. lastGroupIdData := &model.FeedFormulaEditRecord{}
  175. if err := s.DB.Model(new(model.FeedFormulaEditRecord)).
  176. Where("is_show = ?", operationPb.IsShow_OK).
  177. Order("group_id desc").
  178. First(&lastGroupIdData).Error; err != nil {
  179. zaplog.Error("EditFeedByFeedFormula", zap.Any("lastGroupIdData", err))
  180. } else {
  181. editRecordData.GroupId = lastGroupIdData.GroupId + 1
  182. editRecordData.BeforeValue = lastGroupIdData.BeforeValue
  183. }
  184. if feedFormulaDetail.ForageName != req.ForageName {
  185. editRecordData.FieldName = EditRecodeMap["forage_name"]
  186. editRecordData.BeforeValue = lastGroupIdData.ForageName
  187. editRecordData.AfterValue = req.ForageName
  188. editRecordList = append(editRecordList, editRecordData)
  189. }
  190. if feedFormulaDetail.Weight != int32(req.Weight*100) {
  191. editRecordData.FieldName = EditRecodeMap["weight"]
  192. editRecordData.AfterValue = fmt.Sprintf("%d", int32(req.Weight*100))
  193. editRecordList = append(editRecordList, editRecordData)
  194. }
  195. if feedFormulaDetail.AllowError != req.AllowError {
  196. editRecordData.FieldName = EditRecodeMap["allow_error"]
  197. editRecordData.AfterValue = fmt.Sprintf("%d", req.AllowError)
  198. editRecordList = append(editRecordList, editRecordData)
  199. }
  200. if feedFormulaDetail.StirDelay != req.StirDelay {
  201. editRecordData.FieldName = EditRecodeMap["stir_delay"]
  202. editRecordData.AfterValue = fmt.Sprintf("%d", req.StirDelay)
  203. editRecordList = append(editRecordList, editRecordData)
  204. }
  205. if feedFormulaDetail.Sort != req.Sort {
  206. editRecordData.FieldName = EditRecodeMap["sort"]
  207. editRecordData.AfterValue = fmt.Sprintf("%d", req.Sort)
  208. editRecordList = append(editRecordList, editRecordData)
  209. }
  210. if err := s.CreateFeedFormulaEditRecord(ctx, editRecordList); err != nil {
  211. zaplog.Error("EditFeedByFeedFormula", zap.Any("CreateFeedFormulaEditRecord", err))
  212. }
  213. }
  214. // CreateFeedFormulaEditRecord 创建配方修改记录
  215. func (s *StoreEntry) CreateFeedFormulaEditRecord(ctx context.Context, req []*model.FeedFormulaEditRecord) error {
  216. if req == nil {
  217. return nil
  218. }
  219. if err := s.DB.Model(new(model.FeedFormulaEditRecord)).Save(req).Error; err != nil {
  220. return xerr.WithStack(err)
  221. }
  222. return nil
  223. }
  224. // FeedFormulaDetailBySort 配方饲料排序
  225. func (s *StoreEntry) FeedFormulaDetailBySort(ctx context.Context, req *operationPb.GroupAddFeedFormulaDetail) error {
  226. feedFormulaData := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  227. if err := s.DB.Model(new(model.FeedFormula)).First(feedFormulaData).Error; err != nil {
  228. return xerr.WithStack(err)
  229. }
  230. // 更新版本号
  231. defer s.UpdateFeedFormalVersion(ctx, feedFormulaData)
  232. tx := s.DB.Transaction(func(tx *gorm.DB) error {
  233. for _, v := range req.List {
  234. if err := tx.Model(new(model.FeedFormulaDetail)).
  235. Where("id = ?", v.Id).
  236. Updates(map[string]interface{}{
  237. "sort": v.Sort,
  238. }).Error; err != nil {
  239. return xerr.WithStack(err)
  240. }
  241. }
  242. return nil
  243. })
  244. return tx
  245. }
  246. // FeedFormulaDetailIsModify 配方饲料是否可修改
  247. func (s *StoreEntry) FeedFormulaDetailIsModify(ctx context.Context, req *operationPb.AddFeedFormulaDetail) error {
  248. feedFormulaData := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  249. if err := s.DB.Model(new(model.FeedFormula)).First(feedFormulaData).Error; err != nil {
  250. return xerr.WithStack(err)
  251. }
  252. // 更新版本号
  253. defer s.UpdateFeedFormalVersion(ctx, feedFormulaData)
  254. return s.DB.Model(new(model.FeedFormulaDetail)).
  255. Where("id = ?", req.Id).
  256. Where("feed_formula_id = ?", req.FeedFormulaId).
  257. Updates(map[string]interface{}{
  258. "is_modify": req.IsModify,
  259. }).Error
  260. }
  261. // DeleteFeedFormulaDetail 配方删除饲料
  262. func (s *StoreEntry) DeleteFeedFormulaDetail(ctx context.Context, req *operationPb.GroupAddFeedFormulaDetail) error {
  263. feedFormulaData := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  264. if err := s.DB.Model(new(model.FeedFormula)).First(feedFormulaData).Error; err != nil {
  265. return xerr.WithStack(err)
  266. }
  267. // 增加配方记录
  268. defer s.deleteFeedFormulaDetailAddRecode(ctx, req)
  269. tr := s.DB.Transaction(func(tx *gorm.DB) error {
  270. for _, v := range req.List {
  271. if err := tx.Model(new(model.FeedFormulaDetail)).
  272. Where("id = ?", v.Id).
  273. Updates(map[string]interface{}{
  274. "is_show": operationPb.IsShow_NO,
  275. }).Error; err != nil {
  276. return xerr.WithStack(err)
  277. }
  278. }
  279. return nil
  280. })
  281. return tr
  282. }
  283. // deleteFeedFormulaDetailAddRecode 删除配方增加修改记录
  284. func (s *StoreEntry) deleteFeedFormulaDetailAddRecode(ctx context.Context, req *operationPb.GroupAddFeedFormulaDetail) {
  285. editRecordList := make([]*model.FeedFormulaEditRecord, 0)
  286. for _, v := range req.List {
  287. editRecordList = append(editRecordList, &model.FeedFormulaEditRecord{
  288. FeedFormulaId: int64(req.FeedFormulaId),
  289. PastureName: "集团",
  290. ForageName: v.ForageName,
  291. Status: operationPb.FeedFormulaEditRecordType_DELETE,
  292. })
  293. }
  294. if err := s.CreateFeedFormulaEditRecord(ctx, editRecordList); err != nil {
  295. zaplog.Error("deleteFeedFormulaDetailAddRecode", zap.Any("CreateFeedFormulaEditRecord", err))
  296. }
  297. }
  298. // SearchFeedFormulaDetail 查询配方饲料详情
  299. func (s *StoreEntry) SearchFeedFormulaDetail(ctx context.Context, req *operationPb.AddFeedFormulaDetail) (*operationPb.FeedFormulaDetailResponse, error) {
  300. feedFormulaData := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  301. if err := s.DB.Model(new(model.FeedFormula)).First(feedFormulaData).Debug().Error; err != nil {
  302. return nil, xerr.WithStack(err)
  303. }
  304. var count int64
  305. feedFormulaDetailList := make([]*model.FeedFormulaDetail, 0)
  306. pref := s.DB.Model(new(model.FeedFormulaDetail)).
  307. Where("is_show = ?", operationPb.IsShow_OK).
  308. Where("feed_formula_id = ?", req.FeedFormulaId)
  309. if req.ForageName != "" {
  310. pref.Where("forage_name = ?", req.ForageName)
  311. }
  312. if req.ForageGroupName != "" {
  313. pref.Where("forage_group_name = ?", req.ForageGroupName)
  314. }
  315. if req.Weight > 0 {
  316. pref.Where("weight = ?", int64(req.Weight*100))
  317. }
  318. if req.IsLockCowCountRatio > 0 {
  319. pref.Where("is_lock_cow_count_ratio = ?", req.IsLockCowCountRatio)
  320. }
  321. if req.StirDelay > 0 {
  322. pref.Where("stir_delay = ?", req.StirDelay)
  323. }
  324. if req.Sort > 0 {
  325. pref.Where("sort = ?", req.Sort)
  326. }
  327. if err := pref.Order("sort").Count(&count).Limit(int(req.Pagination.PageSize)).
  328. Offset(int(req.Pagination.PageOffset)).Find(&feedFormulaDetailList).Debug().Error; err != nil {
  329. return nil, xerr.WithStack(err)
  330. }
  331. return &operationPb.FeedFormulaDetailResponse{
  332. Code: http.StatusOK,
  333. Msg: "ok",
  334. Data: model.FeedFormulaDetailSlice(feedFormulaDetailList).ToPB(),
  335. }, nil
  336. }
  337. // MixedFeedFormula 合成预混料
  338. func (s *StoreEntry) MixedFeedFormula(ctx context.Context, req *operationPb.MixedFeedFormulaRequest) error {
  339. feedFormulaData := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  340. if err := s.DB.Model(new(model.FeedFormula)).First(feedFormulaData).Error; err != nil {
  341. return xerr.WithStack(err)
  342. }
  343. if feedFormulaData.FormulaTypeId == operationPb.FormulaType_PREMIXED_FORMULA {
  344. return xerr.Customf("预混料配方不能合成预混料")
  345. }
  346. tr := s.DB.Transaction(func(tx *gorm.DB) error {
  347. newFeedFormulaData := model.NewNewFeedFormulaByMixed(req)
  348. newFeedFormulaData.EncodeNumber = s.EncodeNumber(ctx)
  349. if err := s.DB.Model(new(model.FeedFormula)).Create(newFeedFormulaData).Error; err != nil {
  350. return xerr.WithStack(err)
  351. }
  352. feedFormulaDetailList := make([]*model.FeedFormulaDetail, 0)
  353. for _, v := range req.FeedList {
  354. feedFormulaDetailList = append(feedFormulaDetailList, &model.FeedFormulaDetail{
  355. PastureName: "集团",
  356. FeedFormulaId: newFeedFormulaData.Id,
  357. ForageId: int64(v.ForageId),
  358. ForageName: v.ForageName,
  359. ForageGroupName: v.ForageGroupName,
  360. Weight: int32(v.Weight * 100),
  361. StirDelay: v.StirDelay,
  362. AllowError: v.AllowError,
  363. IsShow: operationPb.IsShow_OK,
  364. Sort: v.Sort,
  365. })
  366. }
  367. if err := s.DB.Model(new(model.FeedFormulaDetail)).Save(feedFormulaDetailList).Error; err != nil {
  368. return xerr.WithStack(err)
  369. }
  370. return nil
  371. })
  372. return tr
  373. }
  374. // SearchFeedFormulaList 查询数据列表
  375. func (s *StoreEntry) SearchFeedFormulaList(ctx context.Context, req *operationPb.SearchFeedFormulaRequest) (*operationPb.SearchFeedFormulaListResponse, error) {
  376. feedFormula := make([]*model.FeedFormula, 0)
  377. var count int64 = 0
  378. pref := s.DB.Model(new(model.FeedFormula)).Where("is_delete = ?", operationPb.IsShow_OK)
  379. if req.Name != "" {
  380. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  381. }
  382. if req.CattleCategoryId > 0 {
  383. pref.Where("cattle_category_id = ?", req.CattleCategoryId)
  384. }
  385. if req.FormulaTypeId > 0 {
  386. pref.Where("formula_type_id = ?", req.FormulaTypeId)
  387. }
  388. if req.IsShow > 0 {
  389. pref.Where("is_show = ?", req.IsShow)
  390. }
  391. if req.DataSource > 0 {
  392. pref.Where("data_source = ?", req.DataSource)
  393. }
  394. if req.Remarks != "" {
  395. pref.Where("remarks = ?", req.Remarks)
  396. }
  397. if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  398. Find(&feedFormula).Error; err != nil {
  399. return nil, xerr.WithStack(err)
  400. }
  401. return &operationPb.SearchFeedFormulaListResponse{
  402. Code: http.StatusOK,
  403. Msg: "ok",
  404. Data: &operationPb.SearchFeedFormulaListData{
  405. Page: req.Pagination.Page,
  406. PageSize: req.Pagination.PageSize,
  407. Total: int32(count),
  408. List: model.FeedFormulaSlice(feedFormula).ToPB(),
  409. },
  410. }, nil
  411. }
  412. // SearchFeedFormulaById 查询指定数据
  413. func (s *StoreEntry) SearchFeedFormulaById(ctx context.Context, foodFormulaId int64) (*model.FeedFormula, error) {
  414. feedFormula := &model.FeedFormula{}
  415. if err := s.DB.Model(new(model.FeedFormula)).
  416. Where("is_delete = ?", operationPb.IsShow_OK).
  417. Where("id = ?", foodFormulaId).
  418. First(feedFormula).Error; err != nil {
  419. return nil, xerr.WithStack(err)
  420. }
  421. return feedFormula, nil
  422. }
  423. // IsShowFeedFormula 是否启用和是否可修改
  424. func (s *StoreEntry) IsShowFeedFormula(ctx context.Context, req *operationPb.IsShowModifyFeedFormula) error {
  425. feedFormula := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  426. if err := s.DB.First(feedFormula).Error; err != nil {
  427. if errors.Is(err, gorm.ErrRecordNotFound) {
  428. return xerr.Custom("该数据不存在")
  429. }
  430. return xerr.WithStack(err)
  431. }
  432. if req.EditType == 1 {
  433. if err := s.DB.Model(new(model.FeedFormula)).Where("id = ?", req.FeedFormulaId).Update("is_show", req.IsShow).Error; err != nil {
  434. return xerr.WithStack(err)
  435. }
  436. }
  437. if req.EditType == 2 {
  438. if err := s.DB.Model(new(model.FeedFormula)).Where("id = ?", req.FeedFormulaId).Update("is_modify", req.IsShow).Error; err != nil {
  439. return xerr.WithStack(err)
  440. } else {
  441. s.PastureFeedFormulaIsModify(ctx, req.FeedFormulaId, req.IsShow)
  442. }
  443. }
  444. return nil
  445. }
  446. // DeleteFeedFormula 是否删除
  447. func (s *StoreEntry) DeleteFeedFormula(ctx context.Context, feedFormulaId int64) error {
  448. feedFormula := &model.FeedFormula{Id: feedFormulaId}
  449. if err := s.DB.First(feedFormula).Error; err != nil {
  450. if errors.Is(err, gorm.ErrRecordNotFound) {
  451. return xerr.Custom("该数据不存在")
  452. }
  453. return xerr.WithStack(err)
  454. }
  455. if err := s.DB.Model(new(model.FeedFormula)).Where("id = ?", feedFormula.Id).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {
  456. return xerr.WithStack(err)
  457. }
  458. return nil
  459. }
  460. // ExcelImportFeedFormula 导入excel
  461. func (s *StoreEntry) ExcelImportFeedFormula(ctx context.Context, req io.Reader) error {
  462. xlsx, err := excelize.OpenReader(req)
  463. if err != nil {
  464. return xerr.WithStack(err)
  465. }
  466. defer xlsx.Close()
  467. rows, err := xlsx.GetRows(xlsx.GetSheetName(xlsx.GetActiveSheetIndex()))
  468. if err != nil {
  469. return xerr.WithStack(err)
  470. }
  471. if len(rows) > 10000 {
  472. rows = rows[:10000]
  473. }
  474. feedFormulaList := make([]*model.FeedFormula, 0)
  475. for i, row := range rows {
  476. if i == 0 {
  477. continue
  478. }
  479. var (
  480. name, encodeNumber, cattleCategoryName, formulaTypeName, dataSourceName, remarks, isShowStr string
  481. isShow operationPb.IsShow_Kind
  482. )
  483. for k, v := range row {
  484. if k == 0 {
  485. name = v
  486. }
  487. if k == 1 {
  488. encodeNumber = v
  489. }
  490. if k == 2 {
  491. cattleCategoryName = v
  492. }
  493. if k == 3 {
  494. formulaTypeName = v
  495. }
  496. if k == 4 {
  497. dataSourceName = v
  498. }
  499. if k == 5 {
  500. remarks = v
  501. }
  502. if k == 6 {
  503. isShowStr = v
  504. }
  505. }
  506. if isShowStr == "是" {
  507. isShow = operationPb.IsShow_OK
  508. } else {
  509. isShow = operationPb.IsShow_NO
  510. }
  511. feedFormulaItem := &model.FeedFormula{
  512. Name: name,
  513. EncodeNumber: encodeNumber,
  514. CattleCategoryName: cattleCategoryName,
  515. FormulaTypeName: formulaTypeName,
  516. Remarks: remarks,
  517. IsShow: isShow,
  518. IsDelete: operationPb.IsShow_OK,
  519. DataSourceId: operationPb.DataSource_EXCEL_IMPORT,
  520. DataSourceName: dataSourceName,
  521. }
  522. feedFormulaList = append(feedFormulaList, feedFormulaItem)
  523. }
  524. if len(feedFormulaList) > 0 {
  525. if err = s.DB.Create(feedFormulaList).Error; err != nil {
  526. return xerr.WithStack(err)
  527. }
  528. }
  529. return nil
  530. }
  531. // ExcelExportFeedFormula 流式导出excel
  532. func (s *StoreEntry) ExcelExportFeedFormula(ctx context.Context, req *operationPb.SearchFeedFormulaRequest) (*bytes.Buffer, error) {
  533. res, err := s.SearchFeedFormulaList(ctx, req)
  534. if err != nil {
  535. return nil, xerr.WithStack(err)
  536. }
  537. if len(res.Data.List) <= 0 {
  538. return nil, xerr.Custom("数据为空")
  539. }
  540. file := excelize.NewFile()
  541. defer file.Close()
  542. streamWriter, err := file.NewStreamWriter("Sheet1")
  543. if err != nil {
  544. return nil, xerr.WithStack(err)
  545. }
  546. titles := []interface{}{"配方名称", "配方编码", "畜牧类别", "配方类别", "来源", "备注", "是否启用",
  547. "饲料组", "饲料名称", "重量(kg)", "搅拌延迟(min)", "是否锁定牛头数比例", "顺序"}
  548. if err = streamWriter.SetRow("A1", titles); err != nil {
  549. return nil, xerr.WithStack(err)
  550. }
  551. for i, item := range res.Data.List {
  552. cell, err := excelize.CoordinatesToCellName(1, i+2)
  553. if err != nil {
  554. zaplog.Error("exclude CoordinatesToCellName", zap.Any("Err", err))
  555. continue
  556. }
  557. row := make([]interface{}, 0)
  558. row = append(row, item.Name, item.EncodeNumber, item.CattleCategoryName, item.FormulaTypeName, item.DataSourceName,
  559. item.Remarks, item.IsShow)
  560. if err = streamWriter.SetRow(cell, row); err != nil {
  561. return nil, xerr.WithStack(err)
  562. }
  563. }
  564. if err = streamWriter.Flush(); err != nil {
  565. return nil, xerr.WithStack(err)
  566. }
  567. return file.WriteToBuffer()
  568. }
  569. // ExcelTemplateFeedFormula 导出模板
  570. func (s *StoreEntry) ExcelTemplateFeedFormula(ctx context.Context) (*bytes.Buffer, error) {
  571. file := excelize.NewFile()
  572. defer file.Close()
  573. streamWriter, err := file.NewStreamWriter("Sheet1")
  574. if err != nil {
  575. return nil, xerr.WithStack(err)
  576. }
  577. titles := []interface{}{"配方名称", "配方编码", "畜牧类别", "配方类别", "来源", "备注", "是否启用",
  578. "饲料组", "饲料名称", "重量(kg)", "搅拌延迟(min)", "是否锁定牛头数比例", "顺序"}
  579. if err = streamWriter.SetRow("A1", titles); err != nil {
  580. return nil, xerr.WithStack(err)
  581. }
  582. if err = streamWriter.Flush(); err != nil {
  583. return nil, xerr.WithStack(err)
  584. }
  585. return file.WriteToBuffer()
  586. }
  587. // EncodeNumber 配方编码
  588. func (s *StoreEntry) EncodeNumber(ctx context.Context) string {
  589. currTime := time.Now().Format(model.LayoutDate)
  590. prefix := fmt.Sprintf("%s_%s", EncodeNumberPrefix, currTime)
  591. data := &model.UniqueData{}
  592. if err := s.DB.Order("id desc").Where("prefix = ?", prefix).First(data).Error; err != nil {
  593. if !errors.Is(err, gorm.ErrRecordNotFound) {
  594. return ""
  595. }
  596. ud, _ := strconv.Atoi(currTime)
  597. result := ud*100 + 1
  598. newData := &model.UniqueData{
  599. Prefix: prefix,
  600. Data: int64(result),
  601. }
  602. if err = s.DB.Create(newData).Error; err != nil {
  603. zaplog.Error("EncodeNumber Create", zap.Any("data", newData), zap.Any("Err", err))
  604. return ""
  605. }
  606. return fmt.Sprintf("%d", newData.Data)
  607. }
  608. data.Data += 1
  609. if err := s.DB.Model(new(model.UniqueData)).Where("prefix = ?", prefix).Update("data", data.Data).Error; err != nil {
  610. return ""
  611. } else {
  612. return fmt.Sprintf("%d", data.Data)
  613. }
  614. }
  615. // DistributeFeedFormula 配方下发牧场
  616. func (s *StoreEntry) DistributeFeedFormula(ctx context.Context, req *operationPb.DistributeFeedFormulaRequest) error {
  617. distributeData, err := s.checkoutDistributeData(ctx, req)
  618. if err != nil {
  619. return xerr.WithStack(err)
  620. }
  621. wg := sync.WaitGroup{}
  622. wg.Add(len(distributeData.PastureList))
  623. var muError error
  624. for _, pasture := range distributeData.PastureList {
  625. go func(p *operationPb.AddPastureRequest) {
  626. defer wg.Done()
  627. // 过滤掉自己本牧场上报的配方数据
  628. newDistributeFeedRequest := make([]*operationPb.DistributeFeedRequest, 0)
  629. for _, v := range distributeData.FeedFormulaList {
  630. if v.PastureId != p.Id {
  631. newDistributeFeedRequest = append(newDistributeFeedRequest, v)
  632. }
  633. }
  634. if len(newDistributeFeedRequest) <= 0 {
  635. return
  636. }
  637. // 过滤掉已经下发过配方
  638. putDistributeFeedRequest := make([]*operationPb.DistributeFeedRequest, 0)
  639. for _, v := range newDistributeFeedRequest {
  640. if !s.CheckFeedFormulaDistribute(ctx, int64(p.Id), int64(v.Id)) {
  641. putDistributeFeedRequest = append(putDistributeFeedRequest, v)
  642. }
  643. }
  644. if len(putDistributeFeedRequest) <= 0 {
  645. return
  646. }
  647. // 请求参数
  648. request, response := &operationPb.DistributeDataRequest{
  649. PastureId: p.PastureId,
  650. FeedFormulaList: newDistributeFeedRequest,
  651. }, &model.PastureResponse{
  652. Code: 0,
  653. Msg: "",
  654. Data: &model.PastureSuccess{Success: false},
  655. }
  656. defer func() {
  657. if response.Code == http.StatusOK {
  658. feedFormulaDistributeLog := model.NewFeedFormulaDistributeLogList(distributeData.FeedFormulaList, int64(p.Id), p.Name, operationPb.IsShow_OK)
  659. if err = s.DB.Create(feedFormulaDistributeLog).Error; err != nil {
  660. zaplog.Error("DistributeFeedFormula", zap.Any("feedFormulaDistributeLog", feedFormulaDistributeLog), zap.Any("err", err))
  661. }
  662. } else {
  663. muError = multierr.Append(muError, err)
  664. }
  665. }()
  666. if err = s.PastureHttpClient(ctx, model.FeedFormulaDistributeUrl, int64(p.Id), request, response); err != nil {
  667. muError = multierr.Append(muError, err)
  668. zaplog.Error("DistributeFeedFormula",
  669. zap.Any("pasture", p),
  670. zap.Any("body", distributeData.FeedFormulaList),
  671. zap.Any("err", err),
  672. zap.Any("response", response),
  673. )
  674. b, _ := json.Marshal(request)
  675. res, _ := json.Marshal(response)
  676. pastureDataLog := model.NewPastureDataLog(int64(p.Id), PastureDataLogType["FeedFormula_Distribute"], model.FeedFormulaDistributeUrl, string(b), string(res))
  677. if err = s.DB.Create(pastureDataLog).Error; err != nil {
  678. zaplog.Error("DistributeFeedFormula", zap.Any("pastureDataLog", pastureDataLog), zap.Any("err", err))
  679. }
  680. }
  681. }(pasture)
  682. }
  683. wg.Wait()
  684. return xerr.WithStack(muError)
  685. }
  686. // CancelDistributeFeedFormula 取消配方下发牧场
  687. func (s *StoreEntry) CancelDistributeFeedFormula(ctx context.Context, req *operationPb.DistributeFeedFormulaRequest) error {
  688. distributeData, err := s.checkoutDistributeData(ctx, req)
  689. if err != nil {
  690. return xerr.WithStack(err)
  691. }
  692. wg := sync.WaitGroup{}
  693. wg.Add(len(distributeData.PastureList))
  694. var muError error
  695. for _, pasture := range distributeData.PastureList {
  696. go func(p *operationPb.AddPastureRequest) {
  697. defer wg.Done()
  698. pastureDataId := make([]int64, 0)
  699. for _, v := range distributeData.FeedFormulaList {
  700. if v.PastureId == p.Id {
  701. pastureDataId = append(pastureDataId, int64(v.PastureDataId))
  702. }
  703. }
  704. if len(pastureDataId) <= 0 {
  705. return
  706. }
  707. request := &model.CancelDistributeFeedFormulaRequest{
  708. PastureId: int64(p.Id),
  709. PastureDataId: pastureDataId,
  710. }
  711. response := &model.PastureResponse{}
  712. if err = s.PastureHttpClient(ctx, model.FeedFormulaCancelDistributeUrl, int64(p.Id), request, response); err != nil {
  713. zaplog.Error("DistributeFeedFormula",
  714. zap.String("url", model.FeedFormulaCancelDistributeUrl),
  715. zap.Any("pasture", p),
  716. zap.Any("body", distributeData.FeedFormulaList),
  717. zap.Any("err", err),
  718. zap.Any("response", response))
  719. b, _ := json.Marshal(request)
  720. res, _ := json.Marshal(response)
  721. pastureDataLog := model.NewPastureDataLog(int64(p.Id), PastureDataLogType["FeedFormula_Cancel_Distribute"], model.FeedFormulaCancelDistributeUrl, string(b), string(res))
  722. s.DB.Create(pastureDataLog)
  723. }
  724. }(pasture)
  725. }
  726. wg.Wait()
  727. return muError
  728. }
  729. // EditRecodeFeedFormula 配方修改记录
  730. func (s *StoreEntry) EditRecodeFeedFormula(ctx context.Context, req *operationPb.EditRecodeFeedFormulaRequest) (*operationPb.EditRecodeFeedFormulaResponse, error) {
  731. feedFormulaData := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  732. if err := s.DB.Model(new(model.FeedFormula)).First(feedFormulaData).Error; err != nil {
  733. return nil, xerr.WithStack(err)
  734. }
  735. res := &operationPb.EditRecodeFeedFormulaResponse{
  736. Code: http.StatusOK,
  737. Msg: "ok",
  738. Data: make([]*operationPb.EditRecodeFeedFormulaData, 0),
  739. }
  740. feedFormulaEditRecordList := make([]*model.FeedFormulaEditRecord, 0)
  741. pref := s.DB.Model(new(model.FeedFormulaEditRecord)).Where("status > 0").Where("feed_formula_id = ?", req.FeedFormulaId)
  742. if req.PastureId > 0 {
  743. pref.Where("pasture_id = ?", req.PastureId)
  744. }
  745. if req.StartTime > 0 && req.EndTime > 0 && req.EndTime >= req.StartTime {
  746. pref.Where("created_at >= ?", req.StartTime).Where("created_at <= ?", req.EndTime)
  747. }
  748. if err := pref.Order("group_id").Find(&feedFormulaEditRecordList).Error; err != nil {
  749. return res, xerr.WithStack(err)
  750. }
  751. groupByFeedFormulaEditRecordList := make(map[int64][]*model.FeedFormulaEditRecord)
  752. for _, v := range feedFormulaEditRecordList {
  753. if groupByFeedFormulaEditRecordList[v.GroupId] == nil {
  754. groupByFeedFormulaEditRecordList[v.GroupId] = make([]*model.FeedFormulaEditRecord, 0)
  755. }
  756. groupByFeedFormulaEditRecordList[v.GroupId] = append(groupByFeedFormulaEditRecordList[v.GroupId], v)
  757. }
  758. editRecodeFeedFormulaDataList := make([]*operationPb.EditRecodeFeedFormulaData, 0)
  759. for _, data := range groupByFeedFormulaEditRecordList {
  760. var modifyDetail = ""
  761. var pastureId int32 = 0
  762. var pastureName = ""
  763. var createTime int64 = 0
  764. for i, v := range data {
  765. if i == 0 {
  766. modifyDetail += fmt.Sprintf("%s\n ", v.PastureName)
  767. pastureId = int32(v.PastureId)
  768. pastureName = v.PastureName
  769. createTime = v.CreatedAt
  770. }
  771. switch v.Status {
  772. case operationPb.FeedFormulaEditRecordType_INSERT:
  773. modifyDetail += fmt.Sprintf(`%s新增了饲料%s\n `, v.OperationName, v.ForageName)
  774. case operationPb.FeedFormulaEditRecordType_UPDATE:
  775. modifyDetail += fmt.Sprintf(`%s将%s的%s"%s"更新为"%s"\n `, v.OperationName, v.ForageName, v.FieldName, v.BeforeValue, v.AfterValue)
  776. case operationPb.FeedFormulaEditRecordType_DELETE:
  777. modifyDetail += fmt.Sprintf(`%s删除了%s\n `, v.OperationName, v.ForageName)
  778. }
  779. }
  780. editRecodeFeedFormulaDataList = append(editRecodeFeedFormulaDataList, &operationPb.EditRecodeFeedFormulaData{
  781. PastureId: pastureId,
  782. PastureName: pastureName,
  783. ModifyTime: time.Unix(createTime, 0).Format(model.LayoutTime),
  784. ModifyDetail: modifyDetail,
  785. })
  786. }
  787. res.Data = editRecodeFeedFormulaDataList
  788. return res, nil
  789. }
  790. func (s *StoreEntry) FeedFormulaDetailList(ctx context.Context, req *operationPb.FeedFormulaDetailRequest) (*operationPb.FeedFormulaDetailResponse, error) {
  791. res := &operationPb.FeedFormulaDetailResponse{
  792. Code: http.StatusOK,
  793. Msg: "ok",
  794. Data: make([]*operationPb.AddFeedFormulaDetail, 0),
  795. }
  796. feedFormula, err := s.SearchFeedFormulaById(ctx, int64(req.FeedFormulaId))
  797. if err != nil {
  798. return nil, xerr.WithStack(err)
  799. }
  800. feedFormulaId := feedFormula.Id
  801. if feedFormula.PastureDataId > 0 {
  802. feedFormulaId = feedFormula.PastureDataId
  803. }
  804. list, err := s.SearchFeedFormalDetailById(ctx, feedFormulaId, feedFormula.PastureId)
  805. if err != nil {
  806. return nil, xerr.WithStack(err)
  807. }
  808. if len(list) <= 0 {
  809. list, err = s.SearchFeedFormalDetailById(ctx, feedFormula.Id, 0)
  810. if err != nil {
  811. return nil, xerr.WithStack(err)
  812. }
  813. }
  814. res.Data = model.FeedFormulaDetailSlice(list).ToPB()
  815. return res, nil
  816. }
  817. // FeedFormulaUsage 配方使用概况
  818. func (s *StoreEntry) FeedFormulaUsage(ctx context.Context, req *operationPb.FeedFormulaUsageRequest) (*operationPb.FeedFormulaUsageResponse, error) {
  819. feedFormulaDistributeLogList := make([]*model.FeedFormulaDistributeLog, 0)
  820. if err := s.DB.Model(new(model.FeedFormulaDistributeLog)).
  821. Where("feed_formula_id = ?", req.FeedFormulaId).
  822. Where("is_show = ?", operationPb.IsShow_OK).Group("pasture_id").
  823. Find(&feedFormulaDistributeLogList).Error; err != nil {
  824. return nil, xerr.WithStack(err)
  825. }
  826. res := &operationPb.FeedFormulaUsageResponse{
  827. Code: http.StatusOK,
  828. Msg: "ok",
  829. Data: make([]*operationPb.FeedFormulaUsageList, 0),
  830. }
  831. wg := sync.WaitGroup{}
  832. wg.Add(len(feedFormulaDistributeLogList))
  833. for _, list := range feedFormulaDistributeLogList {
  834. go func(l *model.FeedFormulaDistributeLog) {
  835. defer wg.Done()
  836. groupDetail, err := s.PastureDetailById(ctx, l.PastureId)
  837. if err != nil {
  838. zaplog.Error("FeedFormulaUsage", zap.Any("PastureDetailById", err))
  839. return
  840. }
  841. req.PastureId = int32(groupDetail.PastureId)
  842. response := &operationPb.PastureFeedFormulaUsageResponse{}
  843. if err = s.PastureHttpClient(ctx, model.FeedUsageURl, groupDetail.Id, req, response); err != nil {
  844. zaplog.Error("FeedFormulaUsage", zap.Any("PastureDetailById", err))
  845. return
  846. }
  847. if response.Code == http.StatusOK {
  848. data := &operationPb.FeedFormulaUsageList{
  849. PastureId: int32(groupDetail.Id),
  850. PastureName: groupDetail.Name,
  851. MixedFodderAccurateRatio: response.Data.MixedFodderAccurateRatio,
  852. MixedFodderCorrectRatio: response.Data.MixedFodderCorrectRatio,
  853. SprinkleFodderAccurateRatio: response.Data.SprinkleFodderAccurateRatio,
  854. SprinkleFodderCorrectRatio: response.Data.SprinkleFodderCorrectRatio,
  855. AddFeedTime: response.Data.AddFeedTime,
  856. SprinkleTime: response.Data.SprinkleTime,
  857. StirTime: response.Data.StirTime,
  858. LastEditTime: response.Data.LastEditTime,
  859. }
  860. res.Data = append(res.Data, data)
  861. } else {
  862. zaplog.Error("FeedFormulaUsage-http", zap.Any("response", response))
  863. return
  864. }
  865. }(list)
  866. }
  867. wg.Wait()
  868. return res, nil
  869. }
  870. func (s *StoreEntry) PastureFeedFormulaIsModify(ctx context.Context, feedFormulaId int32, isModify operationPb.IsShow_Kind) {
  871. feedFormulaDistributeLogList := make([]*model.FeedFormulaDistributeLog, 0)
  872. if err := s.DB.Where("is_show = ?", operationPb.IsShow_OK).
  873. Where("feed_formula_id = ?", feedFormulaId).
  874. Group("pasture_id").Find(&feedFormulaDistributeLogList).Error; err != nil {
  875. zaplog.Error("PastureFeedFormulaIsModify", zap.Any("err", err), zap.Any("feed_formula_id", feedFormulaId))
  876. return
  877. }
  878. for _, v := range feedFormulaDistributeLogList {
  879. response := &model.PastureResponse{}
  880. request := &model.FeedFormulaIsModifyRequest{
  881. PastureId: v.PastureId,
  882. FeedFormulaId: v.FeedFormulaId,
  883. IsModify: int32(isModify),
  884. }
  885. if err := s.PastureHttpClient(ctx, model.FeedFormulaIsModifyUrl, v.Id, request, response); err != nil {
  886. zaplog.Error("PastureFeedFormulaIsModify", zap.Any("request", request), zap.Any("err", err), zap.Any("response", response))
  887. b, _ := json.Marshal(request)
  888. res, _ := json.Marshal(response)
  889. pastureDataLog := model.NewPastureDataLog(v.PastureId, PastureDataLogType["FeedFormula_IsModify"], model.FeedFormulaIsModifyUrl, string(b), string(res))
  890. s.DB.Create(pastureDataLog)
  891. }
  892. }
  893. }
  894. func (s *StoreEntry) checkoutDistributeData(ctx context.Context, req *operationPb.DistributeFeedFormulaRequest) (*operationPb.CheckDistributeData, error) {
  895. result := &operationPb.CheckDistributeData{
  896. PastureList: make([]*operationPb.AddPastureRequest, 0),
  897. FeedFormulaList: make([]*operationPb.DistributeFeedRequest, 0),
  898. }
  899. newGroupPastureList := make([]*model.GroupPasture, 0)
  900. if err := s.DB.Model(new(model.GroupPasture)).Where("id IN ?", req.PastureIds).Where("is_delete = ?", operationPb.IsShow_OK).Find(&newGroupPastureList).Error; err != nil {
  901. return result, xerr.WithStack(err)
  902. }
  903. result.PastureList = model.GroupPastureSlice(newGroupPastureList).ToPB()
  904. newFeedFormulaList := make([]*model.FeedFormula, 0)
  905. if err := s.DB.Model(new(model.FeedFormula)).Where("id IN ?", req.FeedFormulaIds).Find(&newFeedFormulaList).Error; err != nil {
  906. return result, xerr.WithStack(err)
  907. }
  908. result.FeedFormulaList = model.FeedFormulaSlice(newFeedFormulaList).ToDistributePB()
  909. if len(result.FeedFormulaList) != len(req.FeedFormulaIds) {
  910. return result, xerr.Customf("数据错误:%v", req.FeedFormulaIds)
  911. }
  912. for _, v := range result.FeedFormulaList {
  913. feedFormulaDetail := make([]*model.FeedFormulaDetail, 0)
  914. if err := s.DB.Model(new(model.FeedFormulaDetail)).Where("feed_formula_id = ?", v.Id).Find(&feedFormulaDetail).Error; err != nil {
  915. zaplog.Error("checkoutDistributeData", zap.Any("feed_formula_id", v.Id), zap.Any("err", err))
  916. return result, xerr.Customf("%v", err)
  917. }
  918. if len(feedFormulaDetail) <= 0 {
  919. return result, xerr.Customf("请先添加配方饲料信息: %s", v.Name)
  920. }
  921. v.FeedFormulaDetail = model.FeedFormulaDetailSlice(feedFormulaDetail).ToPB()
  922. }
  923. if len(result.PastureList) <= 0 || len(result.FeedFormulaList) <= 0 {
  924. return result, xerr.Customf("数据错误")
  925. }
  926. return result, nil
  927. }
  928. func (s *StoreEntry) checkoutDistributeLog(ctx context.Context, pastureId, feedFormulaId int64) bool {
  929. res := &model.FeedFormulaDistributeLog{}
  930. if err := s.DB.Model(new(model.FeedFormulaDistributeLog)).Where("feed_formula_id = ?", feedFormulaId).
  931. Where("pasture_id = ?", pastureId).Where("is_show = ?", operationPb.IsShow_OK).First(res).Error; err != nil {
  932. return false
  933. }
  934. if res.IsShow == operationPb.IsShow_OK {
  935. return true
  936. }
  937. return false
  938. }
  939. func (s *StoreEntry) SearchFeedFormalDetailById(ctx context.Context, feedFormulaId, pastureId int64) ([]*model.FeedFormulaDetail, error) {
  940. res := make([]*model.FeedFormulaDetail, 0)
  941. if err := s.DB.Model(new(model.FeedFormulaDetail)).Where("pasture_id = ?", pastureId).
  942. Where("feed_formula_id = ?", feedFormulaId).
  943. Where("is_show = ?", operationPb.IsShow_OK).
  944. Order("id desc").Find(&res).Error; err != nil {
  945. return nil, xerr.WithStack(err)
  946. }
  947. return res, nil
  948. }
  949. // UpdateFeedFormalVersion 更新版本库并通知牧场端
  950. func (s *StoreEntry) UpdateFeedFormalVersion(ctx context.Context, req *model.FeedFormula) {
  951. if err := s.DB.Model(req).UpdateColumn("version", gorm.Expr("version + ?", 1)).Error; err != nil {
  952. zaplog.Error("UpdateFeedFormalVersion-UpdateColumn", zap.Any("err", err))
  953. }
  954. // 获取该配方下发记录表
  955. feedFormulaDistributeLogList := make([]*model.FeedFormulaDistributeLog, 0)
  956. if err := s.DB.Table(new(model.FeedFormulaDistributeLog).TableName()).
  957. Where("feed_formula_id = ?", req.Id).
  958. Where("is_show = ?", operationPb.IsShow_OK).
  959. Group("pasture_id").
  960. Find(&feedFormulaDistributeLogList).Error; err != nil {
  961. if !errors.Is(err, gorm.ErrRecordNotFound) {
  962. zaplog.Error("UpdateFeedFormalVersion-feedFormulaDistributeLog", zap.Any("err", err))
  963. }
  964. return
  965. }
  966. if len(feedFormulaDistributeLogList) > 0 {
  967. wg := sync.WaitGroup{}
  968. wg.Add(len(feedFormulaDistributeLogList))
  969. for _, v := range feedFormulaDistributeLogList {
  970. go func(feedFormulaDistributeLog *model.FeedFormulaDistributeLog) {
  971. defer wg.Done()
  972. // 更新牧场端配方版本
  973. s.UpdatePastureFeedDetailVersionLog(ctx, feedFormulaDistributeLog, req)
  974. }(v)
  975. }
  976. wg.Wait()
  977. }
  978. }
  979. func (s *StoreEntry) UpdatePastureFeedDetailVersionLog(ctx context.Context, distributeLog *model.FeedFormulaDistributeLog, req *model.FeedFormula) {
  980. pastureId := distributeLog.PastureId
  981. groupPasture, err := s.GetGroupPastureById(ctx, pastureId)
  982. if err != nil {
  983. zaplog.Error("UpdateFeedFormalVersion", zap.Any("GetGroupPastureById", pastureId), zap.Any("err", err))
  984. return
  985. }
  986. if groupPasture.IsDistribution != operationPb.IsShow_OK {
  987. return
  988. }
  989. var (
  990. belong int32 = 1
  991. feedTemplateId = req.Id
  992. )
  993. if req.PastureDataId > 0 {
  994. belong = 2
  995. feedTemplateId = req.PastureDataId
  996. }
  997. list := make([]*operationPb.AddFeedFormulaDetail, 0)
  998. if err = s.DB.Model(new(model.FeedFormulaDetail)).Where("feed_formula_id = ?", req.Id).Find(&list).Error; err != nil {
  999. zaplog.Error("UpdatePastureFeedDetailVersionLog-getFeedFormulaDetail",
  1000. zap.Any("err", err),
  1001. zap.Any("feed_formula_id", req.Id))
  1002. return
  1003. }
  1004. response := &model.FeedFormulaUpdateVersionResponse{}
  1005. body := &model.FeedFormulaUpdateVersionRequest{
  1006. FeedTemplateId: feedTemplateId,
  1007. Version: req.Version,
  1008. Belong: belong,
  1009. Data: make([]*operationPb.AddFeedFormulaDetail, 0),
  1010. }
  1011. zaplog.Info("UpdateFeedFormalVersion", zap.Any("body", body))
  1012. if err = s.PastureHttpClient(ctx, model.FeedFormulaVersionUpdateUrl, pastureId, body, response); err != nil {
  1013. zaplog.Error("UpdateFeedFormalVersion-http",
  1014. zap.String("url", model.FeedFormulaVersionUpdateUrl),
  1015. zap.Any("pasture", groupPasture), zap.Any("body", body),
  1016. zap.Any("err", err), zap.Any("response", response))
  1017. return
  1018. }
  1019. if response.Code != http.StatusOK {
  1020. zaplog.Error("UpdateFeedFormalVersion-response",
  1021. zap.String("url", model.DashboardExecTimeUrl),
  1022. zap.Any("pasture", groupPasture), zap.Any("body", body),
  1023. zap.Any("err", err), zap.Any("response", response))
  1024. return
  1025. }
  1026. }
  1027. // CheckFeedFormulaDistribute 检查该配方是否下发牧场端
  1028. func (s *StoreEntry) CheckFeedFormulaDistribute(ctx context.Context, pastureId, feedFormulaId int64) bool {
  1029. res := &model.FeedFormulaDistributeLog{}
  1030. if err := s.DB.Where("feed_formula_id = ?", feedFormulaId).Where("pasture_id = ?", pastureId).First(res).Error; err != nil {
  1031. return false
  1032. }
  1033. if res.IsShow == operationPb.IsShow_OK {
  1034. return true
  1035. }
  1036. return false
  1037. }
  1038. // ForageListByGroup 查询集团端饲料的列表数据
  1039. func (s *StoreEntry) ForageListByGroup(ctx context.Context) (*operationPb.SearchForageListResponse, error) {
  1040. forage := make([]*model.Forage, 0)
  1041. var count int64 = 0
  1042. if err := s.DB.Model(new(model.Forage)).Where("is_delete = ?", operationPb.IsShow_OK).
  1043. Where("pasture_id = 0").Where("is_show = ?", operationPb.IsShow_OK).
  1044. Order("id DESC").Count(&count).Find(&forage).Error; err != nil {
  1045. return nil, xerr.WithStack(err)
  1046. }
  1047. return &operationPb.SearchForageListResponse{
  1048. Code: http.StatusOK,
  1049. Msg: "ok",
  1050. Data: &operationPb.SearchForageList{
  1051. Total: int32(count),
  1052. List: model.ForageSlice(forage).ToPB(),
  1053. },
  1054. }, nil
  1055. }