feed_service.go 34 KB

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