cow_cron.go 20 KB

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