group.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. package module
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "strconv"
  7. "time"
  8. "tmr-watch/http/handle/restful"
  9. "tmr-watch/models"
  10. "tmr-watch/pkg/logger/zaplog"
  11. "go.uber.org/zap"
  12. operationPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/operation"
  13. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/pasture"
  14. "github.com/xormplus/xorm"
  15. )
  16. // DistributeFeedFormula 接受集团饲料配方下发
  17. func DistributeFeedFormula(feedTemplateList []*models.FeedTemplate) error {
  18. tx := restful.Engine.NewSession()
  19. defer tx.Close()
  20. for _, feedTemplate := range feedTemplateList {
  21. // 过滤掉没有饲料详情的配方
  22. if len(feedTemplate.FeedFormulaDetail) <= 0 {
  23. continue
  24. }
  25. if _, err := tx.Table(new(models.FeedTemplate)).Insert(feedTemplate); err != nil {
  26. return err
  27. }
  28. feedFormulaDetail := make([]*models.FeedTemplateDetail, 0)
  29. for _, f := range feedTemplate.FeedFormulaDetail {
  30. f.FtId = feedTemplate.Id
  31. feedFormulaDetail = append(feedFormulaDetail, f)
  32. }
  33. zaplog.Info("feedFormulaDetail", zap.Any("feedFormulaDetail", feedFormulaDetail))
  34. if _, err := tx.Table(new(models.FeedTemplateDetail)).Insert(feedFormulaDetail); err != nil {
  35. return err
  36. }
  37. }
  38. return tx.Commit()
  39. }
  40. // CancelDistributeFeedFormula 集团饲料配方取消下发
  41. func CancelDistributeFeedFormula(pastureId int64, ids []int64) error {
  42. if _, err := restful.Engine.Table(new(models.FeedTemplate)).
  43. Where("id IN ?", ids).Where("pasture_id = ?", pastureId).Update(map[string]interface{}{"enable": 2, "is_modify": 2}); err != nil {
  44. return err
  45. }
  46. return nil
  47. }
  48. func FeedFormulaIsModify(req *models.PastureFeedFormulaIsModifyRequest) error {
  49. if _, err := restful.Engine.Table(new(models.FeedTemplate)).Cols("is_modify").
  50. Where("id = ?", req.FeedFormulaId).And("pastureid = ?", req.PastureId).
  51. Update(map[string]interface{}{"is_modify": req.IsModify}); err != nil {
  52. return err
  53. }
  54. return nil
  55. }
  56. // MixedFodderData 混料准确率
  57. func MixedFodderData(req *models.AnalysisAccuracyRequest) ([]*models.MixedFodderDataList, error) {
  58. res := make([]*models.MixedFodderDataList, 0)
  59. whereFeedFormulaIdStr := ""
  60. if req.FeedFormulaId > 0 {
  61. whereFeedFormulaIdStr = fmt.Sprintf(" AND f.ccid = %d", req.FeedFormulaId)
  62. }
  63. sql := fmt.Sprintf(`SELECT DATE(de.date) AS plan_time,
  64. CONCAT( IF (SUM(de.actualweightminus)>SUM(de.lweight),ROUND((SUM(de.lweight)/SUM(de.actualweightminus)*100),2) ,SUM(de.actualweightminus)/SUM(de.lweight)*100) ,2) AS mixed_fodder_accurate_ratio,
  65. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) AS mixed_fodder_correct_ratio
  66. FROM downloadplandtl1 de
  67. LEFT JOIN downloadedplan d ON d.id = de.pid
  68. LEFT JOIN feedtemplet f ON f.id = d.tempid
  69. WHERE de.pastureid= %d AND de.intime IS NOT NULL
  70. AND (SELECT d.lpplantype FROM downloadedplan d WHERE d.pastureid = de.pastureid AND d.id = de.pid) IN (0,1,4)
  71. AND de.date >= '%s' AND de.date <= '%s' %s GROUP BY de.date`, req.PastureId, req.StartDate, req.EndDate, whereFeedFormulaIdStr)
  72. if err := restful.Engine.SQL(sql).Find(&res); err != nil {
  73. return nil, err
  74. }
  75. return res, nil
  76. }
  77. // SprinkleFodderData 撒料准确率
  78. func SprinkleFodderData(req *models.AnalysisAccuracyRequest) ([]*models.SprinkleFodderDataList, error) {
  79. res := make([]*models.SprinkleFodderDataList, 0)
  80. whereFeedFormulaIdStr := ""
  81. if req.FeedFormulaId > 0 {
  82. whereFeedFormulaIdStr = fmt.Sprintf(" AND f.ccid = %d", req.FeedFormulaId)
  83. }
  84. sql := fmt.Sprintf(`SELECT DATE(d.mydate) AS plan_time,
  85. CONCAT( IF (SUM(de.actualweightminus)>SUM(de.lweight),ROUND((SUM(de.lweight)/SUM(de.actualweightminus)*100),2),SUM(de.actualweightminus)/SUM(de.lweight)*100) ,2) AS sprinkle_fodder_accurate_ratio,
  86. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) AS sprinkle_fodder_correct_ratio
  87. FROM downloadplandtl2 de
  88. JOIN downloadedplan d ON d.id=de.pid AND d.pastureid = de.pastureid
  89. LEFT JOIN feedtemplet f ON f.id = d.tempid
  90. WHERE de.pastureid = %d AND DATE(de.date) BETWEEN '%s' AND '%s' %s GROUP BY de.date`, req.PastureId, req.StartDate, req.EndDate, whereFeedFormulaIdStr)
  91. if err := restful.Engine.SQL(sql).Find(&res); err != nil {
  92. return nil, err
  93. }
  94. return res, nil
  95. }
  96. // TMRList tmr设备列表
  97. func TMRList(req *models.AnalysisAccuracyRequest) ([]*models.ProcessData, error) {
  98. res := make([]*models.ProcessData, 0)
  99. sql := fmt.Sprintf(`SELECT d.lpplantype as plan_type,
  100. d.tmrtname as tmr_name,
  101. f.ccid as c_cid,
  102. TRIM(d.pastureid) as pasture_id,
  103. TRIM(d.pid) as pid,
  104. TRIM(d.id) as id
  105. FROM downloadedplan d
  106. LEFT JOIN feedtemplet f on f.id = d.tempid
  107. WHERE d.pastureid= %d and d.intime IS NOT NULL
  108. AND d.mydate >= '%s' AND d.mydate <= '%s'`, req.PastureId, req.StartDate, req.EndDate)
  109. if req.CattleParentCategoryId > 0 {
  110. sql = fmt.Sprintf("%s AND f.ccid = %d", sql, req.CattleParentCategoryId)
  111. }
  112. if err := restful.Engine.SQL(sql).Find(&res); err != nil {
  113. return nil, err
  114. }
  115. return res, nil
  116. }
  117. // MixedProcessTimeList 混料时间列表
  118. func MixedProcessTimeList(pastureId int32, id int64) ([]*models.ProcessTimeList, error) {
  119. res := make([]*models.ProcessTimeList, 0)
  120. sql := fmt.Sprintf(`SELECT IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  121. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime)),TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  122. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))) AS process_time
  123. FROM downloadplandtl1_exec d1 WHERE d1.pastureid = %d AND d1.pid = %d ORDER BY sort`, pastureId, id)
  124. if err := restful.Engine.SQL(sql).Find(&res); err != nil {
  125. return nil, err
  126. }
  127. return res, nil
  128. }
  129. // SprinkleProcessTimeList 混料时间列表
  130. func SprinkleProcessTimeList(pastureId int32, id int64) ([]*models.ProcessTimeList, error) {
  131. res := make([]*models.ProcessTimeList, 0)
  132. sql := fmt.Sprintf(`SELECT IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  133. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime)), TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  134. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))) AS process_time FROM downloadplandtl2 d1
  135. WHERE d1.pastureid = %d AND pid =%d ORDER BY sort`, pastureId, id)
  136. if err := restful.Engine.SQL(sql).Find(&res); err != nil {
  137. return nil, err
  138. }
  139. return res, nil
  140. }
  141. func SprinkleStatistics(req *models.SprinkleStatisticsRequest) ([]*models.SprinkleStatisticsDataList, error) {
  142. res := make([]*models.SprinkleStatisticsDataList, 0)
  143. newSql := restful.Engine.Table("downloadedplan").Alias("b").
  144. Select("a.fbarid,a.fname,a.intime,a.processtime,b.times").
  145. Join("LEFT", []string{"downloadplandtl2", "a"}, "a.pastureid = b.pastureid AND b.pid = a.flpid").
  146. Where("a.pastureid = ?", req.PastureId).And("b.times > 0 ").
  147. And("a.fbarid > 0").And("a.intime IS NOT NULL").And("a.processtime IS NOT NULL")
  148. if len(req.StartDate) > 0 && len(req.EndDate) > 0 {
  149. newSql.And("a.date >= ? and a.date <= ?", req.StartDate, req.EndDate)
  150. }
  151. if req.FeedFormulaId > 0 {
  152. newSql.And("a.feedtempletid = ?", req.FeedFormulaId)
  153. }
  154. if err := newSql.GroupBy("a.fbarid ,b.intime").Limit(100).Find(&res); err != nil {
  155. return nil, err
  156. }
  157. return res, nil
  158. }
  159. func AccountDistribution(req *models.AccountDistributionRequest) error {
  160. res := &models.User{}
  161. _, err := restful.Engine.Select("pastureid,username,empname,password,phone").
  162. Where("enable = ?", operationPb.IsShow_OK).And("isdelete = ?", operationPb.IsShow_NO).And("pastureid = ?", req.PastureId).
  163. And("username = ?", req.Account).Get(res)
  164. if err != nil {
  165. return err
  166. }
  167. if res.Username == req.Account {
  168. return errors.New("该账号已经存在")
  169. }
  170. session := restful.Engine.NewSession()
  171. defer session.Close()
  172. if err = session.Begin(); err != nil {
  173. return err
  174. }
  175. // 查看牧场是否存在
  176. pastureData := &models.Pasture{}
  177. if _, err = session.Table(new(models.Pasture).TableName()).Where("pastureid = ?", req.PastureId).Get(pastureData); err != nil {
  178. return err
  179. }
  180. if pastureData.PastureId <= 0 {
  181. newPasture := models.NewPasture(int64(req.PastureId), req.PastureName, req.Address, req.UserName, req.Phone)
  182. if _, err = session.Table(new(models.Pasture).TableName()).Insert(newPasture); err != nil {
  183. return err
  184. }
  185. }
  186. // 查询牧场对应菜单是否存在
  187. menuPasture := &models.MenuPasture{}
  188. if _, err = session.Table(new(models.MenuPasture).TableName()).Where("pastureid = ?", req.PastureId).Get(menuPasture); err != nil {
  189. return err
  190. }
  191. // 创建新的超级管理员角色
  192. newRole := models.NewDefaultRole(int64(req.PastureId))
  193. if _, err = session.Table(new(models.Role).TableName()).Insert(newRole); err != nil {
  194. return err
  195. }
  196. menuList := make([]*models.Menu, 0)
  197. if err = session.Table(new(models.Menu).TableName()).Find(&menuList); err != nil {
  198. return err
  199. }
  200. if menuPasture.PastureId <= 0 {
  201. newMenuPastureList := models.NewMenuPastureList(int64(req.PastureId), menuList)
  202. if _, err = session.Table(new(models.MenuPasture).TableName()).Insert(newMenuPastureList); err != nil {
  203. return err
  204. }
  205. }
  206. NewRoleMenu := models.NewRoleMenu(int64(req.PastureId), newRole.Id, menuList)
  207. if _, err = session.Table(new(models.RoleMenu).TableName()).Insert(NewRoleMenu); err != nil {
  208. return err
  209. }
  210. // 创建用户并绑定管理员权限
  211. newUser := models.NewUser(int64(req.PastureId), req.Account, req.UserName, req.Password, req.Phone, newRole.Id)
  212. if _, err = session.Table(new(models.User).TableName()).Insert(newUser); err != nil {
  213. return err
  214. }
  215. return session.Commit()
  216. }
  217. func CattleCategoryDistribute(req *models.CowClass) error {
  218. has, err := restful.Engine.Table(new(models.CowClass).TableName()).Exist(&models.CowClass{GroupId: req.GroupId})
  219. if err != nil {
  220. return err
  221. }
  222. if has {
  223. if _, err = restful.Engine.Table(new(models.CowClass).TableName()).
  224. Where("group_id = ?", req.GroupId).
  225. Update(map[string]interface{}{
  226. "pastureid": req.PastureId,
  227. "classcode": req.ClassCode,
  228. "classname": req.ClassName,
  229. "enable": req.Enable,
  230. "parentid": req.ParentId,
  231. "parentname": req.ParentName,
  232. }); err != nil {
  233. return err
  234. }
  235. } else {
  236. lastData := &models.CowClass{}
  237. if err = restful.Engine.Table(new(models.CowClass).TableName()).OrderBy("id desc").GetFirst(lastData).Error; err != nil {
  238. req.Id = 1
  239. } else {
  240. req.Id = lastData.Id + 1
  241. }
  242. if _, err = restful.Engine.Table(new(models.CowClass).TableName()).Insert(req); err != nil {
  243. return err
  244. }
  245. }
  246. return nil
  247. }
  248. func ForageCategoryDistribute(req *models.FeedClass) error {
  249. has, err := restful.Engine.Table(new(models.FeedClass).TableName()).Exist(&models.FeedClass{GroupId: req.GroupId})
  250. if err != nil {
  251. return err
  252. }
  253. if has {
  254. if _, err = restful.Engine.Table(new(models.FeedClass).TableName()).
  255. Where("group_id = ?", req.GroupId).
  256. Update(map[string]interface{}{
  257. "pastureid": req.PastureId,
  258. "fccode": req.FCCode,
  259. "fcname": req.FCName,
  260. "enable": req.Enable,
  261. "bigfeedclassid": req.BigFeedClassId,
  262. "bigfeedclassname": req.BigFeedClassName,
  263. }); err != nil {
  264. return err
  265. }
  266. } else {
  267. lastData := &models.FeedClass{}
  268. if err = restful.Engine.Table(new(models.FeedClass).TableName()).OrderBy("id desc").GetFirst(lastData).Error; err != nil {
  269. req.Id = 1
  270. } else {
  271. req.Id = lastData.Id + 1
  272. }
  273. if _, err = restful.Engine.Table(new(models.FeedClass).TableName()).Insert(req); err != nil {
  274. return err
  275. }
  276. }
  277. return nil
  278. }
  279. func ForageCategoryDelete(pastureId, groupId int64) error {
  280. feedClassHas := &models.FeedClass{GroupId: groupId, PastureId: pastureId}
  281. has, err := restful.Engine.Table(new(models.FeedClass).TableName()).Exist(feedClassHas)
  282. if err != nil {
  283. return err
  284. }
  285. if has {
  286. if _, err = restful.Engine.Table(new(models.FeedClass).TableName()).ID(feedClassHas.Id).Delete(feedClassHas); err != nil {
  287. return err
  288. }
  289. }
  290. return nil
  291. }
  292. func CowCategoryDelete(pastureId, groupId int64) error {
  293. cowClassHas := &models.CowClass{GroupId: groupId, PastureId: pastureId}
  294. has, err := restful.Engine.Table(new(models.CowClass).TableName()).Exist(cowClassHas)
  295. if err != nil {
  296. return err
  297. }
  298. if has {
  299. if _, err = restful.Engine.Table(new(models.CowClass).TableName()).ID(cowClassHas.Id).Delete(cowClassHas); err != nil {
  300. return err
  301. }
  302. }
  303. return nil
  304. }
  305. func FeedTemplateList(req *models.FeedListRequest) ([]*models.FeedTemplate, int64, error) {
  306. var (
  307. res []*models.FeedTemplate
  308. total int64
  309. err error
  310. )
  311. newSession := restful.Engine.NewSession()
  312. total, err = newSession.Table(new(models.FeedTemplate).TableName()).
  313. Where("pastureid = ?", req.PastureId).Count(&res)
  314. if err != nil {
  315. return nil, 0, err
  316. }
  317. if err = newSession.Table(new(models.FeedTemplate).TableName()).Limit(int(req.PageSize), int(req.Page-1)*int(req.PageSize)).Find(&res); err != nil {
  318. return nil, 0, err
  319. }
  320. return res, total, nil
  321. }
  322. func FeedList(req *models.FeedListRequest) ([]*models.Feed, int64, error) {
  323. var (
  324. res []*models.Feed
  325. total int64
  326. err error
  327. )
  328. newSession := restful.Engine.NewSession()
  329. total, err = newSession.Table(new(models.Feed).TableName()).
  330. Where("pastureid = ?", req.PastureId).Count(&res)
  331. if err != nil {
  332. return nil, 0, err
  333. }
  334. if err = newSession.Table(new(models.Feed).TableName()).Limit(int(req.PageSize), int(req.Page-1)*int(req.PageSize)).Find(&res); err != nil {
  335. return nil, 0, err
  336. }
  337. return res, total, nil
  338. }
  339. func FeedTemplateDetailList(req *models.FeedListRequest) ([]*models.FeedTemplateDetail, int64, error) {
  340. var (
  341. res []*models.FeedTemplateDetail
  342. total int64
  343. err error
  344. )
  345. newSession := restful.Engine.NewSession()
  346. total, err = newSession.Table(new(models.FeedTemplateDetail).TableName()).
  347. Where("pastureid = ?", req.PastureId).Count(&res)
  348. if err != nil {
  349. return nil, 0, err
  350. }
  351. if err = newSession.Table(new(models.FeedTemplateDetail).TableName()).Limit(int(req.PageSize), int(req.Page-1)*int(req.PageSize)).Find(&res); err != nil {
  352. return nil, 0, err
  353. }
  354. return res, total, nil
  355. }
  356. func FeedTemplateUsageDetail(req *models.FeedFormulaUsageRequest) (*models.FeedFormulaUsageResponse, error) {
  357. mixedDetail, err := getMixedDetail(req.PastureId, req.FeedFormulaId, req.StartTime, req.EndTime)
  358. if err != nil {
  359. return nil, err
  360. }
  361. sprinkleDetail, err := getSprinkleDetail(req.PastureId, req.FeedFormulaId, req.StartTime, req.EndTime)
  362. if err != nil {
  363. return nil, err
  364. }
  365. response := &models.FeedFormulaUsageResponse{
  366. MixedFodderAccurateRatio: strconv.FormatFloat(mixedDetail.MixedFodderAccurateRatio, 'f', 2, 64) + "%",
  367. MixedFodderCorrectRatio: strconv.FormatFloat(mixedDetail.MixedFodderCorrectRatio, 'f', 3, 64) + "%",
  368. SprinkleFodderAccurateRatio: strconv.FormatFloat(sprinkleDetail.SprinkleFodderAccurateRatio, 'f', 3, 64) + "%",
  369. SprinkleFodderCorrectRatio: strconv.FormatFloat(sprinkleDetail.SprinkleFodderCorrectRatio, 'f', 3, 64) + "%",
  370. AddFeedTime: "",
  371. SprinkleTime: "",
  372. StirTime: "",
  373. LastEditTime: "",
  374. }
  375. return response, nil
  376. }
  377. func getMixedDetail(pastureId, feedFormulaId int32, startTime, endTime string) (*models.MixedDetail, error) {
  378. sql := fmt.Sprintf(`SELECT * FROM (
  379. SELECT DATE(de.date) AS plan_time,
  380. IFNULL((SELECT d.templetname FROM downloadedplan d WHERE d.pastureid = de.pastureid AND d.id = de.pid),de.fname) AS feed_formula_name,
  381. IFNULL((SELECT d.tempid FROM downloadedplan d WHERE d.pastureid = de.pastureid AND d.id = de.pid),0) AS feed_formula_id,
  382. ROUND(SUM(de.lweight),2) AS l_weight,ROUND(SUM(de.actualweightminus),2) AS reality_weight,
  383. SUM(1) AS plan_mixed_opts,SUM(de.havebuttom) AS reality_mixed_opts,
  384. ROUND(SUM(de.havebuttom)/SUM(1)*100,2) AS mixed_ops_ratio,
  385. SUM(IF(de.buttontype =1,1,0)) AS mixed_auto_jump_number , SUM(IF(de.buttontype>1,1,0)) AS mixed_manual_jump_number ,
  386. ROUND(ABS(SUM(de.lweight)-SUM(de.actualweightminus)),2) AS mix_error_number,
  387. CONCAT( IF (SUM(de.actualweightminus)>SUM(de.lweight),ROUND((SUM(de.lweight)/SUM(de.actualweightminus)*100),2) ,
  388. SUM(de.actualweightminus)/SUM(de.lweight)*100) ,2) AS mixed_fodder_accurate_ratio,
  389. IF (SUM(de.actualweightminus)>SUM(de.lweight),
  390. ROUND((SUM(de.lweight)/SUM(de.actualweightminus)*100),2) ,
  391. ROUND((SUM(de.actualweightminus)/SUM(de.lweight)*100) ,2)) AS hlzq,
  392. SUM(CASE WHEN (ABS(de.actualweightminus-de.lweight)/de.lweight)>3 AND de.lweight >30 AND de.actualweightminus >30 THEN 1 ELSE 0 END) AS cancel_number,
  393. ROUND(STD(ABS(de.actualweightminus-de.lweight)) ,2) AS variance_ratio,
  394. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) AS mixed_fodder_correct_number,
  395. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) AS mixed_fodder_correct_ratio,
  396. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) hlzql,
  397. TRIM(de.pid) pid,
  398. ROUND(IFNULL(SUM(IF(((ABS(de.actualweightminus-de.lweight)/de.lweight)<=3 OR (de.lweight <30 AND de.actualweightminus <30 )),
  399. IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0),0))/SUM(IF(((ABS(de.actualweightminus-de.lweight)/de.lweight)<=3 OR (de.lweight <30 AND de.actualweightminus <30 )),1,0 )),0)*100,2) AS remove_cancel_correct_ratio
  400. FROM downloadplandtl1 de WHERE de.pastureid= %d AND de.intime IS NOT NULL AND (SELECT d.lpplantype FROM downloadedplan d WHERE d.pastureid = de.pastureid AND d.id = de.pid) IN (0,1,4) AND de.date >= '%s' AND de.date <= '%s'
  401. GROUP BY de.date ) tmp `, pastureId, startTime, endTime)
  402. if feedFormulaId > 0 {
  403. sql = fmt.Sprintf("%s HAVING tmp.feed_formula_id = %d", sql, feedFormulaId)
  404. }
  405. dataList := &models.MixedDetail{}
  406. if _, err := restful.Engine.NewSession().SQL(sql).Get(dataList); err != nil {
  407. return nil, err
  408. }
  409. return dataList, nil
  410. }
  411. func getSprinkleDetail(pastureId, feedFormulaId int32, startTime, endTime string) (*models.SprinkleDetail, error) {
  412. sql := fmt.Sprintf(`SELECT * FROM (SELECT DATE(d.mydate) AS plan_time,
  413. IFNULL((SELECT d.templetname FROM downloadedplan d WHERE d.pastureid = de.pastureid AND d.id = de.pid),de.fname) AS feed_formula_name,
  414. IFNULL((SELECT d.tempid FROM downloadedplan d WHERE d.pastureid = de.pastureid AND d.id = de.pid),0) AS feed_formula_id,
  415. d.tmrtname AS tmr_name,
  416. IFNULL(TIMEDIFF ((SELECT MAX(intime) FROM downloadplandtl2 d2 WHERE d2.pid=de.pid AND d2.pastureid = de.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2 WHERE d2.pid=de.pid AND d2.pastureid = de.pastureid )),'00:00:00') AS mixed_time,
  417. IFNULL(TIMEDIFF ((SELECT MIN(intime) FROM downloadplandtl2 d2 WHERE d2.pid=de.pid AND d2.pastureid = de.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2 WHERE d2.pid=de.pid AND d2.pastureid = de.pastureid )),'00:00:00') AS wait_time,
  418. SUM(de.lweight) AS l_weight,ROUND(SUM(de.actualweightminus)) AS reality_weight,
  419. SUM(1) AS plan_sprinkle_opts,
  420. SUM(de.havebuttom) AS reality_sprinkle_opts,
  421. ROUND(SUM(de.havebuttom)/SUM(1)*100,2) AS sprinkle_ops_ratio,
  422. SUM(IF(de.buttontype =1,1,0)) AS sprinkle_auto_jump_number ,
  423. SUM(IF(de.buttontype>1,1,0)) AS sprinkle_manual_jump_number ,
  424. ABS(SUM(de.actualweightminus)-SUM(de.lweight)) AS sprinkle_error_number,
  425. CONCAT( IF (SUM(de.actualweightminus)>SUM(de.lweight),ROUND((SUM(de.lweight)/SUM(de.actualweightminus)*100),2) ,
  426. SUM(de.actualweightminus)/SUM(de.lweight)*100) ,2) AS sprinkle_fodder_accurate_ratio,
  427. IF (SUM(de.actualweightminus)>SUM(de.lweight),ROUND((SUM(de.lweight)/SUM(de.actualweightminus)*100),2) ,
  428. ROUND((SUM(de.actualweightminus)/SUM(de.lweight)*100) ,2)) slzq,
  429. SUM(CASE WHEN (ABS(de.actualweightminus-de.lweight)/de.lweight)>3 AND de.lweight >30 AND de.actualweightminus >30 THEN 1 ELSE 0 END) AS cancel_number,
  430. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) AS sprinkle_fodder_correct_number,
  431. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) AS sprinkle_fodder_correct_ratio,
  432. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) as slzql,
  433. TRIM(de.pid) pid,
  434. ROUND(IFNULL(SUM(IF(((ABS(de.actualweightminus-de.lweight)/de.lweight)<=3 OR (de.lweight <30 AND de.actualweightminus <30 )),
  435. IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0),0))/SUM(IF(((ABS(de.actualweightminus-de.lweight)/de.lweight)<=3 OR (de.lweight <30 AND de.actualweightminus <30 )),1,0 )),0)*100,2) AS remove_cancel_correct_ratio
  436. FROM downloadplandtl2 de JOIN downloadedplan d ON d.id=de.pid AND d.pastureid = de.pastureid
  437. WHERE d.pastureid = %d AND DATE(d.mydate) BETWEEN '%s' AND '%s' AND d.lpplantype IN (0,2)) tmr `, pastureId, startTime, endTime)
  438. if feedFormulaId > 0 {
  439. sql = fmt.Sprintf("%s HAVING feed_formula_id = %d", sql, feedFormulaId)
  440. }
  441. dataList := &models.SprinkleDetail{}
  442. if _, err := restful.Engine.NewSession().SQL(sql).Get(dataList); err != nil {
  443. return nil, err
  444. }
  445. return dataList, nil
  446. }
  447. func FeedFormulaVersion(pastureId int64, req *models.FeedFormulaUpdateVersionRequest) error {
  448. if req.Belong == 0 {
  449. return nil
  450. }
  451. DbSession := restful.Engine.NewSession()
  452. defer DbSession.Close()
  453. // 开启事务
  454. if err := DbSession.Begin(); err != nil {
  455. return err
  456. }
  457. zaplog.Info("FeedFormulaVersion", zap.Any("req", req), zap.Any("pastureId", pastureId))
  458. feedDetailVersion := &models.FeedDetailVersion{
  459. FeedTemplateId: req.FeedTemplateId,
  460. PastureId: pastureId,
  461. GroupVersion: req.Version,
  462. Belong: req.Belong,
  463. CreatedAt: time.Now().Unix(),
  464. UpdatedAt: time.Now().Unix(),
  465. }
  466. zaplog.Info("FeedFormulaVersion-Insert", zap.Any("feedDetailVersion", feedDetailVersion))
  467. if _, err := DbSession.Insert(feedDetailVersion); err != nil {
  468. DbSession.Rollback()
  469. return err
  470. }
  471. // FeedDetailVersionLog 更新
  472. versionLogs := make([]*models.FeedDetailVersionLog, 0)
  473. for _, v := range req.Data {
  474. versionLogs = append(versionLogs, &models.FeedDetailVersionLog{
  475. VersionId: feedDetailVersion.Id,
  476. PastureId: pastureId,
  477. FeedTemplateId: req.FeedTemplateId,
  478. ForageId: int64(v.ForageId),
  479. ForageName: v.ForageName,
  480. ForageGroupName: v.ForageGroupName,
  481. Weight: int32(v.Weight * 100),
  482. StirDelay: v.StirDelay,
  483. AllowError: v.AllowError,
  484. IsModify: v.IsModify,
  485. IsLockCowCountRatio: operationPb.IsShow_Kind(v.IsLockCowCountRatio),
  486. Sort: v.Sort,
  487. })
  488. }
  489. zaplog.Info("versionLogs-Insert", zap.Any("versionLogs", versionLogs))
  490. if len(versionLogs) > 0 {
  491. if _, err := DbSession.Table(new(models.FeedDetailVersionLog).TableName()).Insert(versionLogs); err != nil {
  492. DbSession.Rollback()
  493. return err
  494. }
  495. }
  496. return DbSession.Commit()
  497. }
  498. func NewSearchFeedTemplateList(ctx context.Context, req *pasturePb.SearchFeedTemplateRequest) ([]*models.FeedTemplate, int64, error) {
  499. DBSession := restful.Engine.NewSession()
  500. defer DBSession.Close()
  501. res := make([]*models.FeedTemplate, 0)
  502. if req.PastureId > 0 {
  503. DBSession.And("pastureid = ?", req.PastureId)
  504. }
  505. if req.Name != "" {
  506. DBSession.And("tname like ?", "%"+req.Name+"%")
  507. }
  508. if req.CattleCategoryId > 0 {
  509. DBSession.And("ccid = ?", req.CattleCategoryId)
  510. }
  511. if req.FormulaTypeId > 0 {
  512. DBSession.And("fttypeid = ?", req.FormulaTypeId)
  513. }
  514. switch req.SourceId {
  515. case 0:
  516. DBSession.And("source = '自定义'")
  517. case 1:
  518. DBSession.And("source = '集团下发未调整'")
  519. case 2:
  520. DBSession.And("source = '集团下发有调整'")
  521. case 3:
  522. DBSession.And("source = '导入'")
  523. }
  524. if req.Enable > 0 {
  525. DBSession.And("enable = ?", req.Enable)
  526. }
  527. if req.Remark != "" {
  528. DBSession.And("remark = ?", req.Remark)
  529. }
  530. if err := DBSession.Desc("id").Find(&res); err != nil {
  531. return nil, 0, err
  532. } else {
  533. return res, int64(len(res)), nil
  534. }
  535. }
  536. func FeedDetailVersionLogList(ctx context.Context) ([]*models.FeedDetailVersion, error) {
  537. res := make([]*models.FeedDetailVersion, 0)
  538. if err := restful.Engine.NewSession().Find(&res); err != nil {
  539. if !errors.Is(err, xorm.ErrNotExist) {
  540. return nil, err
  541. }
  542. }
  543. return res, nil
  544. }
  545. func SearchFeedTemplateById(ctx context.Context, pastureId, id int64) (*models.FeedTemplate, error) {
  546. res := &models.FeedTemplate{Id: id}
  547. if _, err := restful.Engine.Table(new(models.FeedTemplate).TableName()).Where("pastureid = ?", pastureId).Get(res); err != nil {
  548. return nil, err
  549. }
  550. return res, nil
  551. }
  552. // SearchFeedTemplateDetailListByFeedTemplateId 获取配方当前饲料列表详情
  553. func SearchFeedTemplateDetailListByFeedTemplateId(ctx context.Context, pastureId, feedTemplateId int64) ([]*models.FeedTemplateDetail, error) {
  554. res := make([]*models.FeedTemplateDetail, 0)
  555. if err := restful.Engine.Table(new(models.FeedTemplateDetail).TableName()).
  556. Where("pastureid = ?", pastureId).
  557. And("ftid = ?", feedTemplateId).
  558. Find(&res); err != nil {
  559. return nil, err
  560. }
  561. return res, nil
  562. }
  563. // GetFeedDetailVersionByDesc 获取配方最新版本数据
  564. func GetFeedDetailVersionByDesc(ctx context.Context, pastureId, groupDataId int64) (*models.FeedDetailVersion, error) {
  565. res := &models.FeedDetailVersion{}
  566. if _, err := restful.Engine.Table(new(models.FeedDetailVersion).TableName()).
  567. Where("pasture_id = ?", pastureId).
  568. And("feed_template_id = ?", groupDataId).
  569. OrderBy("id desc").Get(res); err != nil {
  570. return nil, err
  571. }
  572. return res, nil
  573. }
  574. // SearchFeedDetailVersionLogById 获取配方关联最新饲料信息
  575. func SearchFeedDetailVersionLogById(ctx context.Context, pastureId, feedTemplateId, versionId int64) ([]*models.FeedDetailVersionLog, error) {
  576. res := make([]*models.FeedDetailVersionLog, 0)
  577. if err := restful.Engine.NewSession().Table(new(models.FeedDetailVersionLog).TableName()).
  578. Where("pasture_id = ?", pastureId).
  579. And("feed_template_id = ?", feedTemplateId).
  580. And("version_id = ?", versionId).
  581. Find(&res); err != nil {
  582. return nil, err
  583. }
  584. return res, nil
  585. }
  586. // FeetTemplateUpgradeNewVersion 配方更新至最新版本
  587. func FeetTemplateUpgradeNewVersion(ctx context.Context, pastureId, feedTemplateId int64) error {
  588. feedTemplateData, err := SearchFeedTemplateById(ctx, pastureId, feedTemplateId)
  589. if err != nil {
  590. return err
  591. }
  592. newFeedDetailVersion, err := GetFeedDetailVersionByDesc(ctx, pastureId, feedTemplateData.GroupDataId)
  593. if err != nil {
  594. return err
  595. }
  596. DBSession := restful.Engine.NewSession()
  597. defer DBSession.Close()
  598. if err = DBSession.Begin(); err != nil {
  599. return err
  600. }
  601. if _, err = DBSession.Table(new(models.FeedTemplateDetail).TableName()).
  602. Where("pastureid = ?", pastureId).
  603. And("ftid = ?", feedTemplateId).
  604. Update(map[string]interface{}{"is_show": operationPb.IsShow_NO}); err != nil {
  605. return err
  606. }
  607. res, err := SearchFeedDetailVersionLogById(ctx, pastureId, newFeedDetailVersion.FeedTemplateId, newFeedDetailVersion.Id)
  608. if err != nil {
  609. return err
  610. }
  611. if len(res) <= 0 {
  612. return DBSession.Commit()
  613. }
  614. newFtDetailList := make([]*models.FeedTemplateDetail, 0)
  615. for _, v := range res {
  616. newFtDetailList = append(newFtDetailList, &models.FeedTemplateDetail{
  617. PastureId: pastureId,
  618. FtId: feedTemplateId,
  619. FId: v.ForageId,
  620. FName: v.ForageName,
  621. FWeight: float64(v.Weight / 100),
  622. IsLockCount: int32(v.IsLockCowCountRatio),
  623. IsFg: 0,
  624. Sort: v.Sort,
  625. FeedGroup: v.ForageGroupName,
  626. PreFtId: 0,
  627. AutoSecond: v.StirDelay,
  628. AutoSecondName: "",
  629. SplitFtPreId: 0,
  630. Deviation: v.AllowError,
  631. IsModify: int32(v.IsModify),
  632. IsShow: int32(operationPb.IsShow_OK),
  633. })
  634. }
  635. if _, err = DBSession.Table(new(models.FeedTemplateDetail).TableName()).Insert(newFtDetailList); err != nil {
  636. return err
  637. }
  638. if _, err = DBSession.Table(new(models.FeedTemplate).TableName()).
  639. Where("pastureid = ?", pastureId).
  640. And("id = ?", feedTemplateId).
  641. Update(map[string]interface{}{"group_version": newFeedDetailVersion.Id}); err != nil {
  642. return err
  643. }
  644. return DBSession.Commit()
  645. }