Browse Source

crontab: isPeak update

Yi 2 days ago
parent
commit
65e34c5c18
4 changed files with 52 additions and 57 deletions
  1. 1 0
      module/backend/cow.go
  2. 21 33
      module/crontab/neck_ring_estrus.go
  3. 30 23
      util/util_test.go
  4. 0 1
      util/util_test1.go

+ 1 - 0
module/backend/cow.go

@@ -302,6 +302,7 @@ func (s *StoreEntry) BehaviorCurve(ctx context.Context, req *pasturePb.CowBehavi
 		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Where("active_time BETWEEN ? AND ?", fmt.Sprintf("%s 00:00:00", startDataTime), fmt.Sprintf("%s 23:59:59", endDataTime)).
 		Where("is_peak = ?", pasturePb.IsShow_Ok).
+		Group("first_time").
 		Find(&estrusList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}

+ 21 - 33
module/crontab/neck_ring_estrus.go

@@ -4,6 +4,7 @@ import (
 	"fmt"
 	"kpt-pasture/model"
 	"kpt-pasture/util"
+	"sort"
 	"time"
 
 	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
@@ -70,8 +71,10 @@ func (e *Entry) EntryCowEstrus(pastureId int64) (err error) {
 func (e *Entry) CowEstrusWarning(pastureId int64, xToday *XToday, nowTime time.Time) {
 	cft := xToday.ActiveLow - XAdjust21
 	neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
+	habitStartDate := nowTime.AddDate(0, 0, -1).Format(model.LayoutDate2)
+	habitEndDate := nowTime.Format(model.LayoutDate2)
 	if err := e.DB.Model(new(model.NeckActiveHabit)).
-		Where("heat_date BETWEEN ? AND ?", nowTime.AddDate(0, 0, -1).Format(model.LayoutDate2), nowTime.Format(model.LayoutDate2)).
+		Where("heat_date BETWEEN ? AND ?", habitStartDate, habitEndDate). // todo 查询的时间范围可以优化成当前时间的前12个小时的
 		Where("pasture_id = ?", pastureId).
 		Where("filter_high > 0 AND change_filter > ?", model.DefaultChangeFilter).
 		Where("cow_id > ?", 0).
@@ -85,7 +88,6 @@ func (e *Entry) CowEstrusWarning(pastureId int64, xToday *XToday, nowTime time.T
 
 	neckActiveHabitMap := make(map[int64][]*model.NeckActiveHabit)
 	for _, habit := range neckActiveHabitList {
-		zaplog.Info("CowEstrusWarning", zap.Any("habit", habit))
 		if neckActiveHabitMap[habit.CowId] == nil {
 			neckActiveHabitMap[habit.CowId] = make([]*model.NeckActiveHabit, 0)
 		}
@@ -95,10 +97,12 @@ func (e *Entry) CowEstrusWarning(pastureId int64, xToday *XToday, nowTime time.T
 	neckRingEstrusList := make([]*model.NeckRingEstrus, 0)
 	for cowId, cowHabitList := range neckActiveHabitMap {
 		// 最近3天最大发情记录,小于该变化趋势的不再插入
-		before3Data := e.GetBeforeThreeDaysCowEstrus(pastureId, cowId, nowTime.AddDate(0, 0, -2).Format(model.LayoutTime))
-
+		before3StartDate := nowTime.AddDate(0, 0, -2).Format(model.LayoutTime)
+		before3Data := e.GetBeforeThreeDaysCowEstrus(pastureId, cowId, before3StartDate)
 		// 判断最近50天内是否存在发情记录(发情等级>=2),如果18~25天@xadjust21,如果36~50天@xadjust42
-		cow21Estrus := e.GetTwoEstrus(pastureId, cowId, nowTime.AddDate(0, 0, -100).Format(model.LayoutTime), nowTime.AddDate(0, 0, -2).Format(model.LayoutTime))
+		cow21EstrusStartDate := nowTime.AddDate(0, 0, -100).Format(model.LayoutTime)
+		cow21EstrusEndDate := nowTime.AddDate(0, 0, -2).Format(model.LayoutTime)
+		cow21Estrus := e.GetTwoEstrus(pastureId, cowId, cow21EstrusStartDate, cow21EstrusEndDate)
 		if cow21Estrus.ActiveDate != "" {
 			activeDateTime, _ := util.TimeParseLocal(model.LayoutTime, cow21Estrus.ActiveDate)
 			if activeDateTime.Unix() >= nowTime.AddDate(0, 0, -25).Unix() && activeDateTime.Unix() <= nowTime.AddDate(0, 0, -18).Unix() {
@@ -267,10 +271,9 @@ func (e *Entry) UpdateEstrusFirstTime3(pastureId int64, xToday time.Time) {
 func (e *Entry) UpdateEstrusIsPeak(pastureId int64) {
 	neckRingEstrusList := make([]*model.NeckRingEstrus, 0)
 	if err := e.DB.Model(new(model.NeckRingEstrus)).
-		Where("first_time >= ?", time.Now().Local().AddDate(0, 0, -3).Format(model.LayoutTime)).
+		Where("first_time >= ?", time.Now().Local().AddDate(0, 0, -1).Format(model.LayoutTime)).
 		Where("active_time != ?", "").
 		Where("pasture_id = ?", pastureId).
-		Order("cow_id,first_time,active_time ASC").
 		Find(&neckRingEstrusList).Error; err != nil {
 		zaplog.Error("UpdateEstrusIsPeak", zap.Any("Find", err))
 	}
@@ -281,42 +284,36 @@ func (e *Entry) UpdateEstrusIsPeak(pastureId int64) {
 
 	neckRingEstrusFirstMap := make(map[string][]*model.NeckRingEstrus)
 	for _, v := range neckRingEstrusList {
-		if neckRingEstrusFirstMap[fmt.Sprintf("%s_%d", v.FirstTime, v.CowId)] == nil {
-			neckRingEstrusFirstMap[fmt.Sprintf("%s_%d", v.FirstTime, v.CowId)] = make([]*model.NeckRingEstrus, 0)
+		prefix := fmt.Sprintf("%s_%d", v.FirstTime, v.CowId)
+		if neckRingEstrusFirstMap[prefix] == nil {
+			neckRingEstrusFirstMap[prefix] = make([]*model.NeckRingEstrus, 0)
 		}
-		neckRingEstrusFirstMap[fmt.Sprintf("%s_%d", v.FirstTime, v.CowId)] = append(neckRingEstrusFirstMap[fmt.Sprintf("%s_%d", v.FirstTime, v.CowId)], v)
+		neckRingEstrusFirstMap[prefix] = append(neckRingEstrusFirstMap[prefix], v)
 	}
 
 	nowTime := time.Now().Local()
 	peakIsShow := make([]int64, 0)
-	peakIsNo := make([]int64, 0)
 	for _, estrusItems := range neckRingEstrusFirstMap {
 		eLen := len(estrusItems)
 		if eLen <= 0 {
 			continue
 		}
+		// 倒序排序
+		sort.Slice(estrusItems, func(i, j int) bool {
+			return estrusItems[i].ActiveTime < estrusItems[j].ActiveTime
+		})
 		// 判断是否是高峰期,和当前时间相比,如果超过2个小就是高峰期
 		lastItem := estrusItems[eLen-1]
-		lastActiveTime, err := time.Parse(model.LayoutTime, lastItem.ActiveTime)
-		if err != nil {
-			zaplog.Error("UpdateEstrusIsPeak", zap.Any("Parse", err), zap.Any("lastItem", lastItem))
-			continue
-		}
-		sub := nowTime.Sub(lastActiveTime.Local()).Hours()
-		if sub > 2 {
+		lastActiveTime := util.DateTimeParseLocalUnix2(lastItem.ActiveTime)
+		sub := nowTime.Sub(lastActiveTime).Hours()
+		if sub > 4 && lastItem.IsPeak == pasturePb.IsShow_No {
 			peakIsShow = append(peakIsShow, lastItem.Id)
-			for i := 0; i < eLen-1; i++ {
-				peakIsNo = append(peakIsNo, estrusItems[i].Id)
-			}
-		} else {
-			peakIsNo = append(peakIsNo, lastItem.Id)
 		}
 	}
 
 	zaplog.Info("UpdateEstrusIsPeak",
 		zap.Any("pastureId", pastureId),
 		zap.Any("peakIsShow", peakIsShow),
-		zap.Any("peakIsNo", peakIsNo),
 	)
 
 	if len(peakIsShow) > 0 {
@@ -327,15 +324,6 @@ func (e *Entry) UpdateEstrusIsPeak(pastureId int64) {
 			zaplog.Error("UpdateEstrusIsPeak", zap.Any("Update", err))
 		}
 	}
-
-	if len(peakIsNo) > 0 {
-		if err := e.DB.Model(new(model.NeckRingEstrus)).
-			Where("id IN ?", peakIsNo).
-			Where("pasture_id = ?", pastureId).
-			Update("is_peak", pasturePb.IsShow_No).Error; err != nil {
-			zaplog.Error("UpdateEstrusIsPeak", zap.Any("Update", err))
-		}
-	}
 }
 
 // FindCowEstrusFirstTime1 查找牛只昨天是否有发情数据

+ 30 - 23
util/util_test.go

@@ -1,7 +1,9 @@
 package util
 
 import (
+	"encoding/json"
 	"fmt"
+	"sort"
 	"strconv"
 	"strings"
 	"testing"
@@ -535,28 +537,33 @@ type WeeklyActiveModel struct {
 }
 
 func Test_demo(t *testing.T) {
-	/*str := "insert into system_pasture_menu (pasture_id,menu_id,created_at,updated_at) values"
-	for i := 36; i <= 135; i++ {
-		str += fmt.Sprintf("(11,%d,1748922530,1748922530),", i)
-	}
-
-	fmt.Println(strings.TrimRight(str, ","))
-
-	str1 := "insert into system_role_menu (role_id,menu_id,created_at,updated_at) values"
-	for i := 36; i <= 135; i++ {
-		str1 += fmt.Sprintf("(11,%d,1748922530,1748922530),", i)
-	}
-
-	fmt.Println(strings.TrimRight(str1, ","))
-
-	xToday := time.Now().Local()
-	activeTime, _ := TimeParseLocal(LayoutTime, "2025-06-18 03:00:00")
-	if activeTime.Before(xToday) || activeTime.After(xToday.AddDate(0, 0, 1)) {
-		fmt.Println("1")
-	} else {
-		fmt.Println("2")
-	}*/
+	nowTime := time.Now()
+	lastActiveTime := DateTimeParseLocalUnix2("2025-07-17 07:00:00")
+	sub := nowTime.Sub(lastActiveTime).Hours()
+
+	fmt.Println("sub:", sub)
+
+	weeklyActiveModelList := make([]*WeeklyActiveModel, 0)
+	weeklyActiveModelList = append(weeklyActiveModelList, &WeeklyActiveModel{
+		CowId:    1,
+		HeatDate: "2025-07-17 07:00:00",
+		Nb:       1,
+		High:     1,
+	}, &WeeklyActiveModel{
+		CowId:    2,
+		HeatDate: "2025-07-17 05:00:00",
+		Nb:       2,
+		High:     2,
+	}, &WeeklyActiveModel{
+		CowId:    3,
+		HeatDate: "2025-07-17 09:00:00",
+		Nb:       3,
+		High:     3,
+	})
+	sort.Slice(weeklyActiveModelList, func(i, j int) bool {
+		return weeklyActiveModelList[i].HeatDate < weeklyActiveModelList[j].HeatDate
+	})
+	b, _ := json.Marshal(weeklyActiveModelList)
+	fmt.Println(string(b))
 
-	a := float64(3) / 10
-	fmt.Println(a)
 }

+ 0 - 1
util/util_test1.go

@@ -1 +0,0 @@
-package util