cow_cron.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. for _, indicatorsDetail := range indicatorsDetailsList {
  62. pastureIndicatorList := map[int64]string{}
  63. switch indicatorsDetail.Kind {
  64. case model.AllCow:
  65. pastureIndicatorList = e.FindPastureAllCow(pastureList)
  66. case model.CalvingInterval:
  67. pastureIndicatorList = e.FindCalvingInterval(pastureList, startTime, endTime)
  68. case model.OutputNumber:
  69. pastureIndicatorList = e.FindOutputNumber(pastureList, startTime, endTime)
  70. case model.InputNumber:
  71. pastureIndicatorList = e.FindInputNumber(pastureList, startTime, endTime)
  72. case model.SalesVolume:
  73. pastureIndicatorList = e.FindSalesVolume(pastureList, startTime, endTime)
  74. case model.CalvingNumber:
  75. pastureIndicatorList = e.FindCalvingNumber(pastureList, startTime, endTime)
  76. case model.AdultAbortionRate:
  77. pastureIndicatorList = e.FindAdultAbortionRate(pastureList, "adult", startTime, endTime)
  78. case model.YouthAbortionRate:
  79. pastureIndicatorList = e.FindAdultAbortionRate(pastureList, "youth", startTime, endTime)
  80. case model.AllDieNumber:
  81. pastureIndicatorList = e.FindDepartureNumber(pastureList, pasturePb.DepartureType_Death, startTime, endTime)
  82. case model.DiseaseNumber:
  83. pastureIndicatorList = e.FindDiseaseNumber(pastureList, startTime, endTime)
  84. case model.CureNumber:
  85. pastureIndicatorList = e.FindCureNumber(pastureList, startTime, endTime)
  86. case model.OutNumber:
  87. pastureIndicatorList = e.FindDepartureNumber(pastureList, pasturePb.DepartureType_Out, startTime, endTime)
  88. case model.CalfDieNumber:
  89. pastureIndicatorList = e.FindCalfDieNumber(pastureList, pasturePb.DepartureType_Death, startTime, endTime)
  90. }
  91. for pastureId, value := range pastureIndicatorList {
  92. e.UpdatePastureIndicators(pastureId, indicatorsDetail, startTime, value)
  93. }
  94. }
  95. return nil
  96. }
  97. // UpdateCowInfo 牛只基本信息维护
  98. func (e *Entry) UpdateCowInfo() error {
  99. cowList := make([]*model.Cow, 0)
  100. if err := e.DB.Model(new(model.Cow)).
  101. Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
  102. Find(&cowList).Error; err != nil {
  103. return err
  104. }
  105. if ok := e.IsExistCrontabLog(UpdateCowInfo); ok {
  106. return nil
  107. }
  108. defer func() {
  109. e.CreateCrontabLog(UpdateCowInfo)
  110. }()
  111. for _, cow := range cowList {
  112. weeklyActive := e.UpdateCowWeeklyHigh(cow)
  113. cow.EventUpdate(weeklyActive)
  114. if err := e.DB.Model(new(model.Cow)).
  115. Select("day_age", "calving_age", "pregnancy_age", "admission_age", "abortion_age", "cow_type",
  116. "weekly_active", "lactation_age", "dry_milk_age").
  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.CalendarTypeEndDaysMap[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. model.DryMilkAge,
  307. }).Order("pasture_id").
  308. Find(&systemBasicList).Error; err != nil {
  309. zaplog.Error("crontab", zap.Any("PregnancyCheck", err))
  310. return xerr.WithStack(err)
  311. }
  312. currWeekValue := time.Now().Weekday()
  313. for _, systemBasic := range systemBasicList {
  314. // 周执行
  315. if systemBasic.Name == model.PregnantCheckForFirst && systemBasic.WeekValue >= 0 &&
  316. time.Weekday(systemBasic.WeekValue) != currWeekValue {
  317. continue
  318. }
  319. cowList := make([]*model.Cow, 0)
  320. pref := e.DB.Model(new(model.Cow)).
  321. Where("admission_status = ? ", pasturePb.AdmissionStatus_Admission).
  322. Where("pasture_id = ?", systemBasic.PastureId)
  323. switch systemBasic.Name {
  324. case model.PregnantCheckForFirst: // 初检清单
  325. pref.Where("breed_status = ?", pasturePb.BreedStatus_Breeding).
  326. Where("last_mating_at > ?", 0).
  327. Where("DATE(FROM_UNIXTIME(last_mating_at)) BETWEEN DATE_SUB(CURDATE(), INTERVAL ? DAY) AND DATE_SUB(CURDATE(), INTERVAL ? DAY)", systemBasic.MaxValue, systemBasic.MinValue).
  328. Where(`NOT EXISTS (SELECT 1 FROM event_pregnant_check WHERE event_pregnant_check.cow_id = cow.id
  329. AND event_pregnant_check.status = ? AND event_pregnant_check.pregnant_check_name = ?)`, pasturePb.IsShow_No, model.PregnantCheckForFirst)
  330. case model.PregnantCheckForSecond: // 复检清单 过滤初检空怀的牛只
  331. pref.Where("breed_status IN (?)", []pasturePb.BreedStatus_Kind{pasturePb.BreedStatus_Pregnant}).
  332. Where("last_mating_at > ?", 0).
  333. Where("DATE(FROM_UNIXTIME(last_mating_at)) = DATE_SUB(CURDATE(), INTERVAL ? DAY)", systemBasic.MinValue).
  334. Where(`NOT EXISTS (SELECT 1 FROM event_pregnant_check WHERE event_pregnant_check.cow_id = cow.id
  335. AND event_pregnant_check.status = ? AND event_pregnant_check.pregnant_check_name = ? )`, pasturePb.IsShow_No, model.PregnantCheckForSecond)
  336. case model.WeaningAge: // 断奶清单
  337. pref.Where("day_age = ?", systemBasic.MinValue).
  338. Where("NOT EXISTS (SELECT 1 FROM event_weaning WHERE event_weaning.cow_id = cow.id AND event_weaning.status = ?)", pasturePb.IsShow_No)
  339. case model.PregnancyAge: // 产犊清单
  340. pref.Where("pregnancy_age = ?", systemBasic.MinValue-10).
  341. Where("breed_status = ?", pasturePb.BreedStatus_Pregnant).
  342. Where("NOT EXISTS (SELECT 1 FROM event_calving WHERE event_calving.cow_id = cow.id AND event_calving.status = ?)", pasturePb.IsShow_No)
  343. case model.DryMilkAge: // 干奶清单
  344. pref.Where("pregnancy_age = ?", systemBasic.MinValue).
  345. Where("breed_status = ?", pasturePb.BreedStatus_Pregnant).
  346. Where("is_pregnant = ?", pasturePb.IsShow_Ok).
  347. Where("NOT EXISTS (SELECT 1 FROM event_dry_milk WHERE event_dry_milk.cow_id = cow.id AND event_dry_milk.status = ?)", pasturePb.IsShow_No)
  348. default:
  349. continue
  350. }
  351. if err := pref.Find(&cowList).Error; err != nil {
  352. zaplog.Error("crontab", zap.Any("PregnancyCheck", err), zap.Any("cowList", cowList))
  353. continue
  354. }
  355. if len(cowList) <= 0 {
  356. continue
  357. }
  358. e.InitEventData(cowList, systemBasic)
  359. }
  360. return nil
  361. }
  362. func (e *Entry) DeleteOldOriginal() error {
  363. if err := e.DB.Model(new(model.NeckRingOriginal)).
  364. Where("active_date <= ?", time.Now().AddDate(0, 0, -7).Format(model.LayoutDate2)).
  365. Delete(&model.NeckRingOriginal{}).Error; err != nil {
  366. zaplog.Error("crontab", zap.Any("DeleteOldOriginal", err))
  367. }
  368. return nil
  369. }
  370. // UpdateDiseaseToCalendar 更新每天治疗中牛头数到日历表中
  371. func (e *Entry) UpdateDiseaseToCalendar() error {
  372. pastureList := e.FindPastureList()
  373. for _, pasture := range pastureList {
  374. // 更新每天治疗中牛头数到日历表中
  375. var count int64
  376. if err := e.DB.Model(new(model.EventCowDisease)).
  377. Where("pasture_id = ?", pasture.Id).
  378. Where("health_status IN (?)", []pasturePb.HealthStatus_Kind{pasturePb.HealthStatus_Disease, pasturePb.HealthStatus_Treatment}).
  379. Count(&count).Error; err != nil {
  380. zaplog.Error("crontab", zap.Any("UpdateDisease", err))
  381. }
  382. if count > 0 {
  383. calendarTypeName := backend.CalendarTypeMap()[pasturePb.CalendarType_Disease]
  384. startDay := time.Now().Format(model.LayoutDate2)
  385. newCalendar := model.NewCalendar(pasture.Id, calendarTypeName, pasturePb.CalendarType_Disease, startDay, startDay, int32(count))
  386. if err := e.DB.Model(new(model.Calendar)).
  387. Create(newCalendar).Error; err != nil {
  388. zaplog.Error("crontab", zap.Any("UpdateDisease", err))
  389. }
  390. }
  391. }
  392. return nil
  393. }
  394. func (e *Entry) InitEventData(cowList []*model.Cow, systemBasic *model.SystemBasic) {
  395. calendarType := pasturePb.CalendarType_Invalid
  396. nowTime := time.Now()
  397. startDay, endDay := "", ""
  398. switch systemBasic.Name {
  399. case model.PregnantCheckForFirst, model.PregnantCheckForSecond:
  400. penMap, _ := e.GetPenMapList(systemBasic.PastureId)
  401. calendarType = pasturePb.CalendarType_Pregnancy_Check
  402. startDay, endDay = nowTime.Format(model.LayoutDate2), nowTime.AddDate(0, 0, model.CalendarTypeEndDaysMap[calendarType]).Format(model.LayoutDate2)
  403. eventPregnantCheckDataList := model.NewEventPregnantCheckList(systemBasic.PastureId, cowList, penMap, systemBasic.Name, startDay, endDay)
  404. if err := e.DB.Model(new(model.EventPregnantCheck)).Create(eventPregnantCheckDataList).Error; err != nil {
  405. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventPregnantCheckDataList", eventPregnantCheckDataList))
  406. return
  407. }
  408. case model.WeaningAge:
  409. calendarType = pasturePb.CalendarType_Weaning
  410. startDay, endDay = nowTime.Format(model.LayoutDate2), nowTime.AddDate(0, 0, model.CalendarTypeEndDaysMap[calendarType]).Format(model.LayoutDate2)
  411. eventWeaningDataList := model.NewEventWeaningList(systemBasic.PastureId, cowList, startDay, endDay)
  412. if err := e.DB.Model(new(model.EventWeaning)).Create(eventWeaningDataList).Error; err != nil {
  413. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventWeaningDataList", eventWeaningDataList))
  414. return
  415. }
  416. case model.PregnancyAge:
  417. calendarType = pasturePb.CalendarType_Calving
  418. startDay, endDay = nowTime.Format(model.LayoutDate2), nowTime.AddDate(0, 0, model.CalendarTypeEndDaysMap[calendarType]).Format(model.LayoutDate2)
  419. eventCalvingList := model.NewEventCalvingList(systemBasic.PastureId, cowList, startDay, endDay)
  420. if err := e.DB.Model(new(model.EventCalving)).Create(eventCalvingList).Error; err != nil {
  421. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventCalvingList", eventCalvingList))
  422. return
  423. }
  424. case model.DryMilkAge:
  425. calendarType = pasturePb.CalendarType_DryMilk
  426. startDay, endDay = nowTime.Format(model.LayoutDate2), nowTime.AddDate(0, 0, model.CalendarTypeEndDaysMap[calendarType]).Format(model.LayoutDate2)
  427. eventCalvingList := model.NewEventDryMilkList(systemBasic.PastureId, cowList, startDay, endDay)
  428. if err := e.DB.Model(new(model.EventDryMilk)).Create(eventCalvingList).Error; err != nil {
  429. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventCalvingList", eventCalvingList))
  430. return
  431. }
  432. }
  433. e.CreatedCalendar(systemBasic.PastureId, calendarType, startDay, endDay, int32(len(cowList)))
  434. }
  435. // UpdateCowWeeklyHigh 更新牛只周活动量
  436. func (e *Entry) UpdateCowWeeklyHigh(cow *model.Cow) int32 {
  437. highData, err := e.GetSystemNeckRingConfigure(cow.PastureId, model.High)
  438. if err != nil || highData == nil || highData.Value <= 0 {
  439. return 0
  440. }
  441. minWeeklyActive, er := e.GetSystemNeckRingConfigure(cow.PastureId, model.MinWeeklyActive)
  442. if er != nil || minWeeklyActive == nil || minWeeklyActive.Value <= 0 {
  443. return 0
  444. }
  445. weeklyActiveModelList := make([]*model.WeeklyActiveModel, 0)
  446. startTime := time.Now().AddDate(0, 0, -8).Format(model.LayoutDate2)
  447. endTime := time.Now().AddDate(0, 0, -2).Format(model.LayoutDate2)
  448. 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)
  449. if err = e.DB.Model(new(model.NeckActiveHabit)).
  450. Select(selectStr).
  451. Where("cow_id = ?", cow.Id).
  452. Where("heat_date BETWEEN ? AND ?", startTime, endTime).
  453. Where("high > ?", highData.Value).
  454. Having("nb > ?", 8).
  455. Order("high").
  456. Group("heat_date").
  457. Find(&weeklyActiveModelList).Error; err != nil {
  458. zaplog.Error("crontab", zap.Any("UpdateCowWeeklyHigh", err))
  459. return 0
  460. }
  461. if len(weeklyActiveModelList) < 3 {
  462. return 0
  463. }
  464. countHigh := len(weeklyActiveModelList)
  465. sumHigh := int32(0)
  466. minHigh := weeklyActiveModelList[0].High
  467. maxHigh := int32(0)
  468. for _, v := range weeklyActiveModelList {
  469. sumHigh += v.High
  470. if v.High > maxHigh {
  471. maxHigh = v.High
  472. }
  473. if v.High < minHigh {
  474. minHigh = v.High
  475. }
  476. }
  477. diff := 3
  478. x := int32(0)
  479. if countHigh == 3 {
  480. diff = 2
  481. x = weeklyActiveModelList[1].High
  482. }
  483. avgHigh := float64(sumHigh-minHigh-maxHigh-x) / float64(countHigh-diff)
  484. return int32(avgHigh)
  485. }