feed_service.go 40 KB

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