pasture_service.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. package backend
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "kpt-tmr-group/model"
  9. "kpt-tmr-group/pkg/logger/zaplog"
  10. "kpt-tmr-group/pkg/tool"
  11. "kpt-tmr-group/pkg/xerr"
  12. operationPb "kpt-tmr-group/proto/go/backend/operation"
  13. "net/http"
  14. "strconv"
  15. "sync"
  16. "go.uber.org/zap"
  17. "github.com/xuri/excelize/v2"
  18. "gorm.io/gorm"
  19. )
  20. // CreateGroupPasture 创建集团牧场
  21. func (s *StoreEntry) CreateGroupPasture(ctx context.Context, req *operationPb.AddPastureRequest) error {
  22. // 账号同步牧场端
  23. groupPasture := model.NewGroupPasture(req)
  24. if err := s.DB.Create(groupPasture).Error; err != nil {
  25. return xerr.WithStack(err)
  26. }
  27. if err := s.PastureAccountDistribution(ctx, groupPasture); err != nil {
  28. s.DB.Model(new(model.GroupPasture)).Where("id = ?", groupPasture.Id).Update("is_delete", operationPb.IsShow_NO)
  29. return xerr.WithStack(err)
  30. } else {
  31. s.DB.Model(new(model.GroupPasture)).Where("id = ?", groupPasture.Id).Update("is_distribution", operationPb.IsShow_OK)
  32. }
  33. return nil
  34. }
  35. // PastureAccountDistribution 账号同步牧场端
  36. func (s *StoreEntry) PastureAccountDistribution(ctx context.Context, groupPasture *model.GroupPasture) error {
  37. if groupPasture.Domain == "" {
  38. return nil
  39. }
  40. body := &model.AccountDistribution{
  41. Account: groupPasture.Account,
  42. UserName: groupPasture.ManagerUser,
  43. Password: groupPasture.Password,
  44. Phone: groupPasture.ManagerPhone,
  45. PastureId: int32(groupPasture.Id),
  46. PastureName: groupPasture.Name,
  47. Address: groupPasture.Address,
  48. }
  49. res := &model.PastureCommonResponse{}
  50. if err := s.PastureHttpClient(ctx, model.PastureAccountDistributionURl, groupPasture.Id, body, res); err != nil {
  51. zaplog.Error("AccountDistribution", zap.Any("url", model.PastureAccountDistributionURl), zap.Any("err", err), zap.Any("body", body), zap.Any("res", res))
  52. return xerr.WithStack(err)
  53. }
  54. if res.Code != http.StatusOK {
  55. if err := s.DB.Model(new(model.GroupPasture)).Where("id = ?", groupPasture.Id).Update("is_distribution", operationPb.IsShow_OK).Error; err != nil {
  56. zaplog.Error("AccountDistribution-Update", zap.Any("url", model.PastureAccountDistributionURl), zap.Any("err", err), zap.Any("body", body), zap.Any("res", res))
  57. return xerr.Customf("%s", res.Msg)
  58. }
  59. }
  60. return nil
  61. }
  62. func (s *StoreEntry) FindGroupPastureListByIds(ctx context.Context, pastureIds []int32) ([]*model.GroupPasture, error) {
  63. groupPastureList := make([]*model.GroupPasture, 0)
  64. if err := s.DB.Model(new(model.GroupPasture)).Where("is_delete = ? ", operationPb.IsShow_OK).
  65. Where("id IN ?", pastureIds).
  66. Find(&groupPastureList).Error; err != nil {
  67. return nil, xerr.WithStack(err)
  68. }
  69. return groupPastureList, nil
  70. }
  71. func (s *StoreEntry) GetGroupPastureListById(ctx context.Context, pastureId int64) (*model.GroupPasture, error) {
  72. groupPasture := &model.GroupPasture{
  73. Id: int64(pastureId),
  74. }
  75. if err := s.DB.Model(new(model.GroupPasture)).Where("is_delete = ? ", operationPb.IsShow_OK).
  76. First(&groupPasture).Error; err != nil {
  77. return nil, xerr.WithStack(err)
  78. }
  79. return groupPasture, nil
  80. }
  81. // EditGroupPasture 创建集团牧场
  82. func (s *StoreEntry) EditGroupPasture(ctx context.Context, req *operationPb.AddPastureRequest) error {
  83. groupPasture := &model.GroupPasture{Id: int64(req.Id)}
  84. if err := s.DB.First(groupPasture).Error; err != nil {
  85. if errors.Is(err, gorm.ErrRecordNotFound) {
  86. return xerr.Custom("该数据不存在!")
  87. }
  88. return xerr.WithStack(err)
  89. }
  90. updateData := &model.GroupPasture{
  91. Name: req.Name,
  92. Account: req.Account,
  93. ManagerUser: req.ManagerUser,
  94. ManagerPhone: req.ManagerPhone,
  95. Address: req.Address,
  96. Domain: req.Domain,
  97. }
  98. if err := s.DB.Model(new(model.GroupPasture)).Omit("is_show", "password").
  99. Where("id = ?", req.Id).
  100. Updates(updateData).Error; err != nil {
  101. return xerr.WithStack(err)
  102. }
  103. return nil
  104. }
  105. // SearchGroupPastureList 查询牧场列表
  106. func (s *StoreEntry) SearchGroupPastureList(ctx context.Context, req *operationPb.SearchPastureRequest) (*operationPb.SearchPastureResponse, error) {
  107. groupPasture := make([]*model.GroupPasture, 0)
  108. var count int64 = 0
  109. pref := s.DB.Model(new(model.GroupPasture)).Where("is_delete = ? ", operationPb.IsShow_OK)
  110. if req.Name != "" {
  111. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  112. }
  113. if req.ManagerPhone != "" {
  114. pref.Where("manager_phone like ?", fmt.Sprintf("%s%s%s", "%", req.ManagerPhone, "%"))
  115. }
  116. if req.ManagerUser != "" {
  117. pref.Where("manager_user like ?", fmt.Sprintf("%s%s%s", "%", req.ManagerUser, "%"))
  118. }
  119. if req.StartTime > 0 && req.EndTime > 0 && req.EndTime >= req.StartTime {
  120. pref.Where("created_at BETWEEN ? AND ? ", req.StartTime, req.EndTime)
  121. }
  122. if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  123. Find(&groupPasture).Error; err != nil {
  124. return nil, xerr.WithStack(err)
  125. }
  126. return &operationPb.SearchPastureResponse{
  127. Code: http.StatusOK,
  128. Msg: "ok",
  129. Data: &operationPb.SearchPastureData{
  130. Page: req.Pagination.Page,
  131. Total: int32(count),
  132. PageSize: req.Pagination.PageSize,
  133. List: model.GroupPastureSlice(groupPasture).ToPB(),
  134. },
  135. }, nil
  136. }
  137. func (s *StoreEntry) DeleteGroupPasture(ctx context.Context, pastureId int64) error {
  138. groupPasture := &model.GroupPasture{
  139. Id: pastureId,
  140. }
  141. if err := s.DB.First(groupPasture).Error; err != nil {
  142. if errors.Is(err, gorm.ErrRecordNotFound) {
  143. return xerr.Custom("该数据不存在")
  144. }
  145. return xerr.WithStack(err)
  146. }
  147. if err := s.DB.Model(groupPasture).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {
  148. return xerr.WithStack(err)
  149. }
  150. return nil
  151. }
  152. func (s *StoreEntry) ResetPasswordGroupPasture(ctx context.Context, pastureId int64) error {
  153. groupPasture := &model.GroupPasture{
  154. Id: pastureId,
  155. }
  156. if err := s.DB.Where("is_delete = ?", operationPb.IsShow_OK).First(groupPasture).Error; err != nil {
  157. if errors.Is(err, gorm.ErrRecordNotFound) {
  158. return xerr.Custom("该数据不存在")
  159. }
  160. return xerr.WithStack(err)
  161. }
  162. if err := s.DB.Model(groupPasture).Update("password", tool.Md5String(model.InitManagerPassword)).Error; err != nil {
  163. return xerr.WithStack(err)
  164. }
  165. return nil
  166. }
  167. func (s *StoreEntry) IsShowGroupPasture(ctx context.Context, req *operationPb.IsShowGroupPasture) error {
  168. groupPasture := &model.GroupPasture{
  169. Id: int64(req.PastureId),
  170. }
  171. if err := s.DB.First(groupPasture).Error; err != nil {
  172. if errors.Is(err, gorm.ErrRecordNotFound) {
  173. return xerr.Custom("该数据不存在")
  174. }
  175. return xerr.WithStack(err)
  176. }
  177. if err := s.DB.Model(groupPasture).Where("is_delete = ?", operationPb.IsShow_OK).Update("is_show", req.IsShow).Error; err != nil {
  178. return xerr.WithStack(err)
  179. }
  180. return nil
  181. }
  182. // AddCattleCategory 添加畜牧分类
  183. func (s *StoreEntry) AddCattleCategory(ctx context.Context, req *operationPb.AddCattleCategoryRequest) error {
  184. cattleCategory := model.NewCattleCategory(req)
  185. if err := s.DB.Create(cattleCategory).Error; err != nil {
  186. return xerr.WithStack(err)
  187. }
  188. defer func() {
  189. body := &model.CategoryRequest{
  190. ParentId: int32(req.ParentId),
  191. ParentName: req.ParentName,
  192. Name: req.Name,
  193. Id: int32(req.Id),
  194. Number: req.Number,
  195. IsShow: int32(req.IsShow),
  196. GroupId: int32(cattleCategory.Id),
  197. }
  198. s.CategoryDistribution(ctx, model.CattleCategoryDistributionURl, body)
  199. }()
  200. return nil
  201. }
  202. // EditCattleCategory 编辑畜牧分类
  203. func (s *StoreEntry) EditCattleCategory(ctx context.Context, req *operationPb.AddCattleCategoryRequest) error {
  204. cattleCategory := &model.CattleCategory{Id: int64(req.Id)}
  205. if err := s.DB.First(cattleCategory).Error; err != nil {
  206. if errors.Is(err, gorm.ErrRecordNotFound) {
  207. return xerr.Custom("该数据不存在")
  208. }
  209. return xerr.WithStack(err)
  210. }
  211. updateData := &model.CattleCategory{
  212. ParentName: req.ParentName,
  213. Name: req.Name,
  214. Number: req.Number,
  215. ParentId: req.ParentId,
  216. }
  217. if err := s.DB.Model(new(model.CattleCategory)).Omit("is_show", "is_delete").
  218. Where("id = ?", req.Id).
  219. Updates(updateData).Error; err != nil {
  220. return xerr.WithStack(err)
  221. }
  222. defer func() {
  223. body := &model.CategoryRequest{
  224. ParentId: int32(req.ParentId),
  225. ParentName: req.ParentName,
  226. Name: req.Name,
  227. Id: int32(req.Id),
  228. Number: req.Number,
  229. IsShow: int32(req.IsShow),
  230. GroupId: int32(req.Id),
  231. }
  232. s.CategoryDistribution(ctx, model.CattleCategoryDistributionURl, body)
  233. }()
  234. return nil
  235. }
  236. // IsShowCattleCategory 是否启用
  237. func (s *StoreEntry) IsShowCattleCategory(ctx context.Context, req *operationPb.IsShowCattleCategory) error {
  238. cattleCategory := &model.CattleCategory{Id: int64(req.CattleCategoryId)}
  239. if err := s.DB.First(cattleCategory).Error; err != nil {
  240. if errors.Is(err, gorm.ErrRecordNotFound) {
  241. return xerr.Custom("该数据不存在")
  242. }
  243. return xerr.WithStack(err)
  244. }
  245. if err := s.DB.Model(new(model.CattleCategory)).Where("id = ?", req.CattleCategoryId).Update("is_show", req.IsShow).Error; err != nil {
  246. return xerr.WithStack(err)
  247. }
  248. defer func() {
  249. body := &model.CategoryRequest{
  250. ParentId: int32(cattleCategory.ParentId),
  251. ParentName: cattleCategory.ParentName,
  252. Name: cattleCategory.Name,
  253. Id: int32(req.CattleCategoryId),
  254. Number: cattleCategory.Number,
  255. IsShow: int32(req.IsShow),
  256. GroupId: int32(cattleCategory.Id),
  257. }
  258. s.CategoryDistribution(ctx, model.CattleCategoryDistributionURl, body)
  259. }()
  260. return nil
  261. }
  262. // DeleteCattleCategory 是否删除
  263. func (s *StoreEntry) DeleteCattleCategory(ctx context.Context, cattleCategoryId int64) error {
  264. cattleCategory := &model.CattleCategory{Id: cattleCategoryId}
  265. if err := s.DB.First(cattleCategory).Error; err != nil {
  266. if errors.Is(err, gorm.ErrRecordNotFound) {
  267. return xerr.Custom("该数据不存在")
  268. }
  269. return xerr.WithStack(err)
  270. }
  271. if err := s.DB.Model(new(model.CattleCategory)).Where("id = ?", cattleCategoryId).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {
  272. return xerr.WithStack(err)
  273. }
  274. return nil
  275. }
  276. // SearchCattleCategoryList 牧畜分类类别列表
  277. func (s *StoreEntry) SearchCattleCategoryList(ctx context.Context, req *operationPb.SearchCattleCategoryRequest) (*operationPb.SearchCattleCategoryResponse, error) {
  278. cattleCategory := make([]*model.CattleCategory, 0)
  279. var count int64 = 0
  280. pref := s.DB.Model(new(model.CattleCategory)).Where("is_delete = ?", operationPb.IsShow_OK)
  281. if req.Name != "" {
  282. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  283. }
  284. if req.ParentId > 0 {
  285. pref.Where("parent_id = ?", req.ParentId)
  286. }
  287. if req.IsShow > 0 {
  288. pref.Where("is_show = ?", req.IsShow)
  289. }
  290. if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  291. Find(&cattleCategory).Debug().Error; err != nil {
  292. return nil, xerr.WithStack(err)
  293. }
  294. return &operationPb.SearchCattleCategoryResponse{
  295. Code: http.StatusOK,
  296. Msg: "ok",
  297. Data: &operationPb.SearchCattleCategoryData{
  298. Page: req.Pagination.Page,
  299. PageSize: req.Pagination.PageSize,
  300. Total: int32(count),
  301. List: model.CattleCategorySlice(cattleCategory).ToPB(),
  302. },
  303. }, nil
  304. }
  305. // AddForageCategory 添加饲料分类
  306. func (s *StoreEntry) AddForageCategory(ctx context.Context, req *operationPb.AddForageCategoryRequest) error {
  307. forageCategory := model.NewForageCategory(req)
  308. if err := s.DB.Create(forageCategory).Error; err != nil {
  309. return xerr.WithStack(err)
  310. }
  311. defer func() {
  312. body := &model.CategoryRequest{
  313. ParentId: int32(req.ParentId),
  314. ParentName: req.ParentName,
  315. Name: req.Name,
  316. Id: int32(req.Id),
  317. Number: req.Number,
  318. IsShow: int32(req.IsShow),
  319. GroupId: int32(forageCategory.Id),
  320. }
  321. s.CategoryDistribution(ctx, model.ForageCategoryDistributionURl, body)
  322. }()
  323. return nil
  324. }
  325. // EditForageCategory 编辑饲料分类
  326. func (s *StoreEntry) EditForageCategory(ctx context.Context, req *operationPb.AddForageCategoryRequest) error {
  327. forageCategory := &model.ForageCategory{Id: int64(req.Id)}
  328. if err := s.DB.First(forageCategory).Error; err != nil {
  329. if errors.Is(err, gorm.ErrRecordNotFound) {
  330. return xerr.Custom("该数据不存在")
  331. }
  332. return xerr.WithStack(err)
  333. }
  334. updateData := &model.ForageCategory{
  335. ParentName: req.ParentName,
  336. Name: req.Name,
  337. Number: req.Number,
  338. ParentId: req.ParentId,
  339. }
  340. if err := s.DB.Model(new(model.ForageCategory)).Omit("is_show", "is_delete").
  341. Where("id = ?", req.Id).
  342. Updates(updateData).Error; err != nil {
  343. return xerr.WithStack(err)
  344. }
  345. defer func() {
  346. body := &model.CategoryRequest{
  347. ParentId: int32(req.ParentId),
  348. ParentName: req.ParentName,
  349. Name: req.Name,
  350. Id: int32(req.Id),
  351. Number: req.Number,
  352. IsShow: int32(req.IsShow),
  353. GroupId: int32(req.Id),
  354. }
  355. s.CategoryDistribution(ctx, model.ForageCategoryDistributionURl, body)
  356. }()
  357. return nil
  358. }
  359. // IsShowForageCategory 是否启用
  360. func (s *StoreEntry) IsShowForageCategory(ctx context.Context, req *operationPb.IsShowForageCategory) error {
  361. forageCategory := &model.ForageCategory{Id: int64(req.ForageCategoryId)}
  362. if err := s.DB.First(forageCategory).Error; err != nil {
  363. if errors.Is(err, gorm.ErrRecordNotFound) {
  364. return xerr.Custom("该数据不存在")
  365. }
  366. return xerr.WithStack(err)
  367. }
  368. if err := s.DB.Model(new(model.ForageCategory)).Where("id = ?", req.ForageCategoryId).Update("is_show", req.IsShow).Error; err != nil {
  369. return xerr.WithStack(err)
  370. }
  371. defer func() {
  372. body := &model.CategoryRequest{
  373. ParentId: int32(forageCategory.ParentId),
  374. ParentName: forageCategory.ParentName,
  375. Name: forageCategory.Name,
  376. Id: req.ForageCategoryId,
  377. Number: forageCategory.Number,
  378. IsShow: int32(req.IsShow),
  379. GroupId: int32(forageCategory.Id),
  380. }
  381. s.CategoryDistribution(ctx, model.ForageCategoryDistributionURl, body)
  382. }()
  383. return nil
  384. }
  385. // DeleteForageCategory 是否删除
  386. func (s *StoreEntry) DeleteForageCategory(ctx context.Context, forageCategoryId int64) error {
  387. forageCategory := &model.ForageCategory{Id: forageCategoryId}
  388. if err := s.DB.First(forageCategory).Error; err != nil {
  389. if errors.Is(err, gorm.ErrRecordNotFound) {
  390. return xerr.Custom("该数据不存在")
  391. }
  392. return xerr.WithStack(err)
  393. }
  394. if err := s.DB.Model(new(model.ForageCategory)).Where("id = ?", forageCategoryId).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {
  395. return xerr.WithStack(err)
  396. }
  397. return nil
  398. }
  399. // SearchForageCategoryList 饲料分类类别列表
  400. func (s *StoreEntry) SearchForageCategoryList(ctx context.Context, req *operationPb.SearchForageCategoryRequest) (*operationPb.SearchForageCategoryResponse, error) {
  401. forageCategory := make([]*model.ForageCategory, 0)
  402. var count int64 = 0
  403. pref := s.DB.Model(new(model.ForageCategory)).Where("is_delete = ?", operationPb.IsShow_OK)
  404. if req.Name != "" {
  405. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  406. }
  407. if req.ParentId > 0 {
  408. pref.Where("parent_id = ?", req.ParentId)
  409. }
  410. if req.Number != "" {
  411. pref.Where("number like ?", fmt.Sprintf("%s%s%s", "%", req.Number, "%"))
  412. }
  413. if req.IsShow > 0 {
  414. pref.Where("is_show = ?", req.IsShow)
  415. }
  416. if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  417. Find(&forageCategory).Debug().Error; err != nil {
  418. return nil, xerr.WithStack(err)
  419. }
  420. return &operationPb.SearchForageCategoryResponse{
  421. Code: http.StatusOK,
  422. Msg: "ok",
  423. Data: &operationPb.SearchForageCategoryData{
  424. Page: req.Pagination.Page,
  425. PageSize: req.Pagination.PageSize,
  426. Total: int32(count),
  427. List: model.ForageCategorySlice(forageCategory).ToPB(),
  428. },
  429. }, nil
  430. }
  431. // CategoryDistribution 饲料分类和畜牧分类下发
  432. func (s *StoreEntry) CategoryDistribution(ctx context.Context, url string, req *model.CategoryRequest) error {
  433. groupList, err := s.SearchGroupPastureList(ctx, &operationPb.SearchPastureRequest{})
  434. if err != nil {
  435. return xerr.WithStack(err)
  436. }
  437. wg := sync.WaitGroup{}
  438. wg.Add(len(groupList.Data.List))
  439. for _, v := range groupList.Data.List {
  440. go func(data *operationPb.AddPastureRequest) {
  441. res := &model.PastureCommonResponse{}
  442. req.Id = data.Id
  443. if err = s.PastureHttpClient(ctx, url, int64(data.Id), req, res); err != nil {
  444. zaplog.Error("CategoryDistribution",
  445. zap.Any("url", url),
  446. zap.Any("err", err),
  447. zap.Any("body", req),
  448. zap.Any("res", res),
  449. )
  450. }
  451. if res.Code != http.StatusOK {
  452. zaplog.Error("CategoryDistribution-http",
  453. zap.Any("url", url),
  454. zap.Any("body", req),
  455. zap.Any("res", res),
  456. )
  457. }
  458. wg.Done()
  459. }(v)
  460. }
  461. wg.Wait()
  462. return nil
  463. }
  464. // CreateForage 创建饲料
  465. func (s *StoreEntry) CreateForage(ctx context.Context, req *operationPb.AddForageRequest) error {
  466. forage := model.NewForage(req)
  467. if err := s.DB.Create(forage).Error; err != nil {
  468. return xerr.WithStack(err)
  469. }
  470. return nil
  471. }
  472. // EditForage 编辑饲料
  473. func (s *StoreEntry) EditForage(ctx context.Context, req *operationPb.AddForageRequest) error {
  474. forage := model.Forage{Id: int64(req.Id)}
  475. if err := s.DB.Where("is_delete = ?", operationPb.IsShow_OK).First(&forage).Error; err != nil {
  476. if errors.Is(err, gorm.ErrRecordNotFound) {
  477. return xerr.Custom("该数据不存在")
  478. }
  479. return xerr.WithStack(err)
  480. }
  481. updateData := &model.Forage{
  482. Name: req.Name,
  483. CategoryId: int64(req.CategoryId),
  484. CategoryName: req.CategoryName,
  485. MaterialType: req.MaterialType,
  486. UniqueEncode: req.UniqueEncode,
  487. ForageSourceId: req.ForageSourceId,
  488. PlanTypeId: req.PlanTypeId,
  489. SmallMaterialScale: req.SmallMaterialScale,
  490. AllowError: int64(req.AllowError),
  491. PackageWeight: int64(req.PackageWeight),
  492. Price: int64(req.Price),
  493. JumpWeight: int64(req.JumpWeight),
  494. JumpDelay: req.JumpDelay,
  495. ConfirmStart: req.ConfirmStart,
  496. RelayLocations: int64(req.RelayLocations),
  497. Jmp: req.Jmp,
  498. Backup1: req.Backup1,
  499. Backup2: req.Backup2,
  500. Backup3: req.Backup3,
  501. }
  502. if err := s.DB.Model(new(model.Forage)).Omit("is_show", "is_delete").Where("id = ?", req.Id).
  503. Updates(updateData).Error; err != nil {
  504. return xerr.WithStack(err)
  505. }
  506. return nil
  507. }
  508. func (s *StoreEntry) SearchForageList(ctx context.Context, req *operationPb.SearchForageListRequest) (*operationPb.SearchForageListResponse, error) {
  509. forage := make([]*model.Forage, 0)
  510. var count int64 = 0
  511. pref := s.DB.Model(new(model.Forage)).Where("is_delete = ?", operationPb.IsShow_OK)
  512. if req.Name != "" {
  513. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  514. }
  515. if req.CategoryId > 0 {
  516. pref.Where("category_id = ?", req.CategoryId)
  517. }
  518. if req.ForageSourceId > 0 {
  519. pref.Where("forage_source_id = ?", req.ForageSourceId)
  520. }
  521. if req.IsShow > 0 {
  522. pref.Where("is_show = ?", req.IsShow)
  523. }
  524. if req.AllowError > 0 {
  525. pref.Where("allow_error = ?", req.AllowError)
  526. }
  527. if req.JumpWeight > 0 {
  528. pref.Where("jump_weight = ?", req.JumpWeight)
  529. }
  530. if req.JumpDelay > 0 {
  531. pref.Where("jump_delay = ?", req.JumpDelay)
  532. }
  533. if err := pref.Order("sort").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  534. Find(&forage).Error; err != nil {
  535. return nil, xerr.WithStack(err)
  536. }
  537. return &operationPb.SearchForageListResponse{
  538. Code: http.StatusOK,
  539. Msg: "ok",
  540. Data: &operationPb.SearchForageList{
  541. Page: req.Pagination.Page,
  542. PageSize: req.Pagination.PageSize,
  543. Total: int32(count),
  544. List: model.ForageSlice(forage).ToPB(),
  545. },
  546. }, nil
  547. }
  548. func (s *StoreEntry) ForageListSort(ctx context.Context, req *operationPb.ForageListSortRequest) error {
  549. for _, v := range req.List {
  550. if err := s.DB.Model(new(model.Forage)).Select("sort").Where("id = ?", v.Id).Updates(map[string]interface{}{
  551. "sort": v.Sort,
  552. }).Error; err != nil {
  553. zaplog.Error("ForageListSort", zap.Any("err", err), zap.Any("id", v.Id), zap.Any("sort", v.Sort))
  554. }
  555. }
  556. return nil
  557. }
  558. func (s *StoreEntry) ForageEnumList(ctx context.Context) *operationPb.ForageEnumListResponse {
  559. res := &operationPb.ForageEnumListResponse{
  560. Code: http.StatusOK,
  561. Msg: "ok",
  562. Data: &operationPb.ForageEnumList{
  563. JumpDelaType: make([]*operationPb.JumpDelaTypeEnum, 0),
  564. ForageSource: make([]*operationPb.ForageSourceEnum, 0),
  565. ForagePlanType: make([]*operationPb.ForagePlanTypeEnum, 0),
  566. CattleParentCategory: make([]*operationPb.CattleParentCategoryEnum, 0),
  567. ForageParentCategory: make([]*operationPb.ForageParentCategoryEnum, 0),
  568. IsShow: make([]*operationPb.IsShowEnum, 0),
  569. FormulaType: make([]*operationPb.FormulaTypeEnum, 0),
  570. FormulaList: make([]*operationPb.FormulaOptionEnum, 0),
  571. ConfirmStart: make([]*operationPb.IsShowEnum, 0),
  572. FormulationEvaluation: make([]*operationPb.FormulaOptionEnum, 0),
  573. UseMaterialsType: make([]*operationPb.FormulaOptionEnum, 0),
  574. UseMaterialsList: make([]*operationPb.FormulaOptionEnum, 0),
  575. PriceMaterialsType: make([]*operationPb.FormulaOptionEnum, 0),
  576. },
  577. }
  578. // 跳转延迟
  579. res.Data.JumpDelaType = append(res.Data.JumpDelaType, &operationPb.JumpDelaTypeEnum{
  580. Value: operationPb.JumpDelaType_INVALID,
  581. Label: "禁用",
  582. }, &operationPb.JumpDelaTypeEnum{
  583. Value: operationPb.JumpDelaType_THREE,
  584. Label: "3秒",
  585. }, &operationPb.JumpDelaTypeEnum{
  586. Value: operationPb.JumpDelaType_SIX,
  587. Label: "6秒",
  588. })
  589. // 饲料来源
  590. res.Data.ForageSource = append(res.Data.ForageSource, &operationPb.ForageSourceEnum{
  591. Value: operationPb.ForageSource_SYSTEM_BUILT_IN,
  592. Label: "系统内置",
  593. }, &operationPb.ForageSourceEnum{
  594. Value: operationPb.ForageSource_USER_DEFINED,
  595. Label: "用户自定义",
  596. })
  597. // 计划类型
  598. res.Data.ForagePlanType = append(res.Data.ForagePlanType,
  599. &operationPb.ForagePlanTypeEnum{
  600. Value: operationPb.ForagePlanType_INVALID,
  601. Label: "无",
  602. },
  603. &operationPb.ForagePlanTypeEnum{
  604. Value: operationPb.ForagePlanType_FORKLIFT,
  605. Label: "铲车",
  606. }, &operationPb.ForagePlanTypeEnum{
  607. Value: operationPb.ForagePlanType_CONCENTRATE,
  608. Label: "精料",
  609. })
  610. // 畜牧类别
  611. res.Data.CattleParentCategory = append(res.Data.CattleParentCategory, &operationPb.CattleParentCategoryEnum{
  612. Value: operationPb.CattleCategoryParent_LACTATION_CAW,
  613. Label: "泌乳牛",
  614. }, &operationPb.CattleParentCategoryEnum{
  615. Value: operationPb.CattleCategoryParent_FATTEN_CAW,
  616. Label: "育肥牛",
  617. }, &operationPb.CattleParentCategoryEnum{
  618. Value: operationPb.CattleCategoryParent_RESERVE_CAW,
  619. Label: "后备牛",
  620. }, &operationPb.CattleParentCategoryEnum{
  621. Value: operationPb.CattleCategoryParent_DRY_CAW,
  622. Label: "干奶牛",
  623. }, &operationPb.CattleParentCategoryEnum{
  624. Value: operationPb.CattleCategoryParent_PERINATAL_CAW,
  625. Label: "围产牛",
  626. }, &operationPb.CattleParentCategoryEnum{
  627. Value: operationPb.CattleCategoryParent_OTHER_CAW,
  628. Label: "其他",
  629. })
  630. // 饲料类别
  631. res.Data.ForageParentCategory = append(res.Data.ForageParentCategory, &operationPb.ForageParentCategoryEnum{
  632. Value: operationPb.ForageCategoryParent_ROUGHAGE,
  633. Label: "粗料",
  634. }, &operationPb.ForageParentCategoryEnum{
  635. Value: operationPb.ForageCategoryParent_CONCENTRATE,
  636. Label: "精料",
  637. }, &operationPb.ForageParentCategoryEnum{
  638. Value: operationPb.ForageCategoryParent_HALF_ROUGHAGE_HALF_CONCENTRATE,
  639. Label: "粗料精料参半",
  640. }, &operationPb.ForageParentCategoryEnum{
  641. Value: operationPb.ForageCategoryParent_OTHER,
  642. Label: "其他",
  643. })
  644. res.Data.IsShow = append(res.Data.IsShow, &operationPb.IsShowEnum{
  645. Value: operationPb.IsShow_OK,
  646. Label: "是",
  647. }, &operationPb.IsShowEnum{
  648. Value: operationPb.IsShow_NO,
  649. Label: "否",
  650. })
  651. res.Data.FormulationEvaluation = append(res.Data.FormulationEvaluation, &operationPb.FormulaOptionEnum{
  652. Value: 0,
  653. Label: "按配方查询",
  654. }, &operationPb.FormulaOptionEnum{
  655. Value: 1,
  656. Label: "按栏舍查询",
  657. })
  658. res.Data.FormulaType = append(res.Data.FormulaType, &operationPb.FormulaTypeEnum{
  659. Value: operationPb.FormulaType_FEED_FORMULA,
  660. Label: "饲喂配方",
  661. }, &operationPb.FormulaTypeEnum{
  662. Value: operationPb.FormulaType_PREMIXED_FORMULA,
  663. Label: "预混配方",
  664. }, &operationPb.FormulaTypeEnum{
  665. Value: operationPb.FormulaType_SUPPLEMENTARY_FORMULA,
  666. Label: "补料配方",
  667. })
  668. res.Data.ConfirmStart = append(res.Data.ConfirmStart, &operationPb.IsShowEnum{
  669. Value: operationPb.IsShow_OK,
  670. Label: "启用",
  671. }, &operationPb.IsShowEnum{
  672. Value: operationPb.IsShow_NO,
  673. Label: "禁用",
  674. })
  675. res.Data.UseMaterialsList = append(res.Data.UseMaterialsList, &operationPb.FormulaOptionEnum{
  676. Value: 1,
  677. Label: "理论",
  678. }, &operationPb.FormulaOptionEnum{
  679. Value: 2,
  680. Label: "实际",
  681. })
  682. res.Data.PriceMaterialsType = append(res.Data.PriceMaterialsType, &operationPb.FormulaOptionEnum{
  683. Value: 1,
  684. Label: "畜牧类别",
  685. }, &operationPb.FormulaOptionEnum{
  686. Value: 2,
  687. Label: "栏舍名称",
  688. }, &operationPb.FormulaOptionEnum{
  689. Value: 3,
  690. Label: "日期",
  691. }, &operationPb.FormulaOptionEnum{
  692. Value: 4,
  693. Label: "TMR设备号",
  694. })
  695. res.Data.UseMaterialsType = append(res.Data.PriceMaterialsType, &operationPb.FormulaOptionEnum{
  696. Value: 5,
  697. Label: "TMR班次",
  698. }, &operationPb.FormulaOptionEnum{
  699. Value: 6,
  700. Label: "车次",
  701. })
  702. res.Data.JumpType = append(res.Data.JumpType, &operationPb.FormulaOptionEnum{
  703. Value: 0,
  704. Label: "手动跳转",
  705. }, &operationPb.FormulaOptionEnum{
  706. Value: 1,
  707. Label: "自动跳转",
  708. })
  709. res.Data.StatisticsType = append(res.Data.StatisticsType, &operationPb.FormulaOptionEnum{
  710. Value: 7,
  711. Label: "无分类",
  712. }, &operationPb.FormulaOptionEnum{
  713. Value: 0,
  714. Label: "驾驶员",
  715. }, &operationPb.FormulaOptionEnum{
  716. Value: 1,
  717. Label: "配方名称",
  718. }, &operationPb.FormulaOptionEnum{
  719. Value: 2,
  720. Label: "栏舍名称",
  721. }, &operationPb.FormulaOptionEnum{
  722. Value: 3,
  723. Label: "牧畜类别",
  724. }, &operationPb.FormulaOptionEnum{
  725. Value: 4,
  726. Label: "车次",
  727. }, &operationPb.FormulaOptionEnum{
  728. Value: 5,
  729. Label: "TMR名称",
  730. }, &operationPb.FormulaOptionEnum{
  731. Value: 6,
  732. Label: "饲料",
  733. })
  734. res.Data.FormulaList = append(res.Data.FormulaList, &operationPb.FormulaOptionEnum{
  735. Value: 0,
  736. Label: "所有",
  737. })
  738. formulaList := make([]*model.FeedFormula, 0)
  739. if err := s.DB.Where("is_delete = ?", operationPb.IsShow_OK).Find(&formulaList).Error; err != nil {
  740. zaplog.Error("OptionFormula", zap.Any("Err", err))
  741. return res
  742. }
  743. for _, v := range formulaList {
  744. res.Data.FormulaList = append(res.Data.FormulaList, &operationPb.FormulaOptionEnum{
  745. Value: int32(v.Id),
  746. Label: v.Name,
  747. })
  748. }
  749. return res
  750. }
  751. func (s *StoreEntry) DeleteForageList(ctx context.Context, ids []int64) error {
  752. if len(ids) == 0 {
  753. return xerr.Custom("参数错误")
  754. }
  755. if err := s.DB.Model(new(model.Forage)).Where("id IN ?", ids).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {
  756. return xerr.WithStack(err)
  757. }
  758. return nil
  759. }
  760. func (s *StoreEntry) IsShowForage(ctx context.Context, req *operationPb.IsShowForage) error {
  761. forage := &model.Forage{Id: int64(req.ForageId)}
  762. if err := s.DB.First(forage).Error; err != nil {
  763. if errors.Is(err, gorm.ErrRecordNotFound) {
  764. return xerr.Custom("该数据不存在")
  765. }
  766. return xerr.WithStack(err)
  767. }
  768. if err := s.DB.Model(new(model.Forage)).Where("id = ?", req.ForageId).Update("is_show", req.IsShow).Error; err != nil {
  769. return xerr.WithStack(err)
  770. }
  771. return nil
  772. }
  773. // ExcelImportForage 导入excel
  774. func (s *StoreEntry) ExcelImportForage(ctx context.Context, req io.Reader) error {
  775. xlsx, err := excelize.OpenReader(req)
  776. if err != nil {
  777. return xerr.WithStack(err)
  778. }
  779. defer xlsx.Close()
  780. rows, err := xlsx.GetRows(xlsx.GetSheetName(xlsx.GetActiveSheetIndex()))
  781. if err != nil {
  782. return xerr.WithStack(err)
  783. }
  784. if len(rows) > 10000 {
  785. rows = rows[:10000]
  786. }
  787. forageList := make([]*model.Forage, 0)
  788. for i, row := range rows {
  789. if i == 0 {
  790. continue
  791. }
  792. var (
  793. forageSourceId int32
  794. categoryId, price, jumpWeight, relayLocations int
  795. allowError, packageWeight int
  796. name, uniqueEncode, backup1, backup2, backup3 string
  797. )
  798. for k, v := range row {
  799. if k == 0 {
  800. name = v
  801. }
  802. if k == 2 {
  803. uniqueEncode = v
  804. }
  805. if k == 3 {
  806. forageSourceId = operationPb.ForageSource_Kind_value[v]
  807. }
  808. if k == 5 {
  809. allowError, _ = strconv.Atoi(v)
  810. }
  811. if k == 6 {
  812. packageWeight, _ = strconv.Atoi(v)
  813. }
  814. if k == 7 {
  815. price, _ = strconv.Atoi(v)
  816. }
  817. if k == 8 {
  818. jumpWeight, _ = strconv.Atoi(v)
  819. }
  820. if k == 11 {
  821. relayLocations, _ = strconv.Atoi(v)
  822. }
  823. if k == 13 {
  824. backup1 = v
  825. }
  826. if k == 14 {
  827. backup2 = v
  828. }
  829. if k == 15 {
  830. backup3 = v
  831. }
  832. }
  833. forageItem := &model.Forage{
  834. Name: name,
  835. CategoryId: int64(categoryId),
  836. MaterialType: 0,
  837. UniqueEncode: uniqueEncode,
  838. ForageSourceId: operationPb.ForageSource_Kind(forageSourceId),
  839. PlanTypeId: 0,
  840. SmallMaterialScale: "",
  841. AllowError: int64(allowError),
  842. PackageWeight: int64(packageWeight),
  843. Price: int64(price),
  844. JumpWeight: int64(jumpWeight),
  845. JumpDelay: 0,
  846. ConfirmStart: 0,
  847. RelayLocations: int64(relayLocations),
  848. Jmp: 0,
  849. Backup1: backup1,
  850. Backup2: backup2,
  851. Backup3: backup3,
  852. IsShow: operationPb.IsShow_OK,
  853. IsDelete: operationPb.IsShow_OK,
  854. DataSource: operationPb.DataSource_EXCEL_IMPORT,
  855. }
  856. forageList = append(forageList, forageItem)
  857. }
  858. if len(forageList) > 0 {
  859. if err = s.DB.Create(forageList).Error; err != nil {
  860. return xerr.WithStack(err)
  861. }
  862. }
  863. return nil
  864. }
  865. // ExcelExportForage 流式导出excel
  866. func (s *StoreEntry) ExcelExportForage(ctx context.Context, req *operationPb.SearchForageListRequest) (*bytes.Buffer, error) {
  867. res, err := s.SearchForageList(ctx, req)
  868. if err != nil {
  869. return nil, xerr.WithStack(err)
  870. }
  871. if len(res.Data.List) <= 0 {
  872. return nil, xerr.Custom("数据为空")
  873. }
  874. file := excelize.NewFile()
  875. defer file.Close()
  876. streamWriter, err := file.NewStreamWriter(model.DefaultSheetName)
  877. if err != nil {
  878. return nil, xerr.WithStack(err)
  879. }
  880. titles := []interface{}{"饲料名称", "饲料分类", "唯一编码", "饲料来源", "计划类型", "允许误差(kg)", "包装单位重量(kg)",
  881. "单价", "跳转重量域(kg)", "跳转延迟", "确认开始", "继电器位置", "无上域", "备用字段01", "备用字段02", "备用字段03"}
  882. if err = streamWriter.SetRow("A1", titles); err != nil {
  883. return nil, xerr.WithStack(err)
  884. }
  885. for i, item := range res.Data.List {
  886. cell, err := excelize.CoordinatesToCellName(1, i+2)
  887. if err != nil {
  888. zaplog.Error("excelize.CoordinatesToCellName", zap.Any("Err", err))
  889. continue
  890. }
  891. row := make([]interface{}, 0)
  892. row = append(row, item.Name, item.CategoryName, item.UniqueEncode, item.ForageSourceId, item.PlanTypeId,
  893. item.AllowError, item.PackageWeight, float64(item.Price/100.00), item.JumpWeight, item.JumpDelay,
  894. item.ConfirmStart, item.RelayLocations, item.Jmp, item.Backup1, item.Backup2, item.Backup3)
  895. if err = streamWriter.SetRow(cell, row); err != nil {
  896. return nil, xerr.WithStack(err)
  897. }
  898. }
  899. if err = streamWriter.Flush(); err != nil {
  900. return nil, xerr.WithStack(err)
  901. }
  902. return file.WriteToBuffer()
  903. }
  904. // ExcelTemplateForage 导出模板
  905. func (s *StoreEntry) ExcelTemplateForage(ctx context.Context) (*bytes.Buffer, error) {
  906. file := excelize.NewFile()
  907. defer file.Close()
  908. streamWriter, err := file.NewStreamWriter("Sheet1")
  909. if err != nil {
  910. return nil, xerr.WithStack(err)
  911. }
  912. titles := []interface{}{"饲料名称", "饲料分类", "唯一编码", "饲料来源", "计划类型", "允许误差(kg)", "包装单位重量(kg)",
  913. "单价", "跳转重量域(kg)", "跳转延迟", "确认开始", "继电器位置", "无上域", "备用字段01", "备用字段02", "备用字段03"}
  914. if err = streamWriter.SetRow("A1", titles); err != nil {
  915. return nil, xerr.WithStack(err)
  916. }
  917. if err = streamWriter.Flush(); err != nil {
  918. return nil, xerr.WithStack(err)
  919. }
  920. return file.WriteToBuffer()
  921. }
  922. func (s *StoreEntry) SmallMaterial(ctx context.Context, req *operationPb.SmallMaterialRequest) (*model.PastureCommonResponse, error) {
  923. body := &model.PastureCommonRequest{
  924. Name: req.ApiName,
  925. ReturnType: "Map",
  926. ParamMaps: &model.FormulaEstimateParams{
  927. PastureId: fmt.Sprintf("%d", req.PastureId),
  928. ImforName: req.InfoName,
  929. },
  930. }
  931. response := &model.PastureCommonResponse{Data: &model.PastureCommonData{}}
  932. if err := s.PastureHttpClient(ctx, model.UrlDataByName, int64(req.PastureId), body, response); err != nil {
  933. return nil, xerr.WithStack(err)
  934. }
  935. return response, nil
  936. }