feed_service.go 25 KB

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