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