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