cow_cron.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. "gorm.io/gorm"
  10. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  11. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  12. "gitee.com/xuyiping_admin/pkg/xerr"
  13. "go.uber.org/zap"
  14. )
  15. const (
  16. UpdateCowInfo = "UpdateCowInfo"
  17. ImmunizationPlan = "ImmunizationPlan"
  18. SameTimePlan = "SameTimePlan"
  19. WorkOrderMaster = "WorkOrderMaster"
  20. SystemBasicCrontab = "SystemBasicCrontab"
  21. NeckRingOriginal = "NeckRingOriginal"
  22. )
  23. // GenerateAsynqWorkOrder 异步生成工作单
  24. func (e *Entry) GenerateAsynqWorkOrder() error {
  25. if ok := e.IsExistCrontabLog(WorkOrderMaster); ok {
  26. return nil
  27. }
  28. defer func() {
  29. e.CreateCrontabLog(WorkOrderMaster)
  30. }()
  31. workOrderList := make([]*model.WorkOrderMaster, 0)
  32. if err := e.DB.Where("is_show = ?", pasturePb.IsShow_Ok).Find(&workOrderList).Error; err != nil {
  33. return err
  34. }
  35. for _, workOrder := range workOrderList {
  36. timeUnix, err := util.ConvertParseLocalUnix(workOrder.ExecTime)
  37. if timeUnix <= 0 || err != nil {
  38. zaplog.Error("crontab", zap.Any("GenerateWorkOrder", err), zap.Any("execTime", workOrder.ExecTime))
  39. continue
  40. }
  41. nowTime := time.Now().Unix()
  42. if timeUnix < nowTime {
  43. continue
  44. }
  45. execTime := timeUnix - nowTime
  46. task := model.NewTaskWorkOrderPayload(workOrder.Id, time.Duration(execTime)*time.Second)
  47. if _, err = e.AsynqClient.CtxEnqueue(context.Background(), task); err != nil {
  48. zaplog.Error("PushMessage CtxEnqueue", zap.Any("Err", err))
  49. }
  50. }
  51. return nil
  52. }
  53. // UpdateCowInfo 牛只基本信息维护
  54. func (e *Entry) UpdateCowInfo() error {
  55. cowList := make([]*model.Cow, 0)
  56. if err := e.DB.Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).Find(&cowList).Error; err != nil {
  57. return err
  58. }
  59. if ok := e.IsExistCrontabLog(UpdateCowInfo); ok {
  60. return nil
  61. }
  62. defer func() {
  63. e.CreateCrontabLog(UpdateCowInfo)
  64. }()
  65. for _, cow := range cowList {
  66. updates := map[string]interface{}{
  67. "day_age": cow.GetDayAge(),
  68. "calving_at": cow.GetCalvingAge(),
  69. "pregnancy_age": cow.GetDaysPregnant(),
  70. "admission_age": cow.GetAdmissionAge(),
  71. "abortion_age": cow.GetAbortionAge(),
  72. }
  73. if cow.GetDayAge() == 60 {
  74. updates["cow_type"] = pasturePb.CowType_Weaned_Calf
  75. }
  76. if err := e.DB.Model(new(model.Cow)).
  77. Where("id = ?", cow.Id).
  78. Updates(updates).Error; err != nil {
  79. zaplog.Error("Crontab", zap.Any("UpdateCowDayAge", err))
  80. }
  81. }
  82. return nil
  83. }
  84. // ImmunizationPlan 免疫计划,生成工作单
  85. func (e *Entry) ImmunizationPlan() error {
  86. if ok := e.IsExistCrontabLog(ImmunizationPlan); ok {
  87. return nil
  88. }
  89. planList := make([]*model.ImmunizationPlan, 0)
  90. if err := e.DB.Where("is_show = ?", pasturePb.IsShow_Ok).Find(&planList).Error; err != nil {
  91. return xerr.WithStack(err)
  92. }
  93. var todayCount int32 = 0
  94. defer func() {
  95. var count int64 = 0
  96. if err := e.DB.Model(new(model.EventImmunizationPlan)).
  97. Where("status = ?", pasturePb.IsShow_Ok).
  98. Count(&count).Error; err != nil {
  99. zaplog.Error("Crontab", zap.Any("ImmunizationPlanDefer", err))
  100. }
  101. todayCount += int32(count)
  102. if todayCount > 0 {
  103. e.CreatedCalendar(pasturePb.CalendarType_Immunisation, todayCount)
  104. }
  105. e.CreateCrontabLog(ImmunizationPlan)
  106. }()
  107. nowTime := time.Now().Unix()
  108. for _, plan := range planList {
  109. cowList := make([]*model.Cow, 0)
  110. pref := e.DB.Table(fmt.Sprintf("%s as a", new(model.Cow).TableName())).
  111. Select("a.*").
  112. Where("a.admission_status = ?", pasturePb.AdmissionStatus_Admission).
  113. Where("NOT EXIST ( select 1 from event_immunization_plan b where b.pen_id = a.id and b.status = ? and b.plan_day > ?)", plan.Id, pasturePb.IsShow_No, nowTime)
  114. if plan.CowType > 0 {
  115. pref.Where("a.cow_type = ?", plan.CowType)
  116. }
  117. switch plan.Conditions {
  118. case pasturePb.ImmunizationConditions_Days_Age:
  119. pref.Where("a.day_age = ?", plan.Value)
  120. case pasturePb.ImmunizationConditions_Days_After_Delivery:
  121. pref.Where("a.calving_age = ?", plan.Value)
  122. case pasturePb.ImmunizationConditions_Days_Of_Pregnancy:
  123. pref.Where("a.pregnancy_age = ?", plan.Value).
  124. Where("a.is_pregnant = ?", pasturePb.IsShow_Ok)
  125. case pasturePb.ImmunizationConditions_Month:
  126. // todo 待实现月份
  127. continue
  128. case pasturePb.ImmunizationConditions_Admission_Days:
  129. pref.Where("a.admission_age = ?", plan.Value)
  130. case pasturePb.ImmunizationConditions_Other_Vaccine_After:
  131. if plan.ImmunizationPlanId > 0 {
  132. pref.Joins("INNER JOIN event_immunization_plan as b ON b.immunization_plan_id = ? ", plan.ImmunizationPlanId).
  133. Where("b.cow_id = a.id").
  134. Where("DATE_ADD(b.reality_time, INTERVAL ? DAY) = ?", plan.Value, time.Now().Format(model.LayoutDate2)).
  135. Where("b.status = ?", pasturePb.IsShow_Ok)
  136. }
  137. }
  138. if err := pref.Find(&cowList).Error; err != nil {
  139. return xerr.WithStack(err)
  140. }
  141. if len(cowList) <= 0 {
  142. continue
  143. }
  144. todayCount += int32(len(cowList))
  145. penList, _ := e.GetPenMapList()
  146. newImmunizationPlanCowList := model.NewCowImmunizationPlanList(cowList, penList, plan)
  147. newEventItemList := model.NewEventItemList(cowList, pasturePb.CalendarType_Immunisation)
  148. if err := e.DB.Transaction(func(tx *gorm.DB) error {
  149. if err := tx.Create(newImmunizationPlanCowList).Error; err != nil {
  150. return xerr.WithStack(err)
  151. }
  152. if err := tx.Create(newEventItemList).Error; err != nil {
  153. return xerr.WithStack(err)
  154. }
  155. return nil
  156. }); err != nil {
  157. zaplog.Error("ImmunizationPlan", zap.Any("newImmunizationPlanCowList", err), zap.Any("plan", plan), zap.Any("cowList", cowList))
  158. }
  159. }
  160. zaplog.Info("ImmunizationPlan", zap.Any("todayCount", todayCount))
  161. return nil
  162. }
  163. // SameTimePlan 同期计划,生成工作单
  164. func (e *Entry) SameTimePlan() error {
  165. if ok := e.IsExistCrontabLog(SameTimePlan); ok {
  166. return nil
  167. }
  168. sameTimeList := make([]*model.SameTime, 0)
  169. if err := e.DB.Where("is_show = ?", pasturePb.IsShow_Ok).Find(&sameTimeList).Error; err != nil {
  170. return xerr.WithStack(err)
  171. }
  172. // 更新日历里面的数据
  173. var todayCount int32 = 0
  174. defer func() {
  175. if todayCount > 0 {
  176. e.CreatedCalendar(pasturePb.CalendarType_Immunisation, todayCount)
  177. }
  178. e.CreateCrontabLog(SameTimePlan)
  179. }()
  180. currWeek := time.Now().Weekday()
  181. for _, sameTime := range sameTimeList {
  182. if sameTime == nil {
  183. continue
  184. }
  185. if time.Weekday(sameTime.WeekType) != currWeek {
  186. continue
  187. }
  188. cowList := make([]*model.Cow, 0)
  189. pref := e.DB.Model(new(model.Cow)).
  190. Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
  191. Where("sex = ?", pasturePb.Genders_Male)
  192. switch sameTime.CowType {
  193. case pasturePb.SameTimeCowType_Breeding_Calf:
  194. pref.Where("calving_age >= ?", sameTime.PostpartumDaysStart).
  195. Where("calving_age <= ?", sameTime.PostpartumDaysEnd).
  196. Where("is_pregnant = ?", pasturePb.IsShow_No)
  197. case pasturePb.SameTimeCowType_Empty:
  198. pref.Where(
  199. e.DB.Where("breed_status = ?", pasturePb.BreedStatus_Empty).
  200. Or("breed_status = ?", pasturePb.BreedStatus_Abort),
  201. ).Where("is_pregnant = ?", pasturePb.IsShow_No)
  202. default:
  203. continue
  204. }
  205. if err := pref.Find(&cowList).Error; err != nil {
  206. zaplog.Error("crontab", zap.Any("err", err), zap.Any("sameTime", sameTime))
  207. return xerr.WithStack(err)
  208. }
  209. if len(cowList) <= 0 {
  210. continue
  211. }
  212. currCount, err := e.GenerateCalendarBySameTimePlan(cowList, sameTime)
  213. if err != nil {
  214. zaplog.Error("crontab",
  215. zap.Any("GenerateCalendarBySameTimePlan", err),
  216. zap.Any("cowList", cowList),
  217. zap.Any("plan", sameTime),
  218. )
  219. continue
  220. }
  221. todayCount += currCount
  222. }
  223. return nil
  224. }
  225. // UpdateSameTime 更新每天同情数据
  226. func (e *Entry) UpdateSameTime() error {
  227. calendarTypeList := backend.CalendarTypeEnumList("")
  228. showDay := time.Now().Format(model.LayoutDate2)
  229. for _, v := range calendarTypeList {
  230. count := int64(0)
  231. if err := e.DB.Model(new(model.EventCowSameTime)).
  232. Where("same_time_type = ?", v.Value).
  233. Where("status = ?", pasturePb.IsShow_No).
  234. Count(&count).Error; err != nil {
  235. zaplog.Error("crontab", zap.Any("UpdateSameTime", err), zap.Any("count", count))
  236. }
  237. if count >= 0 {
  238. continue
  239. }
  240. isExist := int64(0)
  241. if err := e.DB.Model(new(model.Calendar)).
  242. Where("calendar_type = ?", v.Value).
  243. Where("show_day = ?", showDay).
  244. Count(&isExist).Error; err != nil {
  245. continue
  246. }
  247. if isExist <= 0 {
  248. continue
  249. }
  250. if err := e.DB.Model(new(model.Calendar)).
  251. Where("calendar_type = ?", v.Value).
  252. Where("show_day = ?", showDay).
  253. Updates(map[string]interface{}{
  254. "count": count,
  255. }).Error; err != nil {
  256. continue
  257. }
  258. }
  259. return nil
  260. }
  261. // SystemBasicCrontab 基础配置计划任务
  262. func (e *Entry) SystemBasicCrontab() error {
  263. if ok := e.IsExistCrontabLog(SystemBasicCrontab); ok {
  264. return nil
  265. }
  266. defer func() {
  267. e.CreateCrontabLog(SystemBasicCrontab)
  268. }()
  269. systemBasicList := make([]*model.SystemBasic, 0)
  270. if err := e.DB.Model(new(model.SystemBasic)).
  271. Where("is_show = ?", pasturePb.IsShow_Ok).
  272. Where("name IN ?", []string{
  273. model.PregnantCheckForFirst,
  274. model.PregnantCheckForSecond,
  275. model.WeaningAge,
  276. model.PregnancyAge,
  277. }).Find(&systemBasicList).Error; err != nil {
  278. zaplog.Error("crontab", zap.Any("PregnancyCheck", err))
  279. return xerr.WithStack(err)
  280. }
  281. currWeekValue := time.Now().Weekday()
  282. for _, v := range systemBasicList {
  283. // 周执行
  284. if v.WeekValue >= 0 && time.Weekday(v.WeekValue) != currWeekValue {
  285. continue
  286. }
  287. cowList := make([]*model.Cow, 0)
  288. pref := e.DB.Model(new(model.Cow)).Where("admission_status = ? ", pasturePb.AdmissionStatus_Admission)
  289. switch v.Name {
  290. case model.PregnantCheckForFirst:
  291. pref.Where("breed_status = ?", pasturePb.BreedStatus_Breeding)
  292. case model.PregnantCheckForSecond: // 过滤初检空怀的牛只
  293. pref.Where("breed_status = ?", pasturePb.BreedStatus_Pregnant)
  294. case model.WeaningAge:
  295. pref.Where("day_age = ?", v.MinValue)
  296. case model.PregnancyAge:
  297. pref.Where("pregnancy_age >= ?", v.MinValue).
  298. Where("breed_status = ?", pasturePb.BreedStatus_Pregnant)
  299. default:
  300. continue
  301. }
  302. if v.ValueType == model.ValueTypeFixed {
  303. pref.Where("day_age = ?", v.MinValue)
  304. }
  305. if v.ValueType == model.ValueTypeRange {
  306. pref.Where("day_age >= ?", v.MinValue).Where("day_age <= ?", v.MaxValue)
  307. }
  308. if err := pref.Find(&cowList).Error; err != nil {
  309. zaplog.Error("crontab", zap.Any("PregnancyCheck", err), zap.Any("cowList", cowList))
  310. continue
  311. }
  312. if len(cowList) <= 0 {
  313. continue
  314. }
  315. e.InitEventData(cowList, v.Name)
  316. }
  317. return nil
  318. }
  319. func (e *Entry) InitEventData(cowList []*model.Cow, systemBasicName string) {
  320. switch systemBasicName {
  321. case model.PregnantCheckForFirst, model.PregnantCheckForSecond:
  322. penMap, _ := e.GetPenMapList()
  323. eventPregnantCheckDataList := model.NewEventPregnantCheckList(cowList, penMap, systemBasicName)
  324. if err := e.DB.Create(eventPregnantCheckDataList).Error; err != nil {
  325. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventPregnantCheckDataList", eventPregnantCheckDataList))
  326. }
  327. case model.WeaningAge:
  328. eventWeaningDataList := model.NewEventWeaningList(cowList)
  329. if err := e.DB.Create(eventWeaningDataList).Error; err != nil {
  330. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventWeaningDataList", eventWeaningDataList))
  331. }
  332. case model.PregnancyAge:
  333. eventCalvingList := model.NewEventCalvingList(cowList)
  334. if err := e.DB.Create(eventCalvingList).Error; err != nil {
  335. zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventCalvingList", eventCalvingList))
  336. }
  337. }
  338. }
  339. // DiseaseCheck 疾病检查
  340. func (e *Entry) DiseaseCheck() error {
  341. return nil
  342. }