cow_cron.go 17 KB

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