feed_service.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. }
  27. // CreateFeedFormula 添加数据
  28. func (s *StoreEntry) CreateFeedFormula(ctx context.Context, req *operationPb.AddFeedFormulaRequest) error {
  29. forage := model.NewFeedFormula(req)
  30. if err := s.DB.Create(forage).Error; err != nil {
  31. return xerr.WithStack(err)
  32. }
  33. return nil
  34. }
  35. // EditFeedFormula 编辑数据
  36. func (s *StoreEntry) EditFeedFormula(ctx context.Context, req *operationPb.AddFeedFormulaRequest) error {
  37. forage := model.FeedFormula{Id: int64(req.Id)}
  38. if err := s.DB.Where("is_delete = ?", operationPb.IsShow_OK).First(&forage).Error; err != nil {
  39. if errors.Is(err, gorm.ErrRecordNotFound) {
  40. return xerr.Custom("该数据不存在")
  41. }
  42. return xerr.WithStack(err)
  43. }
  44. updateData := &model.FeedFormula{
  45. Name: req.Name,
  46. Colour: req.Colour,
  47. CattleCategoryId: req.CattleCategoryId,
  48. CattleCategoryName: req.CattleCategoryName,
  49. FormulaTypeId: req.FormulaTypeId,
  50. FormulaTypeName: req.FormulaTypeName,
  51. DataSourceId: req.DataSourceId,
  52. DataSourceName: req.DataSourceName,
  53. Remarks: req.Remarks,
  54. IsShow: req.IsShow,
  55. }
  56. if err := s.DB.Model(new(model.FeedFormula)).
  57. Omit("is_show", "is_delete", "encode_number", "formula_type_id", "formula_type_name", "data_source", "version", "is_modify").
  58. Where("id = ?", req.Id).
  59. Updates(updateData).Error; err != nil {
  60. return xerr.WithStack(err)
  61. }
  62. return nil
  63. }
  64. // SearchFeedFormulaList 查询数据列表
  65. func (s *StoreEntry) SearchFeedFormulaList(ctx context.Context, req *operationPb.SearchFeedFormulaRequest) (*operationPb.SearchFeedFormulaListResponse, error) {
  66. feedFormula := make([]*model.FeedFormula, 0)
  67. var count int64 = 0
  68. pref := s.DB.Model(new(model.FeedFormula)).Where("is_delete = ?", operationPb.IsShow_OK)
  69. if req.Name != "" {
  70. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  71. }
  72. if req.CattleCategoryId > 0 {
  73. pref.Where("cattle_category_id = ?", req.CattleCategoryId)
  74. }
  75. if req.FormulaTypeId > 0 {
  76. pref.Where("formula_type_id = ?", req.FormulaTypeId)
  77. }
  78. if req.IsShow > 0 {
  79. pref.Where("is_show = ?", req.IsShow)
  80. }
  81. if req.DataSource > 0 {
  82. pref.Where("data_source = ?", req.DataSource)
  83. }
  84. if req.Remarks != "" {
  85. pref.Where("remarks = ?", req.Remarks)
  86. }
  87. if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  88. Find(&feedFormula).Error; err != nil {
  89. return nil, xerr.WithStack(err)
  90. }
  91. return &operationPb.SearchFeedFormulaListResponse{
  92. Code: http.StatusOK,
  93. Msg: "ok",
  94. Data: &operationPb.SearchFeedFormulaListData{
  95. Page: req.Pagination.Page,
  96. PageSize: req.Pagination.PageSize,
  97. Total: int32(count),
  98. List: model.FeedFormulaSlice(feedFormula).ToPB(),
  99. },
  100. }, nil
  101. }
  102. // IsShowFeedFormula 是否启用和是否可修改
  103. func (s *StoreEntry) IsShowFeedFormula(ctx context.Context, req *operationPb.IsShowModifyFeedFormula) error {
  104. feedFormula := &model.FeedFormula{Id: int64(req.FeedFormulaId)}
  105. if err := s.DB.First(feedFormula).Error; err != nil {
  106. if errors.Is(err, gorm.ErrRecordNotFound) {
  107. return xerr.Custom("该数据不存在")
  108. }
  109. return xerr.WithStack(err)
  110. }
  111. if req.EditType == 1 {
  112. if err := s.DB.Model(new(model.FeedFormula)).Where("id = ?", req.FeedFormulaId).Update("is_show", req.IsShow).Error; err != nil {
  113. return xerr.WithStack(err)
  114. }
  115. }
  116. if req.EditType == 2 {
  117. if err := s.DB.Model(new(model.FeedFormula)).Where("id = ?", req.FeedFormulaId).Update("is_modify", req.IsShow).Error; err != nil {
  118. return xerr.WithStack(err)
  119. } else {
  120. s.PastureFeedFormulaIsModify(ctx, req.FeedFormulaId, req.IsShow)
  121. }
  122. }
  123. return nil
  124. }
  125. // DeleteFeedFormula 是否删除
  126. func (s *StoreEntry) DeleteFeedFormula(ctx context.Context, feedFormulaId int64) error {
  127. feedFormula := &model.FeedFormula{Id: feedFormulaId}
  128. if err := s.DB.First(feedFormula).Error; err != nil {
  129. if errors.Is(err, gorm.ErrRecordNotFound) {
  130. return xerr.Custom("该数据不存在")
  131. }
  132. return xerr.WithStack(err)
  133. }
  134. if err := s.DB.Model(new(model.FeedFormula)).Where("id = ?", feedFormula.Id).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {
  135. return xerr.WithStack(err)
  136. }
  137. return nil
  138. }
  139. // ExcelImportFeedFormula 导入excel
  140. func (s *StoreEntry) ExcelImportFeedFormula(ctx context.Context, req io.Reader) error {
  141. xlsx, err := excelize.OpenReader(req)
  142. if err != nil {
  143. return xerr.WithStack(err)
  144. }
  145. defer xlsx.Close()
  146. rows, err := xlsx.GetRows(xlsx.GetSheetName(xlsx.GetActiveSheetIndex()))
  147. if err != nil {
  148. return xerr.WithStack(err)
  149. }
  150. if len(rows) > 10000 {
  151. rows = rows[:10000]
  152. }
  153. feedFormulaList := make([]*model.FeedFormula, 0)
  154. for i, row := range rows {
  155. if i == 0 {
  156. continue
  157. }
  158. var (
  159. name, encodeNumber, cattleCategoryName, formulaTypeName, dataSourceName, remarks, isShowStr string
  160. isShow operationPb.IsShow_Kind
  161. )
  162. for k, v := range row {
  163. if k == 0 {
  164. name = v
  165. }
  166. if k == 1 {
  167. encodeNumber = v
  168. }
  169. if k == 2 {
  170. cattleCategoryName = v
  171. }
  172. if k == 3 {
  173. formulaTypeName = v
  174. }
  175. if k == 4 {
  176. dataSourceName = v
  177. }
  178. if k == 5 {
  179. remarks = v
  180. }
  181. if k == 6 {
  182. isShowStr = v
  183. }
  184. }
  185. if isShowStr == "是" {
  186. isShow = operationPb.IsShow_OK
  187. } else {
  188. isShow = operationPb.IsShow_NO
  189. }
  190. feedFormulaItem := &model.FeedFormula{
  191. Name: name,
  192. EncodeNumber: encodeNumber,
  193. CattleCategoryName: cattleCategoryName,
  194. FormulaTypeName: formulaTypeName,
  195. Remarks: remarks,
  196. IsShow: isShow,
  197. IsDelete: operationPb.IsShow_OK,
  198. DataSourceId: operationPb.DataSource_EXCEL_IMPORT,
  199. DataSourceName: dataSourceName,
  200. }
  201. feedFormulaList = append(feedFormulaList, feedFormulaItem)
  202. }
  203. if len(feedFormulaList) > 0 {
  204. if err = s.DB.Create(feedFormulaList).Error; err != nil {
  205. return xerr.WithStack(err)
  206. }
  207. }
  208. return nil
  209. }
  210. // ExcelExportFeedFormula 流式导出excel
  211. func (s *StoreEntry) ExcelExportFeedFormula(ctx context.Context, req *operationPb.SearchFeedFormulaRequest) (*bytes.Buffer, error) {
  212. res, err := s.SearchFeedFormulaList(ctx, req)
  213. if err != nil {
  214. return nil, xerr.WithStack(err)
  215. }
  216. if len(res.Data.List) <= 0 {
  217. return nil, xerr.Custom("数据为空")
  218. }
  219. file := excelize.NewFile()
  220. defer file.Close()
  221. streamWriter, err := file.NewStreamWriter("Sheet1")
  222. if err != nil {
  223. return nil, xerr.WithStack(err)
  224. }
  225. titles := []interface{}{"配方名称", "配方编码", "畜牧类别", "配方类别", "来源", "备注", "是否启用",
  226. "饲料组", "饲料名称", "重量(kg)", "搅拌延迟(min)", "是否锁定牛头数比例", "顺序"}
  227. if err = streamWriter.SetRow("A1", titles); err != nil {
  228. return nil, xerr.WithStack(err)
  229. }
  230. for i, item := range res.Data.List {
  231. cell, err := excelize.CoordinatesToCellName(1, i+2)
  232. if err != nil {
  233. zaplog.Error("excelize.CoordinatesToCellName", zap.Any("Err", err))
  234. continue
  235. }
  236. row := make([]interface{}, 0)
  237. row = append(row, item.Name, item.EncodeNumber, item.CattleCategoryName, item.FormulaTypeName, item.DataSourceName,
  238. item.Remarks, item.IsShow)
  239. if err = streamWriter.SetRow(cell, row); err != nil {
  240. return nil, xerr.WithStack(err)
  241. }
  242. }
  243. if err = streamWriter.Flush(); err != nil {
  244. return nil, xerr.WithStack(err)
  245. }
  246. return file.WriteToBuffer()
  247. }
  248. // ExcelTemplateFeedFormula 导出模板
  249. func (s *StoreEntry) ExcelTemplateFeedFormula(ctx context.Context) (*bytes.Buffer, error) {
  250. file := excelize.NewFile()
  251. defer file.Close()
  252. streamWriter, err := file.NewStreamWriter("Sheet1")
  253. if err != nil {
  254. return nil, xerr.WithStack(err)
  255. }
  256. titles := []interface{}{"配方名称", "配方编码", "畜牧类别", "配方类别", "来源", "备注", "是否启用",
  257. "饲料组", "饲料名称", "重量(kg)", "搅拌延迟(min)", "是否锁定牛头数比例", "顺序"}
  258. if err = streamWriter.SetRow("A1", titles); err != nil {
  259. return nil, xerr.WithStack(err)
  260. }
  261. if err = streamWriter.Flush(); err != nil {
  262. return nil, xerr.WithStack(err)
  263. }
  264. return file.WriteToBuffer()
  265. }
  266. // EncodeNumber 配方编码
  267. func (s *StoreEntry) EncodeNumber(ctx context.Context) string {
  268. currTime := time.Now().Format(model.LayoutDate)
  269. prefix := fmt.Sprintf("%s_%s", EncodeNumberPrefix, currTime)
  270. data := &model.UniqueData{}
  271. if err := s.DB.Order("id desc").Where("prefix = ?", prefix).First(data).Error; err != nil {
  272. if !errors.Is(err, gorm.ErrRecordNotFound) {
  273. return ""
  274. }
  275. ud, _ := strconv.Atoi(currTime)
  276. result := ud*100 + 1
  277. newData := &model.UniqueData{
  278. Prefix: prefix,
  279. Data: int64(result),
  280. }
  281. if err = s.DB.Create(newData).Error; err != nil {
  282. zaplog.Error("EncodeNumber Create", zap.Any("data", newData), zap.Any("Err", err))
  283. return ""
  284. }
  285. return fmt.Sprintf("%d", newData.Data)
  286. }
  287. data.Data += 1
  288. if err := s.DB.Model(new(model.UniqueData)).Where("prefix = ?", prefix).Update("data", data.Data).Error; err != nil {
  289. return ""
  290. } else {
  291. return fmt.Sprintf("%d", data.Data)
  292. }
  293. }
  294. // DistributeFeedFormula 配方下发牧场
  295. func (s *StoreEntry) DistributeFeedFormula(ctx context.Context, req *operationPb.DistributeFeedFormulaRequest) error {
  296. distributeData, err := s.checkoutDistributeData(ctx, req)
  297. if err != nil {
  298. return xerr.WithStack(err)
  299. }
  300. if len(distributeData.PastureList) <= 0 {
  301. return nil
  302. }
  303. wg := sync.WaitGroup{}
  304. wg.Add(len(distributeData.PastureList))
  305. var muError error
  306. for _, pasture := range distributeData.PastureList {
  307. go func(p *model.GroupPasture) {
  308. // 过滤已下发的
  309. body := make([]*model.FeedFormula, 0)
  310. for _, v := range distributeData.FeedFormulaList {
  311. if ok := s.checkoutDistributeLog(ctx, p.Id, v.Id); !ok {
  312. body = append(body, v)
  313. }
  314. }
  315. if len(body) <= 0 {
  316. return
  317. }
  318. request := &model.DistributeFeedFormulaRequest{
  319. PastureId: p.Id,
  320. Body: body,
  321. }
  322. response := &model.PastureResponse{}
  323. defer func() {
  324. if response.Code == http.StatusOK {
  325. s.DB.Create(model.NewFeedFormulaDistributeLogList(distributeData.FeedFormulaList, p.Id, p.Name, operationPb.IsShow_OK))
  326. } else {
  327. muError = multierr.Append(muError, xerr.Custom(response.Msg))
  328. }
  329. wg.Done()
  330. }()
  331. if _, err = s.PastureHttpClient(ctx, model.FeedFormulaDistributeUrl, p.Id, request, response); err != nil {
  332. muError = multierr.Append(muError, err)
  333. zaplog.Error("DistributeFeedFormula", zap.Any("pasture", p), zap.Any("body", distributeData.FeedFormulaList), zap.Any("err", err), zap.Any("response", response))
  334. b, _ := json.Marshal(request)
  335. res, _ := json.Marshal(response)
  336. pastureDataLog := model.NewPastureDataLog(p.Id, PastureDataLogType["FeedFormula_Distribute"], model.FeedFormulaDistributeUrl, string(b), string(res))
  337. s.DB.Create(pastureDataLog)
  338. }
  339. }(pasture)
  340. }
  341. wg.Wait()
  342. return muError
  343. }
  344. // FeedFormulaUsage 配方使用概况
  345. func (s *StoreEntry) FeedFormulaUsage(ctx context.Context, req *operationPb.FeedFormulaUsageRequest) error {
  346. feedFormulaDistributeLogList := make([]*model.FeedFormulaDistributeLog, 0)
  347. if err := s.DB.Model(new(model.FeedFormulaDistributeLog)).
  348. Where("feed_formula_id = ?", req.FeedFormulaId).
  349. Where("is_show = ?", operationPb.IsShow_OK).
  350. Find(&feedFormulaDistributeLogList).Error; err != nil {
  351. return xerr.WithStack(err)
  352. }
  353. wg := sync.WaitGroup{}
  354. wg.Add(len(feedFormulaDistributeLogList))
  355. for _, list := range feedFormulaDistributeLogList {
  356. go func(l *model.FeedFormulaDistributeLog) {
  357. defer wg.Done()
  358. }(list)
  359. }
  360. wg.Wait()
  361. return nil
  362. }
  363. func (s *StoreEntry) PastureFeedFormulaIsModify(ctx context.Context, feedFormulaId int32, isModify operationPb.IsShow_Kind) {
  364. feedFormulaDistributeLogList := make([]*model.FeedFormulaDistributeLog, 0)
  365. if err := s.DB.Where("is_show = ?", operationPb.IsShow_OK).
  366. Where("feed_formula_id = ?", feedFormulaId).
  367. Group("pasture_id").Find(&feedFormulaDistributeLogList).Error; err != nil {
  368. zaplog.Error("PastureFeedFormulaIsModify", zap.Any("err", err), zap.Any("feed_formula_id", feedFormulaId))
  369. return
  370. }
  371. for _, v := range feedFormulaDistributeLogList {
  372. response := &model.PastureResponse{}
  373. request := &model.FeedFormulaIsModifyRequest{
  374. PastureId: v.PastureId,
  375. FeedFormulaId: v.FeedFormulaId,
  376. IsModify: int32(isModify),
  377. }
  378. if _, err := s.PastureHttpClient(ctx, model.FeedFormulaIsModifyUrl, v.Id, request, response); err != nil {
  379. zaplog.Error("PastureFeedFormulaIsModify", zap.Any("request", request), zap.Any("err", err), zap.Any("response", response))
  380. b, _ := json.Marshal(request)
  381. res, _ := json.Marshal(response)
  382. pastureDataLog := model.NewPastureDataLog(v.PastureId, PastureDataLogType["FeedFormula_IsModify"], model.FeedFormulaIsModifyUrl, string(b), string(res))
  383. s.DB.Create(pastureDataLog)
  384. }
  385. }
  386. }
  387. func (s *StoreEntry) checkoutDistributeData(ctx context.Context, req *operationPb.DistributeFeedFormulaRequest) (*model.DistributeData, error) {
  388. result := &model.DistributeData{
  389. PastureList: make([]*model.GroupPasture, 0),
  390. FeedFormulaList: make([]*model.FeedFormula, 0),
  391. }
  392. if err := s.DB.Where("id IN ?", req.PastureIds).Where("is_delete = ?", operationPb.IsShow_OK).Find(&result.PastureList).Error; err != nil {
  393. return result, xerr.WithStack(err)
  394. }
  395. if err := s.DB.Where("id IN ?", req.FeedFormulaIds).Find(&result.FeedFormulaList).Error; err != nil {
  396. return result, xerr.WithStack(err)
  397. }
  398. if len(result.PastureList) <= 0 || len(result.FeedFormulaList) <= 0 {
  399. return result, xerr.Customf("数据错误")
  400. }
  401. return result, nil
  402. }
  403. func (s *StoreEntry) checkoutDistributeLog(ctx context.Context, pastureId, feedFormulaId int64) bool {
  404. res := &model.FeedFormulaDistributeLog{}
  405. if err := s.DB.Model(new(model.FeedFormulaDistributeLog)).Where("feed_formula_id = ?", feedFormulaId).
  406. Where("pasture_id = ?", pastureId).Where("is_show = ?", operationPb.IsShow_OK).First(res).Error; err != nil {
  407. return false
  408. }
  409. if res.IsShow == operationPb.IsShow_OK {
  410. return true
  411. }
  412. return false
  413. }