cow_cron.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. package crontab
  2. import (
  3. "context"
  4. "fmt"
  5. "kpt-pasture/model"
  6. "kpt-pasture/module/backend"
  7. "kpt-pasture/util"
  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. const (
  15. UpdateCowInfo = "UpdateCowInfo"
  16. ImmunizationPlan = "ImmunizationPlan"
  17. SameTimePlan = "SameTimePlan"
  18. WorkOrderMaster = "WorkOrderMaster"
  19. SystemBasicCrontab = "SystemBasicCrontab"
  20. NeckRingOriginal = "NeckRingOriginal"
  21. )
  22. // GenerateAsynqWorkOrder 异步生成工作单
  23. func (e *Entry) GenerateAsynqWorkOrder() error {
  24. if ok := e.IsExistCrontabLog(WorkOrderMaster); ok {
  25. return nil
  26. }
  27. defer func() {
  28. e.CreateCrontabLog(WorkOrderMaster)
  29. }()
  30. workOrderList := make([]*model.WorkOrderMaster, 0)
  31. if err := e.DB.Where("is_show = ?", pasturePb.IsShow_Ok).Find(&workOrderList).Error; err != nil {
  32. return err
  33. }
  34. for _, workOrder := range workOrderList {
  35. timeUnix, err := util.ConvertParseLocalUnix(workOrder.ExecTime)
  36. if timeUnix <= 0 || err != nil {
  37. zaplog.Error("crontab", zap.Any("GenerateWorkOrder", err), zap.Any("execTime", workOrder.ExecTime))
  38. continue
  39. }
  40. nowTime := time.Now().Unix()
  41. if timeUnix < nowTime {
  42. continue
  43. }
  44. execTime := timeUnix - nowTime
  45. task := model.NewTaskWorkOrderPayload(workOrder.Id, time.Duration(execTime)*time.Second)
  46. if _, err = e.AsynqClient.CtxEnqueue(context.Background(), task); err != nil {
  47. zaplog.Error("PushMessage CtxEnqueue", zap.Any("Err", err))
  48. }
  49. }
  50. return nil
  51. }
  52. // Indicators 月度指标维护
  53. func (e *Entry) Indicators() error {
  54. indicatorsDetailsList := make([]*model.IndicatorsDetails, 0)
  55. if err := e.DB.Model(new(model.IndicatorsDetails)).
  56. Find(&indicatorsDetailsList).Error; err != nil {
  57. return err
  58. }
  59. pastureList := e.FindPastureList()
  60. startTime, endTime := util.GetMonthStartAndEndTimestamp()
  61. zaplog.Info("Indicators", zap.Any("startTime", startTime), zap.Any("indicatorsDetailsList", indicatorsDetailsList))
  62. for _, indicatorsDetail := range indicatorsDetailsList {
  63. pastureIndicatorList := map[int64]string{}
  64. switch indicatorsDetail.Kind {
  65. case "all_cow":
  66. pastureIndicatorList = e.FindPastureAllCow(pastureList)
  67. case "calving_interval":
  68. pastureIndicatorList = e.FindCalvingInterval(pastureList, startTime, endTime)
  69. case "output_number":
  70. pastureIndicatorList = e.FindOutputNumber(pastureList, startTime, endTime)
  71. case "input_number":
  72. pastureIndicatorList = e.FindInputNumber(pastureList, startTime, endTime)
  73. case "sales_volume":
  74. pastureIndicatorList = e.FindSalesVolume(pastureList, startTime, endTime)
  75. case "calving_number":
  76. pastureIndicatorList = e.FindCalvingNumber(pastureList, startTime, endTime)
  77. case "adult_abortion_rate":
  78. pastureIndicatorList = e.FindAdultAbortionRate(pastureList, "adult", startTime, endTime)
  79. case "youth_abortion_rate":
  80. pastureIndicatorList = e.FindAdultAbortionRate(pastureList, "youth", startTime, endTime)
  81. case "all_die_number":
  82. pastureIndicatorList = e.FindDepartureNumber(pastureList, pasturePb.DepartureType_Death, startTime, endTime)
  83. case "disease_number":
  84. pastureIndicatorList = e.FindDiseaseNumber(pastureList, startTime, endTime)
  85. case "cure_number":
  86. pastureIndicatorList = e.FindCureNumber(pastureList, startTime, endTime)
  87. case "out_number":
  88. pastureIndicatorList = e.FindDepartureNumber(pastureList, pasturePb.DepartureType_Out, startTime, endTime)
  89. case "calf_die_number":
  90. pastureIndicatorList = e.FindCalfDieNumber(pastureList, pasturePb.DepartureType_Death, startTime, endTime)
  91. }
  92. for pastureId, value := range pastureIndicatorList {
  93. e.UpdatePastureIndicators(pastureId, indicatorsDetail, startTime, value)
  94. }
  95. }
  96. return nil
  97. }
  98. // UpdateCowInfo 牛只基本信息维护
  99. func (e *Entry) UpdateCowInfo() error {
  100. cowList := make([]*model.Cow, 0)
  101. if err := e.DB.Model(new(model.Cow)).
  102. Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
  103. Find(&cowList).Error; err != nil {
  104. return err
  105. }
  106. if ok := e.IsExistCrontabLog(UpdateCowInfo); ok {
  107. return nil
  108. }
  109. defer func() {
  110. e.CreateCrontabLog(UpdateCowInfo)
  111. }()
  112. for _, cow := range cowList {
  113. weeklyActive := e.UpdateCowWeeklyHigh(cow)
  114. cow.EventUpdate(weeklyActive)
  115. if err := e.DB.Model(new(model.Cow)).
  116. Select("day_age", "calving_age", "pregnancy_age", "admission_age", "abortion_age", "cow_type", "weekly_active").
  117. Where("id = ?", cow.Id).
  118. Updates(cow).Error; err != nil {
  119. zaplog.Error("Crontab", zap.Any("UpdateCowDayAge", err))
  120. }
  121. }
  122. return nil
  123. }
  124. // ImmunizationPlan 免疫计划,生成工作单
  125. func (e *Entry) ImmunizationPlan() error {
  126. if ok := e.IsExistCrontabLog(ImmunizationPlan); ok {
  127. return nil
  128. }
  129. planList := make([]*model.ImmunizationPlan, 0)
  130. if err := e.DB.Model(new(model.ImmunizationPlan)).
  131. Where("is_show = ?", pasturePb.IsShow_Ok).
  132. Order("pasture_id").
  133. Find(&planList).Error; err != nil {
  134. return xerr.WithStack(err)
  135. }
  136. var todayCount int32 = 0
  137. nowTime := time.Now()
  138. for _, plan := range planList {
  139. cowList := make([]*model.Cow, 0)
  140. pref := e.DB.Table(fmt.Sprintf("%s as a", new(model.Cow).TableName())).
  141. Select("a.*").
  142. Where("a.pasture_id = ?", plan.PastureId).
  143. Where("a.admission_status = ?", pasturePb.AdmissionStatus_Admission).
  144. Where("NOT EXISTS ( select 1 from event_immunization_plan b where b.pen_id = a.id and b.status = ? and b.plan_day > ?)", pasturePb.IsShow_No, nowTime.Unix())
  145. if plan.CowType > 0 {
  146. pref.Where("a.cow_type = ?", plan.CowType)
  147. }
  148. switch plan.Conditions {
  149. case pasturePb.ImmunizationConditions_Days_Age:
  150. pref.Where("a.day_age = ?", plan.Value)
  151. case pasturePb.ImmunizationConditions_Days_After_Delivery:
  152. pref.Where("a.calving_age = ?", plan.Value)
  153. case pasturePb.ImmunizationConditions_Days_Of_Pregnancy:
  154. pref.Where("a.pregnancy_age = ?", plan.Value).
  155. Where("a.is_pregnant = ?", pasturePb.IsShow_Ok)
  156. case pasturePb.ImmunizationConditions_Month:
  157. continue
  158. case pasturePb.ImmunizationConditions_Admission_Days:
  159. pref.Where("a.admission_age = ?", plan.Value)
  160. case pasturePb.ImmunizationConditions_Other_Vaccine_After:
  161. if plan.ImmunizationPlanId > 0 {
  162. pref.Joins("INNER JOIN event_immunization_plan as b ON b.plan_id = ? ", plan.ImmunizationPlanId).
  163. Where("b.cow_id = a.id").
  164. Where("DATE_ADD(b.reality_day, INTERVAL ? DAY) = ?", plan.Value, time.Now().Format(model.LayoutDate2)).
  165. Where("b.status = ?", pasturePb.IsShow_Ok)
  166. }
  167. }
  168. if err := pref.Find(&cowList).Debug().Error; err != nil {
  169. return xerr.WithStack(err)
  170. }
  171. if len(cowList) <= 0 {
  172. continue
  173. }
  174. newImmunizationPlanCowList := model.NewCowImmunizationPlanList(cowList, plan)
  175. if err := e.DB.Model(new(model.EventImmunizationPlan)).Create(newImmunizationPlanCowList).Error; err != nil {
  176. zaplog.Error("ImmunizationPlan",
  177. zap.Any("err", err),
  178. zap.Any("plan", plan),
  179. zap.Any("cowList", cowList),
  180. zap.Any("newImmunizationPlanCowList", newImmunizationPlanCowList),
  181. )
  182. return xerr.WithStack(err)
  183. }
  184. todayCount = int32(len(newImmunizationPlanCowList))
  185. if todayCount > 0 {
  186. endDay := nowTime.AddDate(0, 0, model.CalendarTypeCycleMap[pasturePb.CalendarType_Immunisation])
  187. e.CreatedCalendar(plan.PastureId, pasturePb.CalendarType_Immunisation, nowTime.Format(model.LayoutDate2), endDay.Format(model.LayoutDate2), todayCount)
  188. }
  189. e.CreateCrontabLog(ImmunizationPlan)
  190. }
  191. return nil
  192. }
  193. // SameTimePlan 同期计划,生成工作单
  194. func (e *Entry) SameTimePlan() error {
  195. if ok := e.IsExistCrontabLog(SameTimePlan); ok {
  196. return nil
  197. }
  198. sameTimeList := make([]*model.SameTime, 0)
  199. if err := e.DB.Model(new(model.SameTime)).
  200. Where("is_show = ?", pasturePb.IsShow_Ok).
  201. Order("pasture_id").
  202. Find(&sameTimeList).Error; err != nil {
  203. return xerr.WithStack(err)
  204. }
  205. if len(sameTimeList) < 0 {
  206. return nil
  207. }
  208. defer func() {
  209. e.CreateCrontabLog(SameTimePlan)
  210. }()
  211. currWeek := time.Now().Weekday()
  212. for _, sameTime := range sameTimeList {
  213. if time.Weekday(sameTime.WeekType) != currWeek {
  214. continue
  215. }
  216. cowList := make([]*model.Cow, 0)
  217. pref := e.DB.Model(new(model.Cow)).
  218. Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
  219. Where("sex = ?", pasturePb.Genders_Female).
  220. Where("pasture_id = ?", sameTime.PastureId).
  221. Where("is_pregnant = ?", pasturePb.IsShow_No)
  222. switch sameTime.CowType {
  223. case pasturePb.SameTimeCowType_Breeding_Calf:
  224. pref.Where("calving_age BETWEEN ? AND ?", sameTime.PostpartumDaysStart, sameTime.PostpartumDaysEnd).
  225. Where("lact > ?", 0)
  226. case pasturePb.SameTimeCowType_Empty:
  227. pref.Where(
  228. e.DB.Where("breed_status = ?", pasturePb.BreedStatus_Empty).
  229. Or("breed_status = ?", pasturePb.BreedStatus_Abort),
  230. )
  231. default:
  232. continue
  233. }
  234. if err := pref.Where(`NOT EXISTS (SELECT 1 FROM event_cow_same_time WHERE event_cow_same_time.cow_id = cow.id
  235. AND event_cow_same_time.status = ?)`, pasturePb.IsShow_No).
  236. Find(&cowList).Error; err != nil {
  237. zaplog.Error("crontab", zap.Any("err", err), zap.Any("sameTime", sameTime))
  238. return xerr.WithStack(err)
  239. }
  240. if len(cowList) <= 0 {
  241. continue
  242. }
  243. if err := e.GenerateCalendarBySameTimePlan(cowList, sameTime); err != nil {
  244. zaplog.Error("crontab",
  245. zap.Any("GenerateCalendarBySameTimePlan", err),
  246. zap.Any("cowList", cowList),
  247. zap.Any("plan", sameTime),
  248. )
  249. continue
  250. }
  251. }
  252. return nil
  253. }
  254. // UpdateSameTime 更新每天同期数据
  255. func (e *Entry) UpdateSameTime() error {
  256. calendarTypeList := backend.CalendarTypeEnumList("")
  257. showDay := time.Now().Format(model.LayoutDate2)
  258. for _, v := range calendarTypeList {
  259. count := int64(0)
  260. if err := e.DB.Model(new(model.EventCowSameTime)).
  261. Where("same_time_type = ?", v.Value).
  262. Where("status = ?", pasturePb.IsShow_No).
  263. Count(&count).Error; err != nil {
  264. zaplog.Error("crontab", zap.Any("UpdateSameTime", err), zap.Any("count", count))
  265. }
  266. if count >= 0 {
  267. continue
  268. }
  269. isExist := int64(0)
  270. if err := e.DB.Model(new(model.Calendar)).
  271. Where("calendar_type = ?", v.Value).
  272. Where("show_day = ?", showDay).
  273. Count(&isExist).Error; err != nil {
  274. continue
  275. }
  276. if isExist <= 0 {
  277. continue
  278. }
  279. if err := e.DB.Model(new(model.Calendar)).
  280. Where("calendar_type = ?", v.Value).
  281. Where("show_day = ?", showDay).
  282. Updates(map[string]interface{}{
  283. "count": count,
  284. }).Error; err != nil {
  285. continue
  286. }
  287. }
  288. return nil
  289. }
  290. // SystemBasicCrontab 基础配置计划任务
  291. func (e *Entry) SystemBasicCrontab() error {
  292. if ok := e.IsExistCrontabLog(SystemBasicCrontab); ok {
  293. return nil
  294. }
  295. defer func() {
  296. e.CreateCrontabLog(SystemBasicCrontab)
  297. }()
  298. systemBasicList := make([]*model.SystemBasic, 0)
  299. if err := e.DB.Model(new(model.SystemBasic)).
  300. Where("is_show = ?", pasturePb.IsShow_Ok).
  301. Where("name IN ?", []string{
  302. model.PregnantCheckForFirst,
  303. model.PregnantCheckForSecond,
  304. model.WeaningAge,
  305. model.PregnancyAge,
  306. }).Find(&systemBasicList).Error; err != nil {
  307. zaplog.Error("crontab", zap.Any("PregnancyCheck", err))
  308. return xerr.WithStack(err)
  309. }
  310. currWeekValue := time.Now().Weekday()
  311. for _, systemBasic := range systemBasicList {
  312. // 周执行
  313. if systemBasic.Name == model.PregnantCheckForFirst && systemBasic.WeekValue >= 0 && time.Weekday(systemBasic.WeekValue) != currWeekValue {
  314. continue
  315. }
  316. cowList := make([]*model.Cow, 0)
  317. pref := e.DB.Model(new(model.Cow)).
  318. Where("admission_status = ? ", pasturePb.AdmissionStatus_Admission).
  319. Where("pasture_id = ?", systemBasic.PastureId)
  320. switch systemBasic.Name {
  321. case model.PregnantCheckForFirst: // 初检清单
  322. pref.Where("breed_status = ?", pasturePb.BreedStatus_Breeding).
  323. Where("last_mating_at > ?", 0).
  324. Where("DATE(FROM_UNIXTIME(last_mating_at)) BETWEEN DATE_SUB(CURDATE(), INTERVAL ? DAY) AND DATE_SUB(CURDATE(), INTERVAL ? DAY)", systemBasic.MaxValue, systemBasic.MinValue).
  325. Where(`NOT EXISTS (SELECT 1 FROM event_pregnant_check WHERE event_pregnant_check.cow_id = cow.id
  326. AND event_pregnant_check.status = ? AND event_pregnant_check.pregnant_check_name = ?)`, pasturePb.IsShow_No, model.PregnantCheckForFirst)
  327. case model.PregnantCheckForSecond: // 复检清单 过滤初检空怀的牛只
  328. pref.Where("breed_status IN (?)", []pasturePb.BreedStatus_Kind{pasturePb.BreedStatus_Pregnant}).
  329. Where("last_mating_at > ?", 0).
  330. Where("DATE(FROM_UNIXTIME(last_mating_at)) = DATE_SUB(CURDATE(), INTERVAL ? DAY)", systemBasic.MinValue).
  331. Where(`NOT EXISTS (SELECT 1 FROM event_pregnant_check WHERE event_pregnant_check.cow_id = cow.id
  332. AND event_pregnant_check.status = ? AND event_pregnant_check.pregnant_check_name = ? )`, pasturePb.IsShow_No, model.PregnantCheckForSecond)
  333. case model.WeaningAge: // 断奶清单
  334. pref.Where("day_age = ?", systemBasic.MinValue).
  335. Where("NOT EXISTS (SELECT 1 FROM event_weaning WHERE event_weaning.cow_id = cow.id AND event_weaning.status = ?)", pasturePb.IsShow_No)
  336. case model.PregnancyAge: // 产犊清单
  337. pref.Where("pregnancy_age BETWEEN ? AND ?", systemBasic.MinValue, systemBasic.MaxValue).
  338. Where("breed_status = ?", pasturePb.BreedStatus_Pregnant).
  339. Where("NOT EXISTS (SELECT 1 FROM event_calving WHERE event_calving.cow_id = cow.id AND event_calving.status = ?)", pasturePb.IsShow_No)
  340. default:
  341. continue
  342. }
  343. if err := pref.Find(&cowList).Error; err != nil {
  344. zaplog.Error("crontab", zap.Any("PregnancyCheck", err), zap.Any("cowList", cowList))
  345. continue
  346. }
  347. if len(cowList) <= 0 {
  348. continue
  349. }
  350. e.InitEventData(cowList, systemBasic)
  351. }
  352. return nil
  353. }
  354. func (e *Entry) DeleteOldOriginal() error {
  355. if err := e.DB.Model(new(model.NeckRingOriginal)).
  356. Where("active_date <= ?", time.Now().AddDate(0, 0, -7).Format(model.LayoutDate2)).
  357. Delete(&model.NeckRingOriginal{}).Error; err != nil {
  358. zaplog.Error("crontab", zap.Any("DeleteOldOriginal", err))
  359. }
  360. return nil
  361. }
  362. // UpdateDiseaseToCalendar 更新每天治疗中牛头数到日历表中
  363. func (e *Entry) UpdateDiseaseToCalendar() error {
  364. pastureList := e.FindPastureList()
  365. for _, pasture := range pastureList {
  366. // 更新每天治疗中牛头数到日历表中
  367. var count int64
  368. if err := e.DB.Model(new(model.EventCowDisease)).
  369. Where("pasture_id = ?", pasture.Id).
  370. Where("health_status IN (?)", []pasturePb.HealthStatus_Kind{pasturePb.HealthStatus_Disease, pasturePb.HealthStatus_Treatment}).
  371. Count(&count).Error; err != nil {
  372. zaplog.Error("crontab", zap.Any("UpdateDisease", err))
  373. }
  374. if count > 0 {
  375. calendarTypeName := backend.CalendarTypeMap()[pasturePb.CalendarType_Disease]
  376. startDay := time.Now().Format(model.LayoutDate2)
  377. newCalendar := model.NewCalendar(pasture.Id, calendarTypeName, pasturePb.CalendarType_Disease, startDay, startDay, int32(count))
  378. if err := e.DB.Model(new(model.Calendar)).
  379. Create(newCalendar).Error; err != nil {
  380. zaplog.Error("crontab", zap.Any("UpdateDisease", err))
  381. }
  382. }
  383. }
  384. return nil
  385. }
  386. func (e *Entry) InitEventData(cowList []*model.Cow, systemBasic *model.SystemBasic) {
  387. calendarType := pasturePb.CalendarType_Invalid
  388. nowTime := time.Now()
  389. startDay, endDay := "", ""
  390. switch systemBasic.Name {
  391. case model.PregnantCheckForFirst, model.PregnantCheckForSecond:
  392. penMap, _ := e.GetPenMapList(systemBasic.PastureId)
  393. calendarType = pasturePb.CalendarType_Pregnancy_Check
  394. startDay, endDay = nowTime.Format(model.LayoutDate2), nowTime.AddDate(0, 0, model.CalendarTypeCycleMap[calendarType]).Format(model.LayoutDate2)
  395. eventPregnantCheckDataList := model.NewEventPregnantCheckList(systemBasic.PastureId, cowList, penMap, systemBasic.Name, startDay, endDay)
  396. if err := e.DB.Model(new(model.EventPregnantCheck)).Create(eventPregnantCheckDataList).Error; err != nil {
  397. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventPregnantCheckDataList", eventPregnantCheckDataList))
  398. return
  399. }
  400. case model.WeaningAge:
  401. calendarType = pasturePb.CalendarType_Weaning
  402. startDay, endDay = nowTime.Format(model.LayoutDate2), nowTime.AddDate(0, 0, model.CalendarTypeCycleMap[calendarType]).Format(model.LayoutDate2)
  403. eventWeaningDataList := model.NewEventWeaningList(systemBasic.PastureId, cowList, startDay, endDay)
  404. if err := e.DB.Model(new(model.EventWeaning)).Create(eventWeaningDataList).Error; err != nil {
  405. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventWeaningDataList", eventWeaningDataList))
  406. return
  407. }
  408. case model.PregnancyAge:
  409. calendarType = pasturePb.CalendarType_Calving
  410. startDay, endDay = nowTime.Format(model.LayoutDate2), nowTime.AddDate(0, 0, model.CalendarTypeCycleMap[calendarType]).Format(model.LayoutDate2)
  411. eventCalvingList := model.NewEventCalvingList(systemBasic.PastureId, cowList, startDay, endDay)
  412. if err := e.DB.Model(new(model.EventCalving)).Create(eventCalvingList).Error; err != nil {
  413. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventCalvingList", eventCalvingList))
  414. return
  415. }
  416. }
  417. e.CreatedCalendar(systemBasic.PastureId, calendarType, startDay, endDay, int32(len(cowList)))
  418. }
  419. // UpdateCowWeeklyHigh 更新牛只周活动量
  420. func (e *Entry) UpdateCowWeeklyHigh(cow *model.Cow) int32 {
  421. highData, err := e.GetSystemNeckRingConfigure(cow.PastureId, model.High)
  422. if err != nil || highData == nil || highData.Value <= 0 {
  423. return 0
  424. }
  425. minWeeklyActive, er := e.GetSystemNeckRingConfigure(cow.PastureId, model.MinWeeklyActive)
  426. if er != nil || minWeeklyActive == nil || minWeeklyActive.Value <= 0 {
  427. return 0
  428. }
  429. weeklyActiveModelList := make([]*model.WeeklyActiveModel, 0)
  430. startTime := time.Now().AddDate(0, 0, -8).Format(model.LayoutDate2)
  431. endTime := time.Now().AddDate(0, 0, -2).Format(model.LayoutDate2)
  432. selectStr := fmt.Sprintf(`cow_id,heat_date,count(1) AS nb,IF(ROUND(AVG(high))>%d, ROUND(AVG(high)), %d) AS high`, minWeeklyActive.Value, minWeeklyActive.Value)
  433. if err = e.DB.Model(new(model.NeckActiveHabit)).
  434. Select(selectStr).
  435. Where("cow_id = ?", cow.Id).
  436. Where("heat_date BETWEEN ? AND ?", startTime, endTime).
  437. Where("high > ?", highData.Value).
  438. Having("nb > ?", 8).
  439. Order("high").
  440. Group("heat_date").
  441. Find(&weeklyActiveModelList).Error; err != nil {
  442. zaplog.Error("crontab", zap.Any("UpdateCowWeeklyHigh", err))
  443. return 0
  444. }
  445. if len(weeklyActiveModelList) < 3 {
  446. return 0
  447. }
  448. countHigh := len(weeklyActiveModelList)
  449. sumHigh := int32(0)
  450. minHigh := weeklyActiveModelList[0].High
  451. maxHigh := int32(0)
  452. for _, v := range weeklyActiveModelList {
  453. sumHigh += v.High
  454. if v.High > maxHigh {
  455. maxHigh = v.High
  456. }
  457. if v.High < minHigh {
  458. minHigh = v.High
  459. }
  460. }
  461. diff := 3
  462. x := int32(0)
  463. if countHigh == 3 {
  464. diff = 2
  465. x = weeklyActiveModelList[1].High
  466. }
  467. avgHigh := float64(sumHigh-minHigh-maxHigh-x) / float64(countHigh-diff)
  468. return int32(avgHigh)
  469. }