cow_cron.go 25 KB

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