cow_cron.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. package crontab
  2. import (
  3. "context"
  4. "fmt"
  5. "kpt-pasture/model"
  6. "kpt-pasture/module/backend"
  7. "kpt-pasture/util"
  8. "sort"
  9. "strings"
  10. "time"
  11. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  12. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  13. "gitee.com/xuyiping_admin/pkg/xerr"
  14. "go.uber.org/zap"
  15. )
  16. const (
  17. UpdateCowInfo = "UpdateCowInfo"
  18. ImmunizationPlan = "ImmunizationPlan"
  19. SameTimePlan = "SameTimePlan"
  20. WorkOrderMaster = "WorkOrderMaster"
  21. SystemBasicCrontab = "SystemBasicCrontab"
  22. NeckRingOriginal = "NeckRingOriginal"
  23. )
  24. // GenerateAsynqWorkOrder 异步生成工作单
  25. func (e *Entry) GenerateAsynqWorkOrder() error {
  26. if ok := e.IsExistCrontabLog(WorkOrderMaster); ok {
  27. return nil
  28. }
  29. defer func() {
  30. e.CreateCrontabLog(WorkOrderMaster)
  31. }()
  32. workOrderList := make([]*model.WorkOrderMaster, 0)
  33. if err := e.DB.Where("is_show = ?", pasturePb.IsShow_Ok).Find(&workOrderList).Error; err != nil {
  34. return err
  35. }
  36. for _, workOrder := range workOrderList {
  37. timeUnix, err := util.ConvertParseLocalUnix(workOrder.ExecTime)
  38. if timeUnix <= 0 || err != nil {
  39. zaplog.Error("crontab", zap.Any("GenerateWorkOrder", err), zap.Any("execTime", workOrder.ExecTime))
  40. continue
  41. }
  42. nowTime := time.Now().Local().Unix()
  43. if timeUnix < nowTime {
  44. continue
  45. }
  46. execTime := timeUnix - nowTime
  47. task := model.NewTaskWorkOrderPayload(workOrder.Id, time.Duration(execTime)*time.Second)
  48. if _, err = e.AsynqClient.CtxEnqueue(context.Background(), task); err != nil {
  49. zaplog.Error("PushMessage CtxEnqueue", zap.Any("Err", err))
  50. }
  51. }
  52. return nil
  53. }
  54. // Indicators 月度指标维护
  55. func (e *Entry) Indicators() error {
  56. nowTime := time.Now().Local()
  57. defer func() {
  58. zaplog.Info("crontab", zap.Any("Indicators", time.Now().Sub(nowTime).Seconds()))
  59. }()
  60. // 获取所有指标
  61. indicatorsDetailsList := make([]*model.IndicatorsDetails, 0)
  62. if err := e.DB.Model(new(model.IndicatorsDetails)).
  63. Where("is_show = ?", pasturePb.IsShow_Ok).
  64. Find(&indicatorsDetailsList).Error; err != nil {
  65. return err
  66. }
  67. // 获取所有牧场
  68. pastureList := e.FindPastureList()
  69. // 获取当月开始时间和结束时间
  70. startTime, endTime := util.GetMonthStartAndEndTimestamp()
  71. for _, indicatorsDetail := range indicatorsDetailsList {
  72. pastureIndicatorList := map[int64]string{}
  73. switch indicatorsDetail.Kind {
  74. case model.AllCow:
  75. pastureIndicatorList = e.FindPastureAllCow(pastureList)
  76. case model.AdultCow:
  77. pastureIndicatorList = e.FindPastureAdultCow(pastureList)
  78. case model.AvgCalvingInterval:
  79. pastureIndicatorList = e.FindAvgCalvingInterval(pastureList, startTime, endTime)
  80. case model.OutputNumber:
  81. pastureIndicatorList = e.FindOutputNumber(pastureList, startTime, endTime)
  82. case model.InputNumber:
  83. pastureIndicatorList = e.FindInputNumber(pastureList, startTime, endTime)
  84. case model.SalesVolume:
  85. pastureIndicatorList = e.FindSalesVolume(pastureList, startTime, endTime)
  86. case model.CalvingNumber:
  87. pastureIndicatorList = e.FindCalvingNumber(pastureList, startTime, endTime)
  88. case model.FattenCattleNumber:
  89. pastureIndicatorList = e.FattenCattleNumber(pastureList, startTime, endTime)
  90. case model.YouthAbortionRate:
  91. pastureIndicatorList = e.FindAdultAbortionRate(pastureList, "youth", startTime, endTime)
  92. case model.AllDieNumber:
  93. pastureIndicatorList = e.FindDeathNumber(pastureList, startTime, endTime, false)
  94. case model.DiseaseNumber:
  95. pastureIndicatorList = e.FindDiseaseNumber(pastureList, startTime, endTime)
  96. case model.CureNumber:
  97. pastureIndicatorList = e.FindCureNumber(pastureList, startTime, endTime)
  98. case model.OutNumber:
  99. pastureIndicatorList = e.FindDepartureNumber(pastureList, pasturePb.SalesType_Out, startTime, endTime)
  100. case model.CalfDieNumber:
  101. pastureIndicatorList = e.FindDeathNumber(pastureList, startTime, endTime, true)
  102. case model.LactationCow:
  103. pastureIndicatorList = e.LactationCow(pastureList, pasturePb.CowMilk_Lactation)
  104. case model.DryMilkCow:
  105. pastureIndicatorList = e.LactationCow(pastureList, pasturePb.CowMilk_Dry_Milk)
  106. case model.ReserveCow:
  107. pastureIndicatorList = e.LactationCow(pastureList, pasturePb.CowMilk_Reserve)
  108. case model.FirstBornSurvivalRate:
  109. pastureIndicatorList = e.FirstBornSurvivalRate(pastureList, startTime, endTime)
  110. case model.FirstBornDeathRate:
  111. pastureIndicatorList = e.FirstBornDeathRate(pastureList, startTime, endTime)
  112. case model.MultiparitySurvivalRate:
  113. pastureIndicatorList = e.MultiparitySurvivalRate(pastureList, startTime, endTime)
  114. case model.MultiparityDeathRate:
  115. pastureIndicatorList = e.MultiparityDeathRate(pastureList, startTime, endTime)
  116. case model.AvgAgeFirstMate:
  117. pastureIndicatorList = e.AvgAgeFirstMate(pastureList, startTime, endTime)
  118. case model.YouthPregnantRate:
  119. pastureIndicatorList = e.CowPregnantRate(pastureList, indicatorsDetail.Kind)
  120. case model.MultiparityPregnantRate:
  121. pastureIndicatorList = e.CowPregnantRate(pastureList, indicatorsDetail.Kind)
  122. case model.MultipartyFirstCheckRate:
  123. pastureIndicatorList = e.PregnantCheckRate(pastureList, startTime, endTime, true, model.PregnantCheckForFirst)
  124. case model.MultipartySecondCheckRate:
  125. pastureIndicatorList = e.PregnantCheckRate(pastureList, startTime, endTime, true, model.PregnantCheckForSecond)
  126. case model.YouthFirstCheckRate:
  127. pastureIndicatorList = e.PregnantCheckRate(pastureList, startTime, endTime, false, model.PregnantCheckForFirst)
  128. case model.YouthSecondCheckRate:
  129. pastureIndicatorList = e.PregnantCheckRate(pastureList, startTime, endTime, false, model.PregnantCheckForSecond)
  130. case model.ForbiddenCowNumber:
  131. pastureIndicatorList = e.ForbiddenCowNumber(pastureList, startTime, endTime)
  132. case model.AvgRegistrationDays:
  133. pastureIndicatorList = e.AvgRegistrationDays(pastureList)
  134. case model.AvgPregnancyDays:
  135. pastureIndicatorList = e.AvgPregnancyDays(pastureList, startTime, endTime)
  136. case model.AvgGestationalAge:
  137. pastureIndicatorList = e.AvgGestationalAge(pastureList)
  138. case model.Month17UnPregnancyRate:
  139. pastureIndicatorList = e.MonthUnPregnancyRate(pastureList, 17)
  140. case model.Month20UnPregnancyRate:
  141. pastureIndicatorList = e.MonthUnPregnancyRate(pastureList, 20)
  142. case model.Multiparty150DaysUnPregnancyRate:
  143. pastureIndicatorList = e.Multiparty150DaysUnPregnancyRate(pastureList, 150)
  144. case model.MultipartyAbortionNumber:
  145. pastureIndicatorList = e.MultipartyAbortionNumber(pastureList, startTime, endTime, pasturePb.IsShow_No)
  146. case model.MultipartyPregnancyNumber:
  147. pastureIndicatorList = e.MultipartyPregnancyNumber(pastureList)
  148. case model.MultipartyAbortionRate:
  149. pastureIndicatorList = e.MultipartyAbortionRate(pastureList, startTime, endTime)
  150. case model.MultipartyOutNumber:
  151. pastureIndicatorList = e.MultipartyOutNumber(pastureList, startTime, endTime)
  152. case model.MultipartyDieNumber:
  153. pastureIndicatorList = e.MultipartyDieNumber(pastureList, startTime, endTime)
  154. case model.Calving60DieRate:
  155. pastureIndicatorList = e.CalvingDieRate(pastureList, startTime, endTime, 60)
  156. case model.Calving60OutRate:
  157. pastureIndicatorList = e.CalvingOutRate(pastureList, startTime, endTime, 60)
  158. case model.AvgDepartureWeight:
  159. pastureIndicatorList = e.AvgDepartureWeight(pastureList, startTime, endTime)
  160. case model.AvgSlaughterCycle:
  161. pastureIndicatorList = e.AvgSlaughterCycle(pastureList, startTime, endTime)
  162. case model.SurvivalLiveRate:
  163. pastureIndicatorList = e.SurvivalLiveRate(pastureList, startTime, endTime, 262)
  164. case model.StillbirthRate:
  165. pastureIndicatorList = e.StillbirthRate(pastureList, startTime, endTime)
  166. case model.FemaleCalfRate:
  167. pastureIndicatorList = e.FemaleCalfRate(pastureList, startTime, endTime)
  168. case model.WeaningDailyWeight:
  169. pastureIndicatorList = e.WeaningDailyWeight(pastureList, startTime, endTime)
  170. case model.Day60DieRate:
  171. pastureIndicatorList = e.DayDieRate(pastureList, startTime, endTime, 60)
  172. case model.AdultPrematureBirthRate:
  173. pastureIndicatorList = e.PrematureBirthRate(pastureList, startTime, endTime, 60, true)
  174. case model.YouthPrematureBirthRate:
  175. pastureIndicatorList = e.PrematureBirthRate(pastureList, startTime, endTime, 60, false)
  176. case model.LessThan6monthCalfNumber:
  177. pastureIndicatorList = e.LessThan6monthCalfNumber(pastureList, startTime, endTime)
  178. case model.AdultCowsPregnancyRate:
  179. pastureIndicatorList = e.AdultCowsPregnancyRate(pastureList, startTime, endTime)
  180. case model.Lact1PregnancyRate:
  181. pastureIndicatorList = e.LactPregnancyRate(pastureList, "lact = 1", startTime, endTime)
  182. case model.Lact2PregnancyRate:
  183. pastureIndicatorList = e.LactPregnancyRate(pastureList, "lact = 2", startTime, endTime)
  184. case model.Lact3PregnancyRate:
  185. pastureIndicatorList = e.LactPregnancyRate(pastureList, "lact >= 3", startTime, endTime)
  186. case model.FirstMatingPregnancyRate:
  187. pastureIndicatorList = e.MatingPregnancyRate(pastureList, model.FirstMatingPregnancyRate, startTime, endTime)
  188. case model.SecondMatingPregnancyRate:
  189. pastureIndicatorList = e.MatingPregnancyRate(pastureList, model.SecondMatingPregnancyRate, startTime, endTime)
  190. case model.Day75DayMatingRate:
  191. pastureIndicatorList = e.Day75DayMatingRate(pastureList)
  192. case model.Day75DMonthMatingRate:
  193. pastureIndicatorList = e.Day75MonthMatingRate(pastureList, indicatorsDetail.Id)
  194. case model.AvgAdultCowEmptyNumber:
  195. pastureIndicatorList = e.AvgAdultCowEmptyNumber(pastureList, startTime, endTime)
  196. case model.AdultCowPregnantCheckOkRate:
  197. pastureIndicatorList = e.CowPregnantCheckOkRate(pastureList, "lact >= 1", startTime, endTime)
  198. case model.YouthCowPregnantCheckOkRate:
  199. pastureIndicatorList = e.CowPregnantCheckOkRate(pastureList, "lact = 0", startTime, endTime)
  200. case model.AdultCowForbiddenMatingRate:
  201. pastureIndicatorList = e.CowForbiddenMatingRate(pastureList, "calving_age >=", startTime, endTime)
  202. case model.YouthCowForbiddenMatingRate:
  203. pastureIndicatorList = e.CowForbiddenMatingRate(pastureList, "day_age >= 395", startTime, endTime)
  204. case model.AdultCowForbiddenMatingNumber:
  205. pastureIndicatorList = e.CowForbiddenMatingNumber(pastureList, "lact >= 1", startTime, endTime)
  206. case model.YouthCowForbiddenMatingNumber:
  207. pastureIndicatorList = e.CowForbiddenMatingNumber(pastureList, "lact = 0", startTime, endTime)
  208. }
  209. for pastureId, value := range pastureIndicatorList {
  210. e.UpdatePastureIndicators(pastureId, indicatorsDetail, startTime, value)
  211. }
  212. }
  213. return nil
  214. }
  215. // UpdateCowInfo 牛只基本信息维护
  216. func (e *Entry) UpdateCowInfo() error {
  217. pastureList := e.FindPastureList()
  218. for _, pasture := range pastureList {
  219. e.UpdateCowInfoByPasture(pasture.Id)
  220. }
  221. e.CreateCrontabLog(UpdateCowInfo)
  222. return nil
  223. }
  224. func (e *Entry) UpdateCowInfoByPasture(pastureId int64) {
  225. if ok := e.IsExistCrontabLog(UpdateCowInfo); ok {
  226. return
  227. }
  228. cowList := make([]*model.Cow, 0)
  229. if err := e.DB.Model(new(model.Cow)).
  230. Where("pasture_id = ?", pastureId).
  231. Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
  232. Find(&cowList).Error; err != nil {
  233. zaplog.Error("crontab", zap.Any("UpdateCowInfoByPasture", err))
  234. return
  235. }
  236. dateTime := time.Now().Local().Format(model.LayoutMonth)
  237. for _, cow := range cowList {
  238. // 周活动量
  239. weeklyActive := e.UpdateCowWeeklyHigh(pastureId, cow)
  240. zaplog.Info("crontab", zap.Any("weeklyActive", weeklyActive))
  241. cow.EventUpdate(weeklyActive)
  242. if err := e.DB.Model(new(model.Cow)).
  243. Select("day_age", "calving_age", "pregnancy_age", "admission_age", "abortion_age", "cow_type", "weekly_active", "lactation_age", "dry_milk_age", "mating_age").
  244. Where("id = ?", cow.Id).
  245. Updates(cow).Error; err != nil {
  246. zaplog.Error("Crontab", zap.Any("UpdateCowDayAge", err))
  247. }
  248. // 每月怀孕数据
  249. cowPregnantList := make([]*model.CowPregnant, 0)
  250. if cow.IsPregnant == pasturePb.IsShow_Ok || cow.BreedStatus == pasturePb.BreedStatus_Pregnant {
  251. cowPregnantList = append(cowPregnantList, model.NewCowPregnant(pastureId, cow, dateTime))
  252. }
  253. if len(cowPregnantList) > 0 {
  254. if err := e.DB.Model(new(model.CowPregnant)).
  255. Where("pasture_id = ?", pastureId).
  256. Where("date_time = ?", dateTime).
  257. Delete(new(model.CowPregnant)).Error; err != nil {
  258. zaplog.Error("Crontab", zap.Any("UpdateCowPregnant", err))
  259. }
  260. if err := e.DB.Model(new(model.CowPregnant)).
  261. Create(&cowPregnantList).Error; err != nil {
  262. zaplog.Error("Crontab", zap.Any("UpdateCowPregnant", err))
  263. }
  264. }
  265. }
  266. }
  267. // ImmunizationPlan 免疫计划,生成工作单
  268. func (e *Entry) ImmunizationPlan() error {
  269. if ok := e.IsExistCrontabLog(ImmunizationPlan); ok {
  270. return nil
  271. }
  272. planList := make([]*model.ImmunizationPlan, 0)
  273. if err := e.DB.Model(new(model.ImmunizationPlan)).
  274. Where("is_show = ?", pasturePb.IsShow_Ok).
  275. Order("pasture_id").
  276. Find(&planList).Error; err != nil {
  277. return xerr.WithStack(err)
  278. }
  279. var todayCount int32 = 0
  280. nowTime := time.Now().Local()
  281. for _, plan := range planList {
  282. cowList := make([]*model.Cow, 0)
  283. pref := e.DB.Table(fmt.Sprintf("%s as a", new(model.Cow).TableName())).
  284. Select("a.*").
  285. Where("a.pasture_id = ?", plan.PastureId).
  286. Where("a.admission_status = ?", pasturePb.AdmissionStatus_Admission).
  287. 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())
  288. if plan.CowType > 0 {
  289. pref.Where("a.cow_type = ?", plan.CowType)
  290. }
  291. switch plan.Conditions {
  292. case pasturePb.ImmunizationConditions_Days_Age:
  293. pref.Where("a.day_age = ?", plan.Value)
  294. case pasturePb.ImmunizationConditions_Days_After_Delivery:
  295. pref.Where("a.calving_age = ?", plan.Value)
  296. case pasturePb.ImmunizationConditions_Days_Of_Pregnancy:
  297. pref.Where("a.pregnancy_age = ?", plan.Value).
  298. Where("a.is_pregnant = ?", pasturePb.IsShow_Ok)
  299. case pasturePb.ImmunizationConditions_Month:
  300. continue
  301. case pasturePb.ImmunizationConditions_Admission_Days:
  302. pref.Where("a.admission_age = ?", plan.Value)
  303. case pasturePb.ImmunizationConditions_Other_Vaccine_After:
  304. if plan.ImmunizationPlanId > 0 {
  305. pref.Joins("INNER JOIN event_immunization_plan as b ON b.plan_id = ? ", plan.ImmunizationPlanId).
  306. Where("b.cow_id = a.id").
  307. Where("DATE_ADD(b.reality_day, INTERVAL ? DAY) = ?", plan.Value, time.Now().Local().Format(model.LayoutDate2)).
  308. Where("b.status = ?", pasturePb.IsShow_Ok)
  309. }
  310. }
  311. if err := pref.Find(&cowList).Debug().Error; err != nil {
  312. return xerr.WithStack(err)
  313. }
  314. if len(cowList) <= 0 {
  315. continue
  316. }
  317. newImmunizationPlanCowList := model.NewCowImmunizationPlanList(cowList, plan)
  318. if err := e.DB.Model(new(model.EventImmunizationPlan)).Create(newImmunizationPlanCowList).Error; err != nil {
  319. zaplog.Error("ImmunizationPlan",
  320. zap.Any("err", err),
  321. zap.Any("plan", plan),
  322. zap.Any("cowList", cowList),
  323. zap.Any("newImmunizationPlanCowList", newImmunizationPlanCowList),
  324. )
  325. return xerr.WithStack(err)
  326. }
  327. todayCount = int32(len(newImmunizationPlanCowList))
  328. if todayCount > 0 {
  329. endDay := nowTime.AddDate(0, 0, model.CalendarTypeEndDaysMap[pasturePb.CalendarType_Immunisation])
  330. e.CreatedCalendar(plan.PastureId, pasturePb.CalendarType_Immunisation, nowTime.Format(model.LayoutDate2), endDay.Format(model.LayoutDate2), todayCount)
  331. }
  332. e.CreateCrontabLog(ImmunizationPlan)
  333. }
  334. return nil
  335. }
  336. // SameTimePlan 同期计划,生成工作单
  337. func (e *Entry) SameTimePlan() error {
  338. if ok := e.IsExistCrontabLog(SameTimePlan); ok {
  339. return nil
  340. }
  341. sameTimeList := make([]*model.SameTime, 0)
  342. if err := e.DB.Model(new(model.SameTime)).
  343. Where("is_show = ?", pasturePb.IsShow_Ok).
  344. Order("pasture_id").
  345. Find(&sameTimeList).Error; err != nil {
  346. return xerr.WithStack(err)
  347. }
  348. if len(sameTimeList) < 0 {
  349. return nil
  350. }
  351. defer func() {
  352. e.CreateCrontabLog(SameTimePlan)
  353. }()
  354. currWeek := time.Now().Local().Weekday()
  355. for _, sameTime := range sameTimeList {
  356. if len(sameTime.WeekType) <= 0 {
  357. continue
  358. }
  359. wts := strings.Split(sameTime.WeekType, model.WeekTypeSeparator)
  360. if len(wts) <= 0 {
  361. continue
  362. }
  363. var info bool
  364. for _, wt := range wts {
  365. if time.Weekday(int(pasturePb.Week_Kind_value[wt])) == currWeek {
  366. info = true
  367. break
  368. }
  369. }
  370. if !info {
  371. continue
  372. }
  373. cowList := make([]*model.Cow, 0)
  374. pref := e.DB.Model(new(model.Cow)).
  375. Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
  376. Where("sex = ?", pasturePb.Genders_Female).
  377. Where("pasture_id = ?", sameTime.PastureId).
  378. Where("is_pregnant = ?", pasturePb.IsShow_No)
  379. switch sameTime.CowType {
  380. case pasturePb.SameTimeCowType_Breeding_Calf:
  381. pref.Where("calving_age BETWEEN ? AND ?", sameTime.PostpartumDaysStart, sameTime.PostpartumDaysEnd).
  382. Where("lact > ?", 0)
  383. case pasturePb.SameTimeCowType_Empty:
  384. pref.Where(
  385. e.DB.Where("breed_status = ?", pasturePb.BreedStatus_Empty).
  386. Or("breed_status = ?", pasturePb.BreedStatus_Abort),
  387. )
  388. default:
  389. continue
  390. }
  391. if err := pref.Where(`NOT EXISTS (SELECT 1 FROM event_cow_same_time WHERE event_cow_same_time.cow_id = cow.id
  392. AND event_cow_same_time.status = ?)`, pasturePb.IsShow_No).
  393. Find(&cowList).Error; err != nil {
  394. zaplog.Error("crontab", zap.Any("err", err), zap.Any("sameTime", sameTime))
  395. return xerr.WithStack(err)
  396. }
  397. if len(cowList) <= 0 {
  398. continue
  399. }
  400. if err := e.GenerateCalendarBySameTimePlan(cowList, sameTime); err != nil {
  401. zaplog.Error("crontab",
  402. zap.Any("GenerateCalendarBySameTimePlan", err),
  403. zap.Any("cowList", cowList),
  404. zap.Any("plan", sameTime),
  405. )
  406. continue
  407. }
  408. }
  409. return nil
  410. }
  411. // UpdateSameTime 更新每天同期数据
  412. func (e *Entry) UpdateSameTime() error {
  413. calendarTypeList := backend.CalendarTypeEnumList("")
  414. showDay := time.Now().Local().Format(model.LayoutDate2)
  415. for _, v := range calendarTypeList {
  416. count := int64(0)
  417. if err := e.DB.Model(new(model.EventCowSameTime)).
  418. Where("same_time_type = ?", v.Value).
  419. Where("status = ?", pasturePb.IsShow_No).
  420. Count(&count).Error; err != nil {
  421. zaplog.Error("crontab", zap.Any("UpdateSameTime", err), zap.Any("count", count))
  422. }
  423. if count >= 0 {
  424. continue
  425. }
  426. isExist := int64(0)
  427. if err := e.DB.Model(new(model.Calendar)).
  428. Where("calendar_type = ?", v.Value).
  429. Where("show_day = ?", showDay).
  430. Count(&isExist).Error; err != nil {
  431. continue
  432. }
  433. if isExist <= 0 {
  434. continue
  435. }
  436. if err := e.DB.Model(new(model.Calendar)).
  437. Where("calendar_type = ?", v.Value).
  438. Where("show_day = ?", showDay).
  439. Updates(map[string]interface{}{
  440. "count": count,
  441. }).Error; err != nil {
  442. continue
  443. }
  444. }
  445. return nil
  446. }
  447. // SystemBasicCrontab 基础配置计划任务
  448. func (e *Entry) SystemBasicCrontab() error {
  449. if ok := e.IsExistCrontabLog(SystemBasicCrontab); ok {
  450. return nil
  451. }
  452. defer func() {
  453. e.CreateCrontabLog(SystemBasicCrontab)
  454. }()
  455. systemBasicList := make([]*model.SystemBasic, 0)
  456. if err := e.DB.Model(new(model.SystemBasic)).
  457. Where("is_show = ?", pasturePb.IsShow_Ok).
  458. Where("name IN ?", []string{
  459. model.PregnantCheckForFirst,
  460. model.PregnantCheckForSecond,
  461. model.WeaningAge,
  462. model.PregnancyAge,
  463. model.DryMilkAge,
  464. }).Order("pasture_id").
  465. Find(&systemBasicList).Error; err != nil {
  466. zaplog.Error("crontab", zap.Any("PregnancyCheck", err))
  467. return xerr.WithStack(err)
  468. }
  469. currWeekValue := time.Now().Local().Weekday()
  470. for _, systemBasic := range systemBasicList {
  471. // 周执行
  472. if systemBasic.Name == model.PregnantCheckForFirst && systemBasic.WeekValue >= 0 &&
  473. time.Weekday(systemBasic.WeekValue) != currWeekValue {
  474. continue
  475. }
  476. cowList := make([]*model.Cow, 0)
  477. pref := e.DB.Model(new(model.Cow)).
  478. Where("admission_status = ? ", pasturePb.AdmissionStatus_Admission).
  479. Where("pasture_id = ?", systemBasic.PastureId)
  480. switch systemBasic.Name {
  481. case model.PregnantCheckForFirst: // 初检清单
  482. pref.Where("breed_status = ?", pasturePb.BreedStatus_Breeding).
  483. Where("last_mating_at > ?", 0).
  484. Where("DATE(FROM_UNIXTIME(last_mating_at)) BETWEEN DATE_SUB(CURDATE(), INTERVAL ? DAY) AND DATE_SUB(CURDATE(), INTERVAL ? DAY)", systemBasic.MaxValue, systemBasic.MinValue).
  485. Where(`NOT EXISTS (SELECT 1 FROM event_pregnant_check WHERE event_pregnant_check.cow_id = cow.id
  486. AND event_pregnant_check.status = ? AND event_pregnant_check.pregnant_check_name = ?)`, pasturePb.IsShow_No, model.PregnantCheckForFirst)
  487. case model.PregnantCheckForSecond: // 复检清单 过滤初检空怀的牛只
  488. pref.Where("breed_status IN (?)", []pasturePb.BreedStatus_Kind{pasturePb.BreedStatus_Pregnant}).
  489. Where("last_mating_at > ?", 0).
  490. Where("DATE(FROM_UNIXTIME(last_mating_at)) = DATE_SUB(CURDATE(), INTERVAL ? DAY)", systemBasic.MinValue).
  491. Where(`NOT EXISTS (SELECT 1 FROM event_pregnant_check WHERE event_pregnant_check.cow_id = cow.id
  492. AND event_pregnant_check.status = ? AND event_pregnant_check.pregnant_check_name = ? )`, pasturePb.IsShow_No, model.PregnantCheckForSecond)
  493. case model.WeaningAge: // 断奶清单
  494. pref.Where("day_age = ?", systemBasic.MinValue).
  495. Where("NOT EXISTS (SELECT 1 FROM event_weaning WHERE event_weaning.cow_id = cow.id AND event_weaning.status = ?)", pasturePb.IsShow_No)
  496. case model.PregnancyAge: // 产犊清单
  497. pref.Where("pregnancy_age BETWEEN ? AND ?", systemBasic.MinValue, systemBasic.MaxValue).
  498. Where("breed_status = ?", pasturePb.BreedStatus_Pregnant).
  499. Where("NOT EXISTS (SELECT 1 FROM event_calving WHERE event_calving.cow_id = cow.id AND event_calving.status = ?)", pasturePb.IsShow_No)
  500. case model.DryMilkAge: // 干奶清单
  501. pref.Where("pregnancy_age BETWEEN ? AND ?", systemBasic.MinValue, systemBasic.MaxValue).
  502. Where("breed_status = ?", pasturePb.BreedStatus_Pregnant).
  503. Where("is_pregnant = ?", pasturePb.IsShow_Ok).
  504. 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)
  505. default:
  506. continue
  507. }
  508. if err := pref.Find(&cowList).Error; err != nil {
  509. zaplog.Error("crontab", zap.Any("PregnancyCheck", err), zap.Any("cowList", cowList))
  510. continue
  511. }
  512. if len(cowList) <= 0 {
  513. continue
  514. }
  515. e.InitEventData(cowList, systemBasic)
  516. }
  517. return nil
  518. }
  519. func (e *Entry) DeleteOldOriginal() error {
  520. if err := e.DB.Model(new(model.NeckRingOriginal)).
  521. Where("active_date <= ?", time.Now().Local().AddDate(0, 0, -15).Format(model.LayoutDate2)).
  522. Delete(&model.NeckRingOriginal{}).Error; err != nil {
  523. zaplog.Error("crontab", zap.Any("DeleteOldOriginal", err))
  524. }
  525. if err := e.DB.Model(new(model.NeckActiveHabit)).
  526. Where("heat_date <= ?", time.Now().Local().AddDate(0, -3, 0).Format(model.LayoutDate2)).
  527. Delete(&model.NeckActiveHabit{}).Error; err != nil {
  528. zaplog.Error("crontab", zap.Any("DeleteNeckActiveHabit", err))
  529. }
  530. return nil
  531. }
  532. // UpdateDiseaseToCalendar 更新每天治疗中牛头数到日历表中
  533. func (e *Entry) UpdateDiseaseToCalendar() error {
  534. pastureList := e.FindPastureList()
  535. for _, pasture := range pastureList {
  536. // 更新每天治疗中牛头数到日历表中
  537. var count int64
  538. if err := e.DB.Model(new(model.EventCowDisease)).
  539. Where("pasture_id = ?", pasture.Id).
  540. Where("health_status IN (?)", []pasturePb.HealthStatus_Kind{pasturePb.HealthStatus_Disease, pasturePb.HealthStatus_Treatment}).
  541. Count(&count).Error; err != nil {
  542. zaplog.Error("crontab", zap.Any("UpdateDisease", err))
  543. }
  544. if count > 0 {
  545. calendarTypeName := backend.CalendarTypeMap()[pasturePb.CalendarType_Disease]
  546. startDay := time.Now().Local().Format(model.LayoutDate2)
  547. newCalendar := model.NewCalendar(pasture.Id, calendarTypeName, pasturePb.CalendarType_Disease, startDay, startDay, int32(count))
  548. if err := e.DB.Model(new(model.Calendar)).
  549. Create(newCalendar).Error; err != nil {
  550. zaplog.Error("crontab", zap.Any("UpdateDisease", err))
  551. }
  552. }
  553. }
  554. return nil
  555. }
  556. func (e *Entry) InitEventData(cowList []*model.Cow, systemBasic *model.SystemBasic) {
  557. calendarType := pasturePb.CalendarType_Invalid
  558. nowTime := time.Now().Local()
  559. startDay, endDay := "", ""
  560. switch systemBasic.Name {
  561. case model.PregnantCheckForFirst, model.PregnantCheckForSecond:
  562. penMap, _ := e.GetPenMapList(systemBasic.PastureId)
  563. calendarType = pasturePb.CalendarType_Pregnancy_Check
  564. startDay, endDay = nowTime.Format(model.LayoutDate2), nowTime.AddDate(0, 0, model.CalendarTypeEndDaysMap[calendarType]).Format(model.LayoutDate2)
  565. eventPregnantCheckDataList := model.NewEventPregnantCheckList(systemBasic.PastureId, cowList, penMap, systemBasic.Name, startDay, endDay)
  566. if err := e.DB.Model(new(model.EventPregnantCheck)).Create(eventPregnantCheckDataList).Error; err != nil {
  567. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventPregnantCheckDataList", eventPregnantCheckDataList))
  568. return
  569. }
  570. case model.WeaningAge:
  571. calendarType = pasturePb.CalendarType_Weaning
  572. startDay, endDay = nowTime.Format(model.LayoutDate2), nowTime.AddDate(0, 0, model.CalendarTypeEndDaysMap[calendarType]).Format(model.LayoutDate2)
  573. eventWeaningDataList := model.NewEventWeaningList(systemBasic.PastureId, cowList, startDay, endDay)
  574. if err := e.DB.Model(new(model.EventWeaning)).
  575. Create(eventWeaningDataList).Error; err != nil {
  576. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventWeaningDataList", eventWeaningDataList))
  577. return
  578. }
  579. case model.PregnancyAge:
  580. calendarType = pasturePb.CalendarType_Calving
  581. startDay, endDay = nowTime.Format(model.LayoutDate2), nowTime.AddDate(0, 0, model.CalendarTypeEndDaysMap[calendarType]).Format(model.LayoutDate2)
  582. eventCalvingList := model.NewEventCalvingList(systemBasic.PastureId, cowList, startDay, endDay)
  583. if err := e.DB.Model(new(model.EventCalving)).Create(eventCalvingList).Error; err != nil {
  584. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventCalvingList", eventCalvingList))
  585. return
  586. }
  587. case model.DryMilkAge:
  588. calendarType = pasturePb.CalendarType_DryMilk
  589. startDay, endDay = nowTime.Format(model.LayoutDate2), nowTime.AddDate(0, 0, model.CalendarTypeEndDaysMap[calendarType]).Format(model.LayoutDate2)
  590. eventCalvingList := model.NewEventDryMilkList(systemBasic.PastureId, cowList, startDay, endDay)
  591. if err := e.DB.Model(new(model.EventDryMilk)).Create(eventCalvingList).Error; err != nil {
  592. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventCalvingList", eventCalvingList))
  593. return
  594. }
  595. }
  596. e.CreatedCalendar(systemBasic.PastureId, calendarType, startDay, endDay, int32(len(cowList)))
  597. }
  598. // UpdateCowWeeklyHigh 更新牛只周活动量
  599. func (e *Entry) UpdateCowWeeklyHigh(pastureId int64, cow *model.Cow) int32 {
  600. highData, err := e.GetSystemNeckRingConfigure(pastureId, model.High)
  601. if err != nil || highData == nil || highData.Value <= 0 {
  602. return 0
  603. }
  604. minWeeklyActive, er := e.GetSystemNeckRingConfigure(pastureId, model.MinWeeklyActive)
  605. if er != nil || minWeeklyActive == nil || minWeeklyActive.Value <= 0 {
  606. return 0
  607. }
  608. weeklyActiveModelList := make([]*model.WeeklyActiveModel, 0)
  609. startTime := time.Now().Local().AddDate(0, 0, -7).Format(model.LayoutDate2)
  610. endTime := time.Now().Local().AddDate(0, 0, -1).Format(model.LayoutDate2)
  611. 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)
  612. if err = e.DB.Model(new(model.NeckActiveHabit)).
  613. Select(selectStr).
  614. Where("pasture_id = ?", pastureId).
  615. Where("cow_id = ?", cow.Id).
  616. Where("heat_date BETWEEN ? AND ?", startTime, endTime).
  617. Where("high > ?", highData.Value).
  618. Having("nb > ?", 8).
  619. Order("high").
  620. Group("heat_date").
  621. Find(&weeklyActiveModelList).Error; err != nil {
  622. zaplog.Error("crontab", zap.Any("UpdateCowWeeklyHigh", err))
  623. return 0
  624. }
  625. if len(weeklyActiveModelList) < 3 {
  626. return 0
  627. }
  628. // 1. 先按High值排序
  629. sort.Slice(weeklyActiveModelList, func(i, j int) bool {
  630. return weeklyActiveModelList[i].High < weeklyActiveModelList[j].High
  631. })
  632. countHigh := len(weeklyActiveModelList)
  633. sumHigh := int32(0)
  634. minHigh := weeklyActiveModelList[0].High
  635. maxHigh := weeklyActiveModelList[len(weeklyActiveModelList)-1].High
  636. for _, v := range weeklyActiveModelList {
  637. sumHigh += v.High
  638. }
  639. diff := 0
  640. x := int32(0)
  641. if countHigh > 3 {
  642. diff = 3
  643. x = weeklyActiveModelList[1].High
  644. } else if countHigh == 3 {
  645. diff = 2
  646. } else {
  647. return 0
  648. }
  649. avgHigh := float64(sumHigh-minHigh-maxHigh-x) / float64(countHigh-diff)
  650. return int32(avgHigh)
  651. }