feed_service.go 40 KB

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