feed_service.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. package backend
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "kpt-tmr-group/model"
  10. "kpt-tmr-group/pkg/logger/zaplog"
  11. "kpt-tmr-group/pkg/xerr"
  12. operationPb "kpt-tmr-group/proto/go/backend/operation"
  13. "net/http"
  14. "strconv"
  15. "sync"
  16. "time"
  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. // CreateFeedFormula 添加数据
  29. func (s *StoreEntry) CreateFeedFormula(ctx context.Context, req *operationPb.AddFeedFormulaRequest) error {
  30. forage := model.NewFeedFormula(req)
  31. if err := s.DB.Create(forage).Error; err != nil {
  32. return xerr.WithStack(err)
  33. }
  34. return nil
  35. }
  36. // EditFeedFormula 编辑数据
  37. func (s *StoreEntry) EditFeedFormula(ctx context.Context, req *operationPb.AddFeedFormulaRequest) error {
  38. forage := model.FeedFormula{Id: int64(req.Id)}
  39. if err := s.DB.Where("is_delete = ?", operationPb.IsShow_OK).First(&forage).Error; err != nil {
  40. if errors.Is(err, gorm.ErrRecordNotFound) {
  41. return xerr.Custom("该数据不存在")
  42. }
  43. return xerr.WithStack(err)
  44. }
  45. updateData := &model.FeedFormula{
  46. Name: req.Name,
  47. Colour: req.Colour,
  48. CattleCategoryId: req.CattleCategoryId,
  49. CattleCategoryName: req.CattleCategoryName,
  50. FormulaTypeId: req.FormulaTypeId,
  51. FormulaTypeName: req.FormulaTypeName,
  52. DataSourceId: req.DataSourceId,
  53. DataSourceName: req.DataSourceName,
  54. Remarks: req.Remarks,
  55. IsShow: req.IsShow,
  56. }
  57. if err := s.DB.Model(new(model.FeedFormula)).
  58. Omit("is_show", "is_delete", "encode_number", "formula_type_id", "formula_type_name", "data_source", "version", "is_modify").
  59. Where("id = ?", req.Id).
  60. Updates(updateData).Error; err != nil {
  61. return xerr.WithStack(err)
  62. }
  63. return nil
  64. }
  65. // AddFeedByFeedFormula 配方添加饲料
  66. func (s *StoreEntry) AddFeedByFeedFormula(ctx context.Context, req *operationPb.GroupAddFeedFormulaDetail) error {
  67. feedFormulaData := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  68. if err := s.DB.Model(new(model.FeedFormula)).First(feedFormulaData).Error; err != nil {
  69. return xerr.WithStack(err)
  70. }
  71. insertData := make([]*model.FeedFormulaDetail, 0)
  72. for _, v := range req.List {
  73. feedData := &model.Feed{Id: int64(v.ForageId)}
  74. if err := s.DB.Model(new(model.Feed)).First(feedData).Error; err != nil {
  75. return xerr.WithStack(err)
  76. }
  77. if v.AllowError > v.StirDelay {
  78. return xerr.Customf("允许误差不能大于搅拌延迟")
  79. }
  80. insertData = append(insertData, &model.FeedFormulaDetail{
  81. PastureName: "集团",
  82. FeedFormulaId: int64(req.FeedFormulaId),
  83. ForageId: int64(v.ForageId),
  84. ForageName: v.ForageName,
  85. ForageGroupName: v.ForageGroupName,
  86. Weight: int32(v.Weight * 100),
  87. StirDelay: v.StirDelay,
  88. AllowError: v.AllowError,
  89. IsShow: operationPb.IsShow_OK,
  90. Sort: v.Sort,
  91. })
  92. }
  93. if err := s.DB.Model(new(model.FeedFormulaDetail)).Save(insertData).Error; err != nil {
  94. return xerr.WithStack(err)
  95. }
  96. return nil
  97. }
  98. // FeedFormulaDetailBySort 配方饲料排序
  99. func (s *StoreEntry) FeedFormulaDetailBySort(ctx context.Context, req *operationPb.GroupAddFeedFormulaDetail) error {
  100. feedFormulaData := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  101. if err := s.DB.Model(new(model.FeedFormula)).First(feedFormulaData).Error; err != nil {
  102. return xerr.WithStack(err)
  103. }
  104. tx := s.DB.Transaction(func(tx *gorm.DB) error {
  105. for _, v := range req.List {
  106. if err := tx.Model(new(model.FeedFormulaDetail)).
  107. Where("id = ?", v.Id).
  108. Updates(map[string]interface{}{
  109. "sort": v.Sort,
  110. }).Error; err != nil {
  111. return xerr.WithStack(err)
  112. }
  113. }
  114. return nil
  115. })
  116. return tx
  117. }
  118. // FeedFormulaDetailDelete 配方删除饲料
  119. func (s *StoreEntry) FeedFormulaDetailDelete(ctx context.Context, req *operationPb.GroupAddFeedFormulaDetail) error {
  120. feedFormulaData := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  121. if err := s.DB.Model(new(model.FeedFormula)).First(feedFormulaData).Error; err != nil {
  122. return xerr.WithStack(err)
  123. }
  124. tr := s.DB.Transaction(func(tx *gorm.DB) error {
  125. for _, v := range req.List {
  126. if err := tx.Model(new(model.FeedFormulaDetail)).
  127. Where("id = ?", v.Id).
  128. Updates(map[string]interface{}{
  129. "is_show": operationPb.IsShow_NO,
  130. }).Error; err != nil {
  131. return xerr.WithStack(err)
  132. }
  133. }
  134. return nil
  135. })
  136. return tr
  137. }
  138. // MixedFeedFormula 合成预混料
  139. func (s *StoreEntry) MixedFeedFormula(ctx context.Context, req *operationPb.MixedFeedFormulaRequest) error {
  140. tr := s.DB.Transaction(func(tx *gorm.DB) error {
  141. feedFormulaData := &model.FeedFormula{
  142. Name: req.Name,
  143. Colour: req.Colour,
  144. EncodeNumber: s.EncodeNumber(ctx),
  145. CattleCategoryId: operationPb.CattleCategoryParent_Kind(req.CattleCategoryId),
  146. CattleCategoryName: req.CattleCategoryName,
  147. FormulaTypeId: req.FormulaTypeId,
  148. FormulaTypeName: req.FormulaTypeName,
  149. DataSourceId: operationPb.DataSource_Kind(req.DataSourceId),
  150. DataSourceName: operationPb.DataSource_Kind_name[req.DataSourceId],
  151. Remarks: req.Remarks,
  152. PastureName: "集团",
  153. IsShow: operationPb.IsShow_OK,
  154. IsModify: operationPb.IsShow_OK,
  155. IsDelete: operationPb.IsShow_OK,
  156. }
  157. if err := s.DB.Model(new(model.FeedFormula)).Create(feedFormulaData).Error; err != nil {
  158. return xerr.WithStack(err)
  159. }
  160. feedFormulaDetailList := make([]*model.FeedFormulaDetail, 0)
  161. for _, v := range req.FeedList {
  162. feedFormulaDetailList = append(feedFormulaDetailList, &model.FeedFormulaDetail{
  163. PastureName: "集团",
  164. FeedFormulaId: feedFormulaData.Id,
  165. ForageId: int64(v.ForageId),
  166. ForageName: v.ForageName,
  167. ForageGroupName: v.ForageGroupName,
  168. Weight: int32(v.Weight * 100),
  169. StirDelay: v.StirDelay,
  170. AllowError: v.AllowError,
  171. IsShow: operationPb.IsShow_OK,
  172. Sort: v.Sort,
  173. })
  174. }
  175. if err := s.DB.Model(new(model.FeedFormulaDetail)).Save(feedFormulaDetailList).Error; err != nil {
  176. return xerr.WithStack(err)
  177. }
  178. return nil
  179. })
  180. return tr
  181. }
  182. // SearchFeedFormulaList 查询数据列表
  183. func (s *StoreEntry) SearchFeedFormulaList(ctx context.Context, req *operationPb.SearchFeedFormulaRequest) (*operationPb.SearchFeedFormulaListResponse, error) {
  184. feedFormula := make([]*model.FeedFormula, 0)
  185. var count int64 = 0
  186. pref := s.DB.Model(new(model.FeedFormula)).Where("is_delete = ?", operationPb.IsShow_OK)
  187. if req.Name != "" {
  188. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  189. }
  190. if req.CattleCategoryId > 0 {
  191. pref.Where("cattle_category_id = ?", req.CattleCategoryId)
  192. }
  193. if req.FormulaTypeId > 0 {
  194. pref.Where("formula_type_id = ?", req.FormulaTypeId)
  195. }
  196. if req.IsShow > 0 {
  197. pref.Where("is_show = ?", req.IsShow)
  198. }
  199. if req.DataSource > 0 {
  200. pref.Where("data_source = ?", req.DataSource)
  201. }
  202. if req.Remarks != "" {
  203. pref.Where("remarks = ?", req.Remarks)
  204. }
  205. if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  206. Find(&feedFormula).Error; err != nil {
  207. return nil, xerr.WithStack(err)
  208. }
  209. return &operationPb.SearchFeedFormulaListResponse{
  210. Code: http.StatusOK,
  211. Msg: "ok",
  212. Data: &operationPb.SearchFeedFormulaListData{
  213. Page: req.Pagination.Page,
  214. PageSize: req.Pagination.PageSize,
  215. Total: int32(count),
  216. List: model.FeedFormulaSlice(feedFormula).ToPB(),
  217. },
  218. }, nil
  219. }
  220. // SearchFeedFormulaById 查询指定数据
  221. func (s *StoreEntry) SearchFeedFormulaById(ctx context.Context, foodFormulaId int64) (*model.FeedFormula, error) {
  222. feedFormula := &model.FeedFormula{}
  223. if err := s.DB.Model(new(model.FeedFormula)).
  224. Where("is_delete = ?", operationPb.IsShow_OK).
  225. Where("id = ?", foodFormulaId).
  226. First(feedFormula).Error; err != nil {
  227. return nil, xerr.WithStack(err)
  228. }
  229. return feedFormula, nil
  230. }
  231. // IsShowFeedFormula 是否启用和是否可修改
  232. func (s *StoreEntry) IsShowFeedFormula(ctx context.Context, req *operationPb.IsShowModifyFeedFormula) error {
  233. feedFormula := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  234. if err := s.DB.First(feedFormula).Error; err != nil {
  235. if errors.Is(err, gorm.ErrRecordNotFound) {
  236. return xerr.Custom("该数据不存在")
  237. }
  238. return xerr.WithStack(err)
  239. }
  240. if req.EditType == 1 {
  241. if err := s.DB.Model(new(model.FeedFormula)).Where("id = ?", req.FeedFormulaId).Update("is_show", req.IsShow).Error; err != nil {
  242. return xerr.WithStack(err)
  243. }
  244. }
  245. if req.EditType == 2 {
  246. if err := s.DB.Model(new(model.FeedFormula)).Where("id = ?", req.FeedFormulaId).Update("is_modify", req.IsShow).Error; err != nil {
  247. return xerr.WithStack(err)
  248. } else {
  249. s.PastureFeedFormulaIsModify(ctx, req.FeedFormulaId, req.IsShow)
  250. }
  251. }
  252. return nil
  253. }
  254. // DeleteFeedFormula 是否删除
  255. func (s *StoreEntry) DeleteFeedFormula(ctx context.Context, feedFormulaId int64) error {
  256. feedFormula := &model.FeedFormula{Id: feedFormulaId}
  257. if err := s.DB.First(feedFormula).Error; err != nil {
  258. if errors.Is(err, gorm.ErrRecordNotFound) {
  259. return xerr.Custom("该数据不存在")
  260. }
  261. return xerr.WithStack(err)
  262. }
  263. if err := s.DB.Model(new(model.FeedFormula)).Where("id = ?", feedFormula.Id).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {
  264. return xerr.WithStack(err)
  265. }
  266. return nil
  267. }
  268. // ExcelImportFeedFormula 导入excel
  269. func (s *StoreEntry) ExcelImportFeedFormula(ctx context.Context, req io.Reader) error {
  270. xlsx, err := excelize.OpenReader(req)
  271. if err != nil {
  272. return xerr.WithStack(err)
  273. }
  274. defer xlsx.Close()
  275. rows, err := xlsx.GetRows(xlsx.GetSheetName(xlsx.GetActiveSheetIndex()))
  276. if err != nil {
  277. return xerr.WithStack(err)
  278. }
  279. if len(rows) > 10000 {
  280. rows = rows[:10000]
  281. }
  282. feedFormulaList := make([]*model.FeedFormula, 0)
  283. for i, row := range rows {
  284. if i == 0 {
  285. continue
  286. }
  287. var (
  288. name, encodeNumber, cattleCategoryName, formulaTypeName, dataSourceName, remarks, isShowStr string
  289. isShow operationPb.IsShow_Kind
  290. )
  291. for k, v := range row {
  292. if k == 0 {
  293. name = v
  294. }
  295. if k == 1 {
  296. encodeNumber = v
  297. }
  298. if k == 2 {
  299. cattleCategoryName = v
  300. }
  301. if k == 3 {
  302. formulaTypeName = v
  303. }
  304. if k == 4 {
  305. dataSourceName = v
  306. }
  307. if k == 5 {
  308. remarks = v
  309. }
  310. if k == 6 {
  311. isShowStr = v
  312. }
  313. }
  314. if isShowStr == "是" {
  315. isShow = operationPb.IsShow_OK
  316. } else {
  317. isShow = operationPb.IsShow_NO
  318. }
  319. feedFormulaItem := &model.FeedFormula{
  320. Name: name,
  321. EncodeNumber: encodeNumber,
  322. CattleCategoryName: cattleCategoryName,
  323. FormulaTypeName: formulaTypeName,
  324. Remarks: remarks,
  325. IsShow: isShow,
  326. IsDelete: operationPb.IsShow_OK,
  327. DataSourceId: operationPb.DataSource_EXCEL_IMPORT,
  328. DataSourceName: dataSourceName,
  329. }
  330. feedFormulaList = append(feedFormulaList, feedFormulaItem)
  331. }
  332. if len(feedFormulaList) > 0 {
  333. if err = s.DB.Create(feedFormulaList).Error; err != nil {
  334. return xerr.WithStack(err)
  335. }
  336. }
  337. return nil
  338. }
  339. // ExcelExportFeedFormula 流式导出excel
  340. func (s *StoreEntry) ExcelExportFeedFormula(ctx context.Context, req *operationPb.SearchFeedFormulaRequest) (*bytes.Buffer, error) {
  341. res, err := s.SearchFeedFormulaList(ctx, req)
  342. if err != nil {
  343. return nil, xerr.WithStack(err)
  344. }
  345. if len(res.Data.List) <= 0 {
  346. return nil, xerr.Custom("数据为空")
  347. }
  348. file := excelize.NewFile()
  349. defer file.Close()
  350. streamWriter, err := file.NewStreamWriter("Sheet1")
  351. if err != nil {
  352. return nil, xerr.WithStack(err)
  353. }
  354. titles := []interface{}{"配方名称", "配方编码", "畜牧类别", "配方类别", "来源", "备注", "是否启用",
  355. "饲料组", "饲料名称", "重量(kg)", "搅拌延迟(min)", "是否锁定牛头数比例", "顺序"}
  356. if err = streamWriter.SetRow("A1", titles); err != nil {
  357. return nil, xerr.WithStack(err)
  358. }
  359. for i, item := range res.Data.List {
  360. cell, err := excelize.CoordinatesToCellName(1, i+2)
  361. if err != nil {
  362. zaplog.Error("excelize.CoordinatesToCellName", zap.Any("Err", err))
  363. continue
  364. }
  365. row := make([]interface{}, 0)
  366. row = append(row, item.Name, item.EncodeNumber, item.CattleCategoryName, item.FormulaTypeName, item.DataSourceName,
  367. item.Remarks, item.IsShow)
  368. if err = streamWriter.SetRow(cell, row); err != nil {
  369. return nil, xerr.WithStack(err)
  370. }
  371. }
  372. if err = streamWriter.Flush(); err != nil {
  373. return nil, xerr.WithStack(err)
  374. }
  375. return file.WriteToBuffer()
  376. }
  377. // ExcelTemplateFeedFormula 导出模板
  378. func (s *StoreEntry) ExcelTemplateFeedFormula(ctx context.Context) (*bytes.Buffer, error) {
  379. file := excelize.NewFile()
  380. defer file.Close()
  381. streamWriter, err := file.NewStreamWriter("Sheet1")
  382. if err != nil {
  383. return nil, xerr.WithStack(err)
  384. }
  385. titles := []interface{}{"配方名称", "配方编码", "畜牧类别", "配方类别", "来源", "备注", "是否启用",
  386. "饲料组", "饲料名称", "重量(kg)", "搅拌延迟(min)", "是否锁定牛头数比例", "顺序"}
  387. if err = streamWriter.SetRow("A1", titles); err != nil {
  388. return nil, xerr.WithStack(err)
  389. }
  390. if err = streamWriter.Flush(); err != nil {
  391. return nil, xerr.WithStack(err)
  392. }
  393. return file.WriteToBuffer()
  394. }
  395. // EncodeNumber 配方编码
  396. func (s *StoreEntry) EncodeNumber(ctx context.Context) string {
  397. currTime := time.Now().Format(model.LayoutDate)
  398. prefix := fmt.Sprintf("%s_%s", EncodeNumberPrefix, currTime)
  399. data := &model.UniqueData{}
  400. if err := s.DB.Order("id desc").Where("prefix = ?", prefix).First(data).Error; err != nil {
  401. if !errors.Is(err, gorm.ErrRecordNotFound) {
  402. return ""
  403. }
  404. ud, _ := strconv.Atoi(currTime)
  405. result := ud*100 + 1
  406. newData := &model.UniqueData{
  407. Prefix: prefix,
  408. Data: int64(result),
  409. }
  410. if err = s.DB.Create(newData).Error; err != nil {
  411. zaplog.Error("EncodeNumber Create", zap.Any("data", newData), zap.Any("Err", err))
  412. return ""
  413. }
  414. return fmt.Sprintf("%d", newData.Data)
  415. }
  416. data.Data += 1
  417. if err := s.DB.Model(new(model.UniqueData)).Where("prefix = ?", prefix).Update("data", data.Data).Error; err != nil {
  418. return ""
  419. } else {
  420. return fmt.Sprintf("%d", data.Data)
  421. }
  422. }
  423. // DistributeFeedFormula 配方下发牧场
  424. func (s *StoreEntry) DistributeFeedFormula(ctx context.Context, req *operationPb.DistributeFeedFormulaRequest) error {
  425. distributeData, err := s.checkoutDistributeData(ctx, req)
  426. if err != nil {
  427. return xerr.WithStack(err)
  428. }
  429. wg := sync.WaitGroup{}
  430. wg.Add(len(distributeData.PastureList))
  431. var muError error
  432. for _, pasture := range distributeData.PastureList {
  433. go func(p *model.GroupPasture) {
  434. defer wg.Done()
  435. // 过滤已下发的
  436. body := make([]*model.FeedFormula, 0)
  437. for _, v := range distributeData.FeedFormulaList {
  438. if ok := s.checkoutDistributeLog(ctx, p.Id, v.Id); !ok {
  439. body = append(body, v)
  440. }
  441. }
  442. if len(body) <= 0 {
  443. return
  444. }
  445. request := &model.DistributeFeedFormulaRequest{
  446. PastureId: p.Id,
  447. Body: body,
  448. }
  449. response := &model.PastureResponse{}
  450. defer func() {
  451. if response.Code == http.StatusOK {
  452. s.DB.Create(model.NewFeedFormulaDistributeLogList(distributeData.FeedFormulaList, p.Id, p.Name, operationPb.IsShow_OK))
  453. } else {
  454. muError = multierr.Append(muError, xerr.Custom(response.Msg))
  455. }
  456. }()
  457. if _, err = s.PastureHttpClient(ctx, model.FeedFormulaDistributeUrl, p.Id, request, response); err != nil {
  458. muError = multierr.Append(muError, err)
  459. zaplog.Error("DistributeFeedFormula", zap.Any("pasture", p), zap.Any("body", distributeData.FeedFormulaList), zap.Any("err", err), zap.Any("response", response))
  460. b, _ := json.Marshal(request)
  461. res, _ := json.Marshal(response)
  462. pastureDataLog := model.NewPastureDataLog(p.Id, PastureDataLogType["FeedFormula_Distribute"], model.FeedFormulaDistributeUrl, string(b), string(res))
  463. s.DB.Create(pastureDataLog)
  464. }
  465. }(pasture)
  466. }
  467. wg.Wait()
  468. return muError
  469. }
  470. // CancelDistributeFeedFormula 取消配方下发牧场
  471. func (s *StoreEntry) CancelDistributeFeedFormula(ctx context.Context, req *operationPb.DistributeFeedFormulaRequest) error {
  472. distributeData, err := s.checkoutDistributeData(ctx, req)
  473. if err != nil {
  474. return xerr.WithStack(err)
  475. }
  476. wg := sync.WaitGroup{}
  477. wg.Add(len(distributeData.PastureList))
  478. var muError error
  479. for _, pasture := range distributeData.PastureList {
  480. go func(p *model.GroupPasture) {
  481. defer wg.Done()
  482. pastureDataId := make([]int64, 0)
  483. for _, v := range distributeData.FeedFormulaList {
  484. if v.PastureId == p.Id {
  485. pastureDataId = append(pastureDataId, v.PastureDataId)
  486. }
  487. }
  488. if len(pastureDataId) <= 0 {
  489. return
  490. }
  491. request := &model.CancelDistributeFeedFormulaRequest{
  492. PastureId: p.Id,
  493. PastureDataId: pastureDataId,
  494. }
  495. response := &model.PastureResponse{}
  496. if _, err = s.PastureHttpClient(ctx, model.FeedFormulaCancelDistributeUrl, p.Id, request, response); err != nil {
  497. zaplog.Error("DistributeFeedFormula", zap.Any("pasture", p), zap.Any("body", distributeData.FeedFormulaList), zap.Any("err", err), zap.Any("response", response))
  498. b, _ := json.Marshal(request)
  499. res, _ := json.Marshal(response)
  500. pastureDataLog := model.NewPastureDataLog(p.Id, PastureDataLogType["FeedFormula_Cancel_Distribute"], model.FeedFormulaCancelDistributeUrl, string(b), string(res))
  501. s.DB.Create(pastureDataLog)
  502. }
  503. }(pasture)
  504. }
  505. wg.Wait()
  506. return muError
  507. }
  508. // EditRecodeFeedFormula 配方修改记录
  509. func (s *StoreEntry) EditRecodeFeedFormula(ctx context.Context, req *operationPb.EditRecodeFeedFormulaRequest) (*operationPb.EditRecodeFeedFormulaResponse, error) {
  510. return nil, nil
  511. }
  512. func (s *StoreEntry) FeedFormulaDetailList(ctx context.Context, req *operationPb.FeedFormulaDetailRequest) (*operationPb.FeedFormulaDetailResponse, error) {
  513. feedFormula, err := s.SearchFeedFormulaById(ctx, int64(req.FeedFormulaId))
  514. if err != nil {
  515. return nil, xerr.WithStack(err)
  516. }
  517. feedFormulaId := feedFormula.Id
  518. if feedFormula.PastureDataId > 0 {
  519. feedFormulaId = feedFormula.PastureDataId
  520. }
  521. list, err := s.SearchFeedFormalDetailById(ctx, feedFormulaId, feedFormula.PastureId)
  522. if err != nil {
  523. return nil, xerr.WithStack(err)
  524. }
  525. return &operationPb.FeedFormulaDetailResponse{
  526. Code: http.StatusOK,
  527. Msg: "ok",
  528. Data: model.FeedFormulaDetailSlice(list).ToPB(),
  529. }, nil
  530. }
  531. // FeedFormulaUsage 配方使用概况
  532. func (s *StoreEntry) FeedFormulaUsage(ctx context.Context, req *operationPb.FeedFormulaUsageRequest) (*operationPb.FeedFormulaUsageResponse, error) {
  533. feedFormulaDistributeLogList := make([]*model.FeedFormulaDistributeLog, 0)
  534. if err := s.DB.Model(new(model.FeedFormulaDistributeLog)).
  535. Where("feed_formula_id = ?", req.FeedFormulaId).
  536. Where("is_show = ?", operationPb.IsShow_OK).Group("pasture_id").
  537. Find(&feedFormulaDistributeLogList).Error; err != nil {
  538. return nil, xerr.WithStack(err)
  539. }
  540. res := &operationPb.FeedFormulaUsageResponse{
  541. Code: http.StatusOK,
  542. Msg: "ok",
  543. Data: make([]*operationPb.FeedFormulaUsageList, 0),
  544. }
  545. wg := sync.WaitGroup{}
  546. wg.Add(len(feedFormulaDistributeLogList))
  547. for _, list := range feedFormulaDistributeLogList {
  548. go func(l *model.FeedFormulaDistributeLog) {
  549. defer wg.Done()
  550. groupDetail, err := s.PastureDetailById(ctx, l.PastureId)
  551. if err != nil {
  552. zaplog.Error("FeedFormulaUsage", zap.Any("PastureDetailById", err))
  553. return
  554. }
  555. req.PastureId = int32(groupDetail.PastureId)
  556. response := &operationPb.PastureFeedFormulaUsageResponse{}
  557. if _, err = s.PastureHttpClient(ctx, model.FeedUsageURl, groupDetail.Id, req, response); err != nil {
  558. zaplog.Error("FeedFormulaUsage", zap.Any("PastureDetailById", err))
  559. return
  560. }
  561. if response.Code == http.StatusOK {
  562. data := &operationPb.FeedFormulaUsageList{
  563. PastureId: int32(groupDetail.Id),
  564. PastureName: groupDetail.Name,
  565. MixedFodderAccurateRatio: response.Data.MixedFodderAccurateRatio,
  566. MixedFodderCorrectRatio: response.Data.MixedFodderCorrectRatio,
  567. SprinkleFodderAccurateRatio: response.Data.SprinkleFodderAccurateRatio,
  568. SprinkleFodderCorrectRatio: response.Data.SprinkleFodderCorrectRatio,
  569. AddFeedTime: response.Data.AddFeedTime,
  570. SprinkleTime: response.Data.SprinkleTime,
  571. StirTime: response.Data.StirTime,
  572. LastEditTime: response.Data.LastEditTime,
  573. }
  574. res.Data = append(res.Data, data)
  575. } else {
  576. zaplog.Error("FeedFormulaUsage-http", zap.Any("response", response))
  577. return
  578. }
  579. }(list)
  580. }
  581. wg.Wait()
  582. return res, nil
  583. }
  584. func (s *StoreEntry) PastureFeedFormulaIsModify(ctx context.Context, feedFormulaId int32, isModify operationPb.IsShow_Kind) {
  585. feedFormulaDistributeLogList := make([]*model.FeedFormulaDistributeLog, 0)
  586. if err := s.DB.Where("is_show = ?", operationPb.IsShow_OK).
  587. Where("feed_formula_id = ?", feedFormulaId).
  588. Group("pasture_id").Find(&feedFormulaDistributeLogList).Error; err != nil {
  589. zaplog.Error("PastureFeedFormulaIsModify", zap.Any("err", err), zap.Any("feed_formula_id", feedFormulaId))
  590. return
  591. }
  592. for _, v := range feedFormulaDistributeLogList {
  593. response := &model.PastureResponse{}
  594. request := &model.FeedFormulaIsModifyRequest{
  595. PastureId: v.PastureId,
  596. FeedFormulaId: v.FeedFormulaId,
  597. IsModify: int32(isModify),
  598. }
  599. if _, err := s.PastureHttpClient(ctx, model.FeedFormulaIsModifyUrl, v.Id, request, response); err != nil {
  600. zaplog.Error("PastureFeedFormulaIsModify", zap.Any("request", request), zap.Any("err", err), zap.Any("response", response))
  601. b, _ := json.Marshal(request)
  602. res, _ := json.Marshal(response)
  603. pastureDataLog := model.NewPastureDataLog(v.PastureId, PastureDataLogType["FeedFormula_IsModify"], model.FeedFormulaIsModifyUrl, string(b), string(res))
  604. s.DB.Create(pastureDataLog)
  605. }
  606. }
  607. }
  608. func (s *StoreEntry) checkoutDistributeData(ctx context.Context, req *operationPb.DistributeFeedFormulaRequest) (*model.DistributeData, error) {
  609. result := &model.DistributeData{
  610. PastureList: make([]*model.GroupPasture, 0),
  611. FeedFormulaList: make([]*model.FeedFormula, 0),
  612. }
  613. if err := s.DB.Where("id IN ?", req.PastureIds).Where("is_delete = ?", operationPb.IsShow_OK).Find(&result.PastureList).Error; err != nil {
  614. return result, xerr.WithStack(err)
  615. }
  616. if err := s.DB.Where("id IN ?", req.FeedFormulaIds).Find(&result.FeedFormulaList).Error; err != nil {
  617. return result, xerr.WithStack(err)
  618. }
  619. if len(result.PastureList) <= 0 || len(result.FeedFormulaList) <= 0 {
  620. return result, xerr.Customf("数据错误")
  621. }
  622. return result, nil
  623. }
  624. func (s *StoreEntry) checkoutDistributeLog(ctx context.Context, pastureId, feedFormulaId int64) bool {
  625. res := &model.FeedFormulaDistributeLog{}
  626. if err := s.DB.Model(new(model.FeedFormulaDistributeLog)).Where("feed_formula_id = ?", feedFormulaId).
  627. Where("pasture_id = ?", pastureId).Where("is_show = ?", operationPb.IsShow_OK).First(res).Error; err != nil {
  628. return false
  629. }
  630. if res.IsShow == operationPb.IsShow_OK {
  631. return true
  632. }
  633. return false
  634. }
  635. func (s *StoreEntry) SearchFeedFormalDetailById(ctx context.Context, feedFormulaId, pastureId int64) ([]*model.FeedFormulaDetail, error) {
  636. res := make([]*model.FeedFormulaDetail, 0)
  637. if err := s.DB.Model(new(model.FeedFormulaDetail)).Where("pasture_id = ?", pastureId).
  638. Where("feed_formula_id = ?", feedFormulaId).
  639. Where("is_show = ?", operationPb.IsShow_OK).
  640. Order("id desc").Find(&res).Error; err != nil {
  641. return nil, xerr.WithStack(err)
  642. }
  643. return res, nil
  644. }