feed_service.go 31 KB

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