neck_ring_calculate.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. package crontab
  2. import (
  3. "fmt"
  4. "kpt-pasture/model"
  5. "kpt-pasture/util"
  6. "math"
  7. "strconv"
  8. "time"
  9. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  10. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  11. "gitee.com/xuyiping_admin/pkg/xerr"
  12. "go.uber.org/zap"
  13. )
  14. func (e *Entry) NeckRingCalculate() error {
  15. pastureList := e.FindPastureList()
  16. if pastureList == nil || len(pastureList) == 0 {
  17. return nil
  18. }
  19. for _, pasture := range pastureList {
  20. if err := e.EntryUpdateActiveHabit(pasture); err != nil {
  21. zaplog.Error("NeckRingCalculate", zap.Any("err", err), zap.Any("pasture", pasture))
  22. }
  23. zaplog.Info(fmt.Sprintf("NeckRingCalculate Success %d", pasture.Id))
  24. }
  25. return nil
  26. }
  27. func (e *Entry) EntryUpdateActiveHabit(appPasture *model.AppPastureList) (err error) {
  28. pastureId := appPasture.Id
  29. // 获取这段执行数据内最大日期和最小日期
  30. xToday, err := e.XToday(pastureId)
  31. if err != nil {
  32. return xerr.WithStack(err)
  33. }
  34. // 未配置的滤波数据不参与计算
  35. if xToday == nil {
  36. return nil
  37. }
  38. var processIds []int64
  39. // 更新活动滤波
  40. processIds, err = e.FirstFilterUpdate(pastureId, xToday)
  41. if err != nil {
  42. zaplog.Error("NeckRingCalculate", zap.Any("pastureId", pastureId), zap.Any("FirstFilterUpdate", err), zap.Any("xToday", xToday))
  43. }
  44. if len(processIds) <= 0 {
  45. return nil
  46. }
  47. e.WeeklyUpdateActiveHabit(pastureId, processIds, xToday)
  48. // 二次更新滤波
  49. e.SecondUpdateChangeFilter(pastureId, processIds, xToday)
  50. // 活动量校正系数和健康评分
  51. e.FilterCorrectAndScoreUpdate(appPasture, processIds, xToday)
  52. // 更新 ChangeFilter
  53. e.UpdateChangeFilter(pastureId, processIds)
  54. // 更新 FilterCorrect
  55. e.UpdateFilterCorrect(pastureId, processIds)
  56. // 插入群体校正表
  57. e.UpdateChangeAdJust(pastureId, processIds)
  58. // 更新 Cft
  59. e.UpdateCft(pastureId, processIds)
  60. // 更新所有的显示状态为否的记录为是
  61. e.UpdateIsShow(pastureId, processIds)
  62. // 健康预警
  63. e.HealthWarning(pastureId, processIds)
  64. return nil
  65. }
  66. // FirstFilterUpdate 首次更新活动滤波
  67. func (e *Entry) FirstFilterUpdate(pastureId int64, xToDay *XToday) (processIds []int64, err error) {
  68. limit := e.Cfg.NeckRingLimit
  69. if limit <= 0 {
  70. limit = defaultLimit
  71. }
  72. firstHeatDate := time.Now().Local().AddDate(0, 0, int(xToDay.BeforeDayNeckRing)*-1).Format(model.LayoutDate2)
  73. querySql := `SELECT * FROM neck_active_habit WHERE pasture_id = ? AND is_show = ? AND heat_date >= ? AND high >= ?
  74. UNION
  75. SELECT * FROM neck_active_habit WHERE pasture_id = ? AND is_show = ? AND heat_date >= ? AND rumina >= ?
  76. ORDER BY active_time,neck_ring_number,frameid LIMIT ?`
  77. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  78. if err = e.DB.Raw(
  79. querySql,
  80. pastureId, pasturePb.IsShow_No, firstHeatDate, xToDay.High,
  81. pastureId, pasturePb.IsShow_No, firstHeatDate, xToDay.Rumina,
  82. limit,
  83. ).Find(&newNeckActiveHabitList).Error; err != nil {
  84. return nil, xerr.WithStack(err)
  85. }
  86. // 活动量滤波
  87. for _, v := range newNeckActiveHabitList {
  88. // 4小时数据不全的不参与滤波
  89. activeTime, _ := util.TimeParseLocal(model.LayoutTime, v.ActiveTime)
  90. if v.RecordCount != model.DefaultRecordCount && time.Now().Local().Sub(activeTime).Hours() <= 4 {
  91. continue
  92. }
  93. // 过滤牛只未绑定的脖环的数据
  94. cowInfo := e.GetCowInfoByNeckRingNumber(v.PastureId, v.NeckRingNumber)
  95. if cowInfo == nil || cowInfo.Id <= 0 {
  96. v.UpdateIsShowOk()
  97. if err = e.DB.Model(new(model.NeckActiveHabit)).
  98. Select("is_show").
  99. Where("id = ?", v.Id).
  100. Updates(v).Error; err != nil {
  101. zaplog.Error("EntryUpdateActiveHabit", zap.Any("error", err))
  102. }
  103. continue
  104. }
  105. frameId := v.Frameid
  106. heatDate := v.HeatDate
  107. if v.Frameid == 0 {
  108. frameId = 11
  109. heatDateParse, _ := util.TimeParseLocal(model.LayoutDate2, heatDate)
  110. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  111. } else {
  112. frameId -= 1
  113. }
  114. firstFilterData := e.FindFilterData(pastureId, v.NeckRingNumber, heatDate, frameId)
  115. if v.FilterHigh > 0 {
  116. firstFilterData.FilterHigh = v.FilterHigh
  117. } else {
  118. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  119. firstFilterData.FilterHigh = int32(computeIfPositiveElse(float64(v.High), float64(firstFilterData.FilterHigh), 0.23, 0.77))
  120. } else {
  121. firstFilterData.FilterHigh = v.High
  122. }
  123. }
  124. if v.FilterRumina > 0 {
  125. firstFilterData.FilterRumina = v.FilterRumina
  126. } else {
  127. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  128. firstFilterData.FilterRumina = int32(computeIfPositiveElse(float64(v.Rumina), float64(firstFilterData.FilterRumina), 0.33, 0.67))
  129. } else {
  130. firstFilterData.FilterRumina = v.Rumina
  131. }
  132. }
  133. if v.FilterChew > 0 {
  134. firstFilterData.FilterChew = v.FilterChew
  135. } else {
  136. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  137. firstFilterData.FilterChew = int32(computeIfPositiveElse(float64(v.Rumina+v.Intake), float64(firstFilterData.FilterChew), 0.33, 0.67))
  138. } else {
  139. firstFilterData.FilterChew = v.Rumina + v.Intake
  140. }
  141. }
  142. cowWeeklyActive := cowInfo.WeeklyActive
  143. if cowWeeklyActive <= 0 {
  144. cowWeeklyActive = v.WeekHigh
  145. }
  146. processIds = append(processIds, v.Id)
  147. // 更新过滤值
  148. if err = e.DB.Model(new(model.NeckActiveHabit)).
  149. Select("filter_high", "filter_rumina", "filter_chew", "cow_id", "lact", "calving_age", "ear_number", "pen_id", "week_high").
  150. Where("id = ?", v.Id).
  151. Updates(map[string]interface{}{
  152. "filter_high": firstFilterData.FilterHigh,
  153. "filter_rumina": firstFilterData.FilterRumina,
  154. "filter_chew": firstFilterData.FilterChew,
  155. "cow_id": cowInfo.Id,
  156. "lact": cowInfo.Lact,
  157. "calving_age": cowInfo.CalvingAge,
  158. "ear_number": cowInfo.EarNumber,
  159. "pen_id": cowInfo.PenId,
  160. "week_high": cowWeeklyActive,
  161. }).Error; err != nil {
  162. zaplog.Error("FirstFilterUpdate",
  163. zap.Any("error", err),
  164. zap.Any("firstFilterData", firstFilterData),
  165. zap.Any("NeckActiveHabit", v),
  166. zap.Any("cowInfo", cowInfo),
  167. zap.Any("xToday", xToDay),
  168. )
  169. }
  170. }
  171. return processIds, nil
  172. }
  173. // SecondUpdateChangeFilter 第二次更新变化趋势滤波
  174. func (e *Entry) SecondUpdateChangeFilter(pastureId int64, processIds []int64, xToday *XToday) {
  175. newChangeFilterList := make([]*ChangeFilterData, 0)
  176. if err := e.DB.Model(new(model.NeckActiveHabit)).
  177. Select("id", "neck_ring_number", "change_high", "change_filter", "rumina_filter", "change_rumina",
  178. "chew_filter", "change_chew", "heat_date", "frameid", "IF(lact = 0, 0.8, 1) as xlc_dis_count").
  179. Where("pasture_id = ?", pastureId).
  180. Where("id IN (?)", processIds).
  181. Where("change_filter = ?", model.InitChangeFilter).
  182. Where("change_high > ?", MinChangeHigh).
  183. Order("neck_ring_number,heat_date,frameid").
  184. Find(&newChangeFilterList).Error; err != nil {
  185. zaplog.Error("SecondUpdateChangeFilter", zap.Any("error", err))
  186. return
  187. }
  188. for _, v := range newChangeFilterList {
  189. frameId := v.Frameid
  190. heatDate := v.HeatDate
  191. if v.Frameid == 0 {
  192. frameId = 11
  193. heatDateParse, _ := util.TimeParseLocal(model.LayoutDate2, heatDate)
  194. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  195. } else {
  196. frameId -= 1
  197. }
  198. xChangeDiscount := float64(xToday.XChangeDiscount) / 10
  199. xRuminaDisc := float64(xToday.XRuminaDisc) / 10
  200. secondFilterData := e.FindFilterData(pastureId, v.NeckRingNumber, heatDate, frameId)
  201. if secondFilterData.ChangeFilter <= MinChangeFilter {
  202. secondFilterData.ChangeFilter = 0
  203. }
  204. if secondFilterData.RuminaFilter <= MinRuminaFilter {
  205. secondFilterData.RuminaFilter = 0
  206. }
  207. if secondFilterData.ChewFilter <= MinChewFilter {
  208. secondFilterData.ChewFilter = 0
  209. }
  210. changeFilter := float64(v.ChangeFilter)
  211. if v.ChangeFilter <= MinChangeFilter {
  212. changeFilter = float64(secondFilterData.ChangeFilter)*(1-xChangeDiscount*v.XlcDisCount) +
  213. math.Min(float64(v.ChangeHigh), float64(secondFilterData.ChangeFilter)+135)*xChangeDiscount*v.XlcDisCount
  214. }
  215. ruminaFilter := float64(v.RuminaFilter)
  216. discount := xRuminaDisc * v.XlcDisCount
  217. if math.Abs(float64(v.ChangeRumina)) > 60 {
  218. discount *= 0.5
  219. }
  220. ruminaFilter = float64(secondFilterData.RuminaFilter)*(1-discount) + float64(v.ChangeRumina)*discount
  221. if ruminaFilter > 50 {
  222. ruminaFilter = 50
  223. }
  224. chewFilter := float64(v.ChewFilter)
  225. chewFilterDiscount := float64(1)
  226. if math.Abs(float64(v.ChangeChew)) > 60 {
  227. chewFilterDiscount = 0.5
  228. }
  229. chewFilter = float64(secondFilterData.ChewFilter)*(1-xRuminaDisc*chewFilterDiscount) +
  230. float64(v.ChangeChew)*xRuminaDisc*chewFilterDiscount
  231. if chewFilter > 50 {
  232. chewFilter = 50
  233. }
  234. if err := e.DB.Model(new(model.NeckActiveHabit)).
  235. Select("change_filter", "rumina_filter", "chew_filter").
  236. Where("id = ?", v.Id).
  237. Updates(map[string]interface{}{
  238. "change_filter": int32(changeFilter),
  239. "rumina_filter": int32(ruminaFilter),
  240. "chew_filter": int32(chewFilter),
  241. }).Error; err != nil {
  242. zaplog.Error("SecondUpdateChangeFilter", zap.Any("error", err), zap.Any("secondFilterData", secondFilterData))
  243. }
  244. }
  245. }
  246. // FilterCorrectAndScoreUpdate 计算活动量变化趋势校正值(活跃度校正)和健康评分
  247. func (e *Entry) FilterCorrectAndScoreUpdate(appPasture *model.AppPastureList, processIds []int64, xToday *XToday) {
  248. beginDayDate := time.Now().Local()
  249. before7DayDate := beginDayDate.AddDate(0, 0, -7).Format(model.LayoutDate2)
  250. before1DayDate := beginDayDate.AddDate(0, 0, -1).Format(model.LayoutDate2)
  251. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  252. if err := e.DB.Model(new(model.NeckActiveHabit)).
  253. Where("id IN (?)", processIds).
  254. Where("pasture_id = ?", appPasture.Id).
  255. Find(&neckActiveHabitList).Error; err != nil {
  256. zaplog.Error("ActivityVolumeChanges-1", zap.Any("error", err), zap.Any("xToday", xToday))
  257. return
  258. }
  259. for _, v := range neckActiveHabitList {
  260. cowScore := CalculateScore(appPasture, v)
  261. if err := e.DB.Model(new(model.NeckActiveHabit)).
  262. Where("id = ?", v.Id).
  263. Update("score", cowScore).Error; err != nil {
  264. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  265. }
  266. activityVolume := &ActivityVolume{}
  267. if err := e.DB.Model(new(model.NeckActiveHabit)).
  268. Select("neck_ring_number", "AVG(IF(change_filter>=60, 60, change_filter)) as avg_filter",
  269. "ROUND(STD(IF(change_filter>=60, 60, change_filter))) as std_filter", "COUNT(1) as nb").
  270. Where("heat_date BETWEEN ? AND ?", before7DayDate, before1DayDate).
  271. Where("pasture_id = ?", appPasture.Id).
  272. Where(e.DB.Where("high > ?", 12).Or("rumina >= ?", xToday.Rumina)).
  273. Where("active_time <= ?", beginDayDate.Add(-12*time.Hour).Format(model.LayoutTime)).
  274. Where("change_filter > ?", MinChangeFilter).
  275. Where("neck_ring_number = ?", v.NeckRingNumber).
  276. Having("nb >= ?", DefaultNb).
  277. First(&activityVolume).Error; err != nil {
  278. zaplog.Error("ActivityVolumeChanges-0", zap.Any("error", err), zap.Any("xToday", xToday), zap.Any("v", v))
  279. continue
  280. }
  281. if activityVolume != nil && activityVolume.NeckRingNumber != "" {
  282. filterCorrect := model.DefaultFilterCorrect - int(math.Round(activityVolume.AvgFilter/3+float64(int(math.Round(activityVolume.StdFilter))/2)))
  283. // 活动量校正系数
  284. if err := e.DB.Model(new(model.NeckActiveHabit)).
  285. Where("id = ?", v.Id).
  286. Update("filter_correct", filterCorrect).Error; err != nil {
  287. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  288. continue
  289. }
  290. }
  291. }
  292. }
  293. func (e *Entry) UpdateChangeFilter(pastureId int64, processIds []int64) {
  294. if err := e.DB.Model(new(model.NeckActiveHabit)).
  295. Where("id IN (?)", processIds).
  296. Where("pasture_id = ?", pastureId).
  297. Where("is_show = ?", pasturePb.IsShow_No).
  298. Where("change_filter = ?", model.InitChangeFilter).
  299. Updates(map[string]interface{}{
  300. "change_filter": model.DefaultChangeFilter,
  301. "rumina_filter": model.DefaultRuminaFilter,
  302. "chew_filter": model.DefaultChewFilter,
  303. }).Error; err != nil {
  304. zaplog.Error("UpdateChangeFilter", zap.Any("change_filter", err))
  305. }
  306. }
  307. func (e *Entry) UpdateFilterCorrect(pastureId int64, processIds []int64) {
  308. if err := e.DB.Model(new(model.NeckActiveHabit)).
  309. Where("id IN (?)", processIds).
  310. Where("pasture_id = ?", pastureId).
  311. Where("change_filter < ?", 0).
  312. Where("filter_correct < ?", model.DefaultFilterCorrect).
  313. Updates(map[string]interface{}{
  314. "filter_correct": model.DefaultFilterCorrect,
  315. }).Error; err != nil {
  316. zaplog.Error("UpdateFilterCorrect", zap.Any("filter_correct", err))
  317. }
  318. }
  319. // UpdateChangeAdJust 更新群体校正数据
  320. func (e *Entry) UpdateChangeAdJust(pastureId int64, processIds []int64) {
  321. neckRingPenChangeList := make([]*model.NeckRingPenChange, 0)
  322. yesterday := time.Now().Local().AddDate(0, 0, -1).Format(model.LayoutDate2)
  323. if err := e.DB.Model(new(model.NeckActiveHabit)).
  324. Select(`heat_date,frameid,pen_id,COUNT(*) AS cow_count,ROUND(AVG(change_high)) AS change_high,ROUND(AVG(change_filter)) AS change_filter`).
  325. Where("pasture_id = ?", pastureId).
  326. Where("heat_date >= ?", yesterday).
  327. Where("cow_id > ?", 0).
  328. Where("pen_id > ?", 0).
  329. Group("heat_date,frameid,pen_id").
  330. Order("heat_date,frameid,pen_id").
  331. Find(&neckRingPenChangeList).Error; err != nil {
  332. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("pastureId", pastureId))
  333. }
  334. for _, v := range neckRingPenChangeList {
  335. var count int64
  336. if err := e.DB.Model(new(model.NeckRingPenChange)).
  337. Where("pasture_id = ?", pastureId).
  338. Where("heat_date = ?", v.HeatDate).
  339. Where("frameid = ?", v.Frameid).
  340. Where("pen_id = ?", v.PenId).
  341. Count(&count).Error; err != nil {
  342. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("v", v), zap.Any("pastureId", pastureId))
  343. }
  344. // 有就更新,没有就新增
  345. if count > 0 {
  346. if err := e.DB.Model(new(model.NeckRingPenChange)).
  347. Where("pasture_id = ?", pastureId).
  348. Where("heat_date = ?", v.HeatDate).
  349. Where("frameid = ?", v.Frameid).
  350. Where("pen_id = ?", v.PenId).
  351. Updates(map[string]interface{}{
  352. "cow_count": v.CowCount,
  353. "change_high": v.ChangeHigh,
  354. "change_filter": v.ChangeFilter,
  355. }).Error; err != nil {
  356. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("v", v), zap.Any("pastureId", pastureId))
  357. }
  358. } else {
  359. neckRingPenChange := model.NewNeckRingPenChange(pastureId, v.HeatDate, v.CowCount, v.Frameid, v.PenId, v.ChangeHigh, v.ChangeFilter)
  360. if err := e.DB.Model(new(model.NeckRingPenChange)).
  361. Create(neckRingPenChange).Error; err != nil {
  362. zaplog.Error("UpdateChangeAdJust",
  363. zap.Any("error", err),
  364. zap.Any("neckRingPenChange", neckRingPenChange),
  365. zap.Any("pastureId", pastureId),
  366. )
  367. }
  368. }
  369. }
  370. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  371. if err := e.DB.Model(new(model.NeckActiveHabit)).
  372. Where("id IN (?)", processIds).
  373. Where("pasture_id = ?", pastureId).
  374. Find(&neckActiveHabitList).Error; err != nil {
  375. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err))
  376. }
  377. if len(neckActiveHabitList) <= 0 {
  378. return
  379. }
  380. for _, v := range neckActiveHabitList {
  381. neckRingPenChange := &model.NeckRingPenChange{}
  382. if err := e.DB.Model(new(model.NeckRingPenChange)).
  383. Where("pasture_id = ?", pastureId).
  384. Where("heat_date = ?", v.HeatDate).
  385. Where("frameid = ?", v.Frameid).
  386. Where("pen_id = ?", v.PenId).
  387. First(&neckRingPenChange).Error; err != nil {
  388. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("v", v), zap.Any("pastureId", pastureId))
  389. continue
  390. }
  391. if neckRingPenChange == nil || neckRingPenChange.Id <= 0 {
  392. continue
  393. }
  394. if neckRingPenChange.ChangeFilter < 10 {
  395. continue
  396. }
  397. if err := e.DB.Model(new(model.NeckActiveHabit)).
  398. Where("id = ?", v.Id).
  399. Update("change_adjust", neckRingPenChange.ChangeFilter).Error; err != nil {
  400. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("v", v), zap.Any("neckRingPenChange", neckRingPenChange))
  401. }
  402. }
  403. }
  404. // UpdateCft 更新群体校正修正
  405. func (e *Entry) UpdateCft(pastureId int64, processIds []int64) {
  406. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  407. if err := e.DB.Model(new(model.NeckActiveHabit)).
  408. Where("id IN (?)", processIds).
  409. Where("pasture_id = ?", pastureId).
  410. Where("is_show = ?", pasturePb.IsShow_No).
  411. Find(&neckActiveHabitList).Error; err != nil {
  412. zaplog.Error("UpdateCft-1", zap.Any("error", err))
  413. }
  414. for _, v := range neckActiveHabitList {
  415. cft := CalculateCFT(v)
  416. if err := e.DB.Model(new(model.NeckActiveHabit)).
  417. Where("id = ?", v.Id).
  418. Where("neck_ring_number = ?", v.NeckRingNumber).
  419. Update("cft", strconv.FormatFloat(float64(cft), 'f', 2, 64)).Error; err != nil {
  420. zaplog.Error("UpdateCft-2", zap.Any("error", err))
  421. }
  422. }
  423. }
  424. func (e *Entry) UpdateIsShow(pastureId int64, processIds []int64) {
  425. if err := e.DB.Model(new(model.NeckActiveHabit)).
  426. Where("id IN (?)", processIds).
  427. Where("pasture_id = ?", pastureId).
  428. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  429. zaplog.Error("UpdateChangeAdJust-2", zap.Any("error", err))
  430. }
  431. }
  432. func (e *Entry) XToday(pastureId int64) (*XToday, error) {
  433. xToday := &XToday{}
  434. systemConfigureList, err := e.FindSystemNeckRingConfigure(pastureId)
  435. if err != nil {
  436. return nil, xerr.WithStack(err)
  437. }
  438. if len(systemConfigureList) <= 0 {
  439. return nil, nil
  440. }
  441. for _, v := range systemConfigureList {
  442. switch v.Name {
  443. case model.MaxHabit:
  444. xToday.LastMaxHabitId = v.Value
  445. case model.High:
  446. xToday.High = int32(v.Value)
  447. case model.Rumina:
  448. xToday.Rumina = int32(v.Value)
  449. case model.XRuminaDisc:
  450. xToday.XRuminaDisc = int32(v.Value)
  451. case model.XChangeDiscount:
  452. xToday.XChangeDiscount = int32(v.Value)
  453. case model.WeeklyActive:
  454. xToday.WeeklyActive = int32(v.Value)
  455. case model.BeforeDayNeckRing:
  456. xToday.BeforeDayNeckRing = int32(v.Value)
  457. }
  458. }
  459. return xToday, nil
  460. }
  461. // WeeklyUpdateActiveHabit 时间点周平均值计算
  462. func (e *Entry) WeeklyUpdateActiveHabit(pastureId int64, processIds []int64, xToDay *XToday) {
  463. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  464. if err := e.DB.Model(new(model.NeckActiveHabit)).
  465. Where("id IN (?)", processIds).
  466. Order("heat_date,neck_ring_number,frameid").
  467. Find(&newNeckActiveHabitList).Error; err != nil {
  468. zaplog.Error("WeeklyUpdateActiveHabit", zap.Any("error", err), zap.Any("processIds", processIds))
  469. }
  470. if len(newNeckActiveHabitList) <= 0 {
  471. return
  472. }
  473. e.HabitUpdateActiveHabit(pastureId, newNeckActiveHabitList, xToDay)
  474. e.SumUpdateActiveHabit(pastureId, newNeckActiveHabitList, xToDay)
  475. e.ActiveChange(pastureId, processIds, xToDay)
  476. e.Before3DaysNeckActiveHabit(pastureId, processIds)
  477. }
  478. func (e *Entry) HabitUpdateActiveHabit(pastureId int64, newNeckActiveHabitList []*model.NeckActiveHabit, xToDay *XToday) {
  479. for _, v := range newNeckActiveHabitList {
  480. // 前七天的
  481. weekHabitData := e.FindWeekHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  482. // 更新过滤值
  483. if err := e.DB.Model(new(model.NeckActiveHabit)).
  484. Select("high_habit", "rumina_habit", "chew_habit", "intake_habit", "inactive_habit").
  485. Where("id = ?", v.Id).
  486. Updates(map[string]interface{}{
  487. "high_habit": weekHabitData.HighHabit,
  488. "rumina_habit": weekHabitData.RuminaHabit,
  489. "chew_habit": weekHabitData.ChewHabit,
  490. "intake_habit": weekHabitData.IntakeHabit,
  491. "inactive_habit": weekHabitData.InactiveHabit,
  492. }).Error; err != nil {
  493. zaplog.Error("WeeklyUpdateActiveHabit",
  494. zap.Error(err),
  495. zap.Any("NeckActiveHabit", v),
  496. zap.Any("pastureId", pastureId),
  497. )
  498. }
  499. }
  500. }
  501. // SumUpdateActiveHabit -- 累计24小时数值
  502. func (e *Entry) SumUpdateActiveHabit(pastureId int64, newNeckActiveHabitList []*model.NeckActiveHabit, xToDay *XToday) {
  503. for _, v := range newNeckActiveHabitList {
  504. sumHabitData := e.FindSumHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  505. // 更新过滤值
  506. if err := e.DB.Model(new(model.NeckActiveHabit)).
  507. Select("sum_rumina", "sum_intake", "sum_inactive", "sum_active", "sum_max_high", "sum_min_high", "sum_min_chew").
  508. Where("id = ?", v.Id).
  509. Updates(map[string]interface{}{
  510. "sum_rumina": sumHabitData.SumRumina,
  511. "sum_intake": sumHabitData.SumIntake,
  512. "sum_inactive": sumHabitData.SumInactive,
  513. "sum_active": sumHabitData.SumActive,
  514. "sum_max_high": sumHabitData.SumMaxHigh,
  515. "sum_min_high": sumHabitData.SumMinHigh,
  516. "sum_min_chew": sumHabitData.SumMinChew,
  517. }).Error; err != nil {
  518. zaplog.Error("WeeklyUpdateActiveHabit",
  519. zap.Any("err", err),
  520. zap.Any("NeckActiveHabit", v),
  521. zap.Any("pastureId", pastureId),
  522. )
  523. }
  524. }
  525. }
  526. // ActiveChange -- 变化百分比
  527. func (e *Entry) ActiveChange(pastureId int64, processIds []int64, xToDay *XToday) {
  528. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  529. if err := e.DB.Model(new(model.NeckActiveHabit)).
  530. Where("pasture_id = ?", pastureId).
  531. Where("id IN (?)", processIds).
  532. Where("high_habit > ?", 0).
  533. Where(e.DB.Where("high >= ?", xToDay.High).Or("rumina >= ?", xToDay.Rumina)).
  534. Find(&newNeckActiveHabitList).Error; err != nil {
  535. zaplog.Error("ActiveChange", zap.Any("error", err), zap.Any("processIds", processIds))
  536. }
  537. for _, v := range newNeckActiveHabitList {
  538. changeHigh := calculateChangeHigh(v, xToDay.WeeklyActive)
  539. changeRumina := int32(0)
  540. changeChew := int32(0)
  541. if v.RuminaHabit != 0 {
  542. changeRumina = int32(math.Round(float64(v.FilterRumina-v.RuminaHabit) / float64(v.RuminaHabit) * 100))
  543. }
  544. if v.ChewHabit != 0 {
  545. changeChew = int32(math.Round(float64(v.FilterChew-v.ChewHabit) / float64(v.ChewHabit) * 100))
  546. }
  547. // 更新过滤值
  548. if err := e.DB.Model(new(model.NeckActiveHabit)).
  549. Select("change_high", "change_rumina", "change_chew").
  550. Where("id = ?", v.Id).
  551. Updates(map[string]interface{}{
  552. "change_high": changeHigh,
  553. "change_rumina": changeRumina,
  554. "change_chew": changeChew,
  555. }).Error; err != nil {
  556. zaplog.Error("ActiveChange",
  557. zap.Any("err", err),
  558. zap.Any("NeckActiveHabit", v),
  559. )
  560. }
  561. }
  562. }
  563. func (e *Entry) Before3DaysNeckActiveHabit(pastureId int64, processIds []int64) {
  564. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  565. if err := e.DB.Model(new(model.NeckActiveHabit)).
  566. Where("id IN (?)", processIds).
  567. Order("heat_date,neck_ring_number,frameid").
  568. Find(&newNeckActiveHabitList).Error; err != nil {
  569. zaplog.Error("Before3DaysNeckActiveHabit", zap.Any("error", err), zap.Any("processIds", processIds))
  570. }
  571. for _, v := range newNeckActiveHabitList {
  572. before3DaysNeckActiveHabit := e.FindBefore3DaysNeckActiveHabit(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid)
  573. if before3DaysNeckActiveHabit.SumRumina == 0 && before3DaysNeckActiveHabit.SumIntake == 0 {
  574. continue
  575. }
  576. // 更新过滤值
  577. if err := e.DB.Model(new(model.NeckActiveHabit)).
  578. Select("before_three_sum_rumina", "before_three_sum_intake").
  579. Where("id = ?", v.Id).
  580. Updates(map[string]interface{}{
  581. "before_three_sum_rumina": before3DaysNeckActiveHabit.SumRumina,
  582. "before_three_sum_intake": before3DaysNeckActiveHabit.SumIntake,
  583. }).Error; err != nil {
  584. zaplog.Error("Before3DaysNeckActiveHabit",
  585. zap.Error(err),
  586. zap.Any("NeckActiveHabit", v),
  587. zap.Any("pastureId", pastureId),
  588. )
  589. }
  590. }
  591. }
  592. // calculateChangeHigh 计算活动量变化
  593. func calculateChangeHigh(data *model.NeckActiveHabit, weeklyActive int32) int32 {
  594. highDiff := data.FilterHigh - data.HighHabit
  595. changeHigh := int32(0)
  596. if highDiff > 0 {
  597. denominator := float64(data.WeekHigh)*0.6 + float64(data.HighHabit)*0.2 + float64(weeklyActive)*0.2
  598. changeHigh = int32(math.Round((float64(highDiff) / denominator) * 100))
  599. } else {
  600. changeHigh = int32(math.Round(float64(highDiff) / float64(data.HighHabit) * 100))
  601. }
  602. return changeHigh
  603. }