feed_service.go 33 KB

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