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