feed_service.go 37 KB

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