Browse Source

Merge branch 'feature/event' of http://192.168.1.8:3000/xuyiping/kpt-pasture into feature/event

Yi 1 month ago
parent
commit
0073adae48

+ 0 - 47
model/cow_pregnant.go

@@ -1,47 +0,0 @@
-package model
-
-import pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
-
-type CowPregnant struct {
-	Id           int64                  `json:"id"`
-	PastureId    int64                  `json:"pastureId"`
-	CowId        int64                  `json:"cowId"`
-	Lact         int32                  `json:"lact"`
-	DayAge       int32                  `json:"dayAge"`
-	PenId        int32                  `json:"penId"`
-	AdmissionAge int32                  `json:"admissionAge"`
-	CowType      pasturePb.CowType_Kind `json:"cowType"`
-	PregnancyAge int32                  `json:"pregnancyAge"`
-	CreatedAt    int64                  `json:"createdAt"`
-	UpdatedAt    int64                  `json:"updatedAt"`
-}
-
-func (c *CowPregnant) TableName() string {
-	return "cow_pregnant"
-}
-
-func NewCowPregnant(cow *Cow) *CowPregnant {
-	return &CowPregnant{
-		PastureId:    cow.PastureId,
-		CowId:        cow.Id,
-		Lact:         cow.Lact,
-		DayAge:       cow.DayAge,
-		PenId:        cow.PenId,
-		AdmissionAge: cow.AdmissionAge,
-		CowType:      cow.CowType,
-		PregnancyAge: cow.PregnancyAge,
-	}
-}
-
-func NewCowPregnantList(cow []*Cow) []*CowPregnant {
-	res := make([]*CowPregnant, len(cow))
-	for i, v := range cow {
-		res[i] = NewCowPregnant(v)
-	}
-	return res
-}
-
-type CowPregnantMonth struct {
-	Month    string `json:"month"`
-	CowCount int32  `json:"cowCount"`
-}

+ 8 - 6
model/event_cow_same_time.go

@@ -95,6 +95,7 @@ type SameTimeItemBody struct {
 	LastAbortionAt  int64                       `json:"lastAbortionAt"`
 	MatingTimes     int32                       `json:"matingTimes"`
 	SameTimeName    string                      `json:"sameTimeName"`
+	PlanDay         int64                       `json:"planDay"`
 }
 
 type SameTimeBodySlice []*SameTimeItemBody
@@ -106,11 +107,7 @@ func (s SameTimeBodySlice) ToPB(
 ) []*pasturePb.SameTimeItems {
 	res := make([]*pasturePb.SameTimeItems, len(s))
 	for i, v := range s {
-		penName, calvingAtFormat, abortionAtFormat := "", "", ""
-		if pen, ok := penMap[v.PenId]; ok {
-			penName = pen.Name
-		}
-
+		calvingAtFormat, abortionAtFormat, playDayAtFormat := "", "", ""
 		if v.LastCalvingAt > 0 {
 			calvingAtFormat = time.Unix(v.LastCalvingAt, 0).Format(LayoutDate2)
 		}
@@ -119,13 +116,17 @@ func (s SameTimeBodySlice) ToPB(
 			abortionAtFormat = time.Unix(v.LastAbortionAt, 0).Format(LayoutDate2)
 		}
 
+		if v.PlanDay > 0 {
+			playDayAtFormat = time.Unix(v.PlanDay, 0).Format(LayoutDate2)
+		}
+
 		res[i] = &pasturePb.SameTimeItems{
 			Id:               int32(v.Id),
 			CowId:            int32(v.CowId),
 			EarNumber:        v.EarNumber,
 			BreedStatus:      v.BreedStatus,
 			BreedStatusName:  breedStatusMap[v.BreedStatus],
-			PenName:          penName,
+			PenName:          v.PenName,
 			PenId:            v.PenId,
 			Lact:             v.Lact,
 			CalvingAge:       v.CalvingAge,
@@ -137,6 +138,7 @@ func (s SameTimeBodySlice) ToPB(
 			AbortionAtFormat: abortionAtFormat,
 			MatingTimes:      v.MatingTimes,
 			SameTimeName:     v.SameTimeName,
+			PlanDay:          playDayAtFormat,
 		}
 	}
 	return res

+ 5 - 0
model/event_mating.go

@@ -313,3 +313,8 @@ type MultiFactorPregnancyRateChart struct {
 	PregnantRateMap map[string]map[string]string `json:"pregnantRateMap"`
 	KepMap          []string                     `json:"kepMap"`
 }
+
+type CowPregnantMonth struct {
+	Month    string `json:"month"`
+	CowCount int32  `json:"cowCount"`
+}

+ 1 - 1
model/event_pregnant_check.go

@@ -82,7 +82,7 @@ func NewEventPregnantCheck(pastureId int64, cow *Cow, penMap map[int32]*Pen, pre
 func NewEventPregnantCheckList(pastureId int64, cowList []*Cow, penMap map[int32]*Pen, pregnantCheckName string) []*EventPregnantCheck {
 	res := make([]*EventPregnantCheck, len(cowList))
 	for i, cow := range cowList {
-		if cow.BreedStatus != pasturePb.BreedStatus_Breeding {
+		if cow.BreedStatus != pasturePb.BreedStatus_Breeding && cow.BreedStatus != pasturePb.BreedStatus_Pregnant {
 			continue
 		}
 		res[i] = NewEventPregnantCheck(pastureId, cow, penMap, pregnantCheckName)

+ 4 - 18
model/neck_ring.go

@@ -1,7 +1,6 @@
 package model
 
 import (
-	"kpt-pasture/store/kptstore"
 	"time"
 
 	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
@@ -20,6 +19,8 @@ type NeckRing struct {
 	OperationName  string                        `json:"operationName"`
 	CreatedAt      int64                         `json:"createdAt"`
 	UpdatedAt      int64                         `json:"updatedAt"`
+
+	PenName string `json:"penName" gorm:"-"`
 }
 
 func (n *NeckRing) TableName() string {
@@ -46,23 +47,9 @@ func NewNeckRing(pastureId int64, number string, cowInfo *Cow, operationUser *Sy
 
 type NeckRingSlice []*NeckRing
 
-func (n NeckRingSlice) ToPB(
-	neckRingStatus map[pasturePb.NeckRingStatus_Kind]string,
-	db *kptstore.DB,
-	getCowPenInfoByCowId func(DB *kptstore.DB, cowId int64) *Pen,
-) []*pasturePb.SearchNeckRingList {
+func (n NeckRingSlice) ToPB(neckRingStatus map[pasturePb.NeckRingStatus_Kind]string) []*pasturePb.SearchNeckRingList {
 	res := make([]*pasturePb.SearchNeckRingList, len(n))
 	for i, v := range n {
-		penId := int32(0)
-		penName := ""
-		if v.CowId > 0 {
-			penInfo := getCowPenInfoByCowId(db, v.CowId)
-			if penInfo != nil {
-				penId = penInfo.Id
-				penName = penInfo.Name
-			}
-		}
-
 		wearAtFormat := ""
 		wearDays := int32(0)
 		if v.WearAt > 0 {
@@ -73,8 +60,7 @@ func (n NeckRingSlice) ToPB(
 			Id:           int32(v.Id),
 			Number:       v.NeckRingNumber,
 			EarNumber:    v.EarNumber,
-			PenId:        penId,
-			PenName:      penName,
+			PenName:      v.PenName,
 			CowId:        int32(v.CowId),
 			WearAtFormat: wearAtFormat,
 			WearDays:     wearDays,

+ 7 - 4
module/backend/analysis.go

@@ -362,19 +362,22 @@ func (s *StoreEntry) AbortionRate(ctx context.Context, req *pasturePb.AbortionRa
 	}
 	// 历史每月怀孕牛头数量
 	cowPregnantMonthList := make([]*model.CowPregnantMonth, 0)
-	pref := s.DB.Model(new(model.CowPregnant)).
+	pref := s.DB.Model(new(model.EventMating)).
 		Select(`
 			COUNT(cow_id) AS cow_count,
-			DATE_FORMAT(FROM_UNIXTIME(created_at),'%Y-%m') as month`,
+			DATE_FORMAT(FROM_UNIXTIME(reality_day),'%Y-%m') as month`,
 		).Where("cow_type = ?", req.CowType).
 		Where("pasture_id = ?", userModel.AppPasture.Id).
-		Where("DATE_FORMAT(FROM_UNIXTIME(`created_at`),'%Y-%m-%d') IN ?", lastDayForMonth)
+		Where("status = ?", pasturePb.IsShow_Ok).
+		Where("mating_result = ?", pasturePb.MatingResult_Pregnant).
+		Where("DATE_FORMAT(FROM_UNIXTIME(`reality_day`),'%Y-%m-%d') IN ?", lastDayForMonth)
 
 	if req.Lact >= 0 && req.Lact <= 3 {
 		pref.Where("lact = ?", req.Lact)
 	} else {
 		pref.Where("lact > ?", req.Lact)
 	}
+
 	if err = pref.Group("month").
 		Find(&cowPregnantMonthList).Error; err != nil {
 		return nil, xerr.WithStack(err)
@@ -386,7 +389,7 @@ func (s *StoreEntry) AbortionRate(ctx context.Context, req *pasturePb.AbortionRa
 			COUNT(cow_id) AS cow_count,
 			DATE_FORMAT(FROM_UNIXTIME(abortion_at),'%Y-%m') as month`,
 		).Where("cow_type = ?", req.CowType).
-		Where("DATE_FORMAT(FROM_UNIXTIME(`abortion_at`),'%Y-%m') IN ?", dayTimeList)
+		Where("DATE_FORMAT(FROM_UNIXTIME(abortion_at),'%Y-%m') IN ?", dayTimeList)
 
 	if req.Lact >= 0 {
 		pref2.Where("lact = ?", req.Lact)

+ 30 - 54
module/backend/calendar.go

@@ -37,7 +37,8 @@ func (s *StoreEntry) CalendarToDoList(ctx context.Context, req *pasturePb.Calend
 		}
 	}
 
-	sql := `SELECT a.cow_id,b.pen_name,a.calendar_type_name,DATE_FORMAT(FROM_UNIXTIME(a.plan_day), '%Y-%m-%d') AS plan_day,b.lact FROM (
+	sql := `SELECT a.cow_id,b.pen_name,a.calendar_type_name,DATE_FORMAT(FROM_UNIXTIME(a.plan_day), '%Y-%m-%d') AS plan_day,b.lact,
+	b.ear_number FROM (
 		SELECT cow_id,plan_day,'免疫' as calendar_type_name FROM event_immunization_plan WHERE status = 2 ` + pastureWhereSql + `
 		UNION ALL
 		SELECT cow_id,plan_day ,'同期' as calendar_type_name FROM event_cow_same_time WHERE status = 2 ` + pastureWhereSql + `
@@ -49,9 +50,9 @@ func (s *StoreEntry) CalendarToDoList(ctx context.Context, req *pasturePb.Calend
 		SELECT cow_id,plan_day ,'配种' as calendar_type_name FROM event_mating WHERE status = 2 ` + pastureWhereSql + `
 		UNION ALL
 		SELECT cow_id,plan_day ,'产犊' as calendar_type_name FROM event_calving WHERE status = 2 ` + pastureWhereSql + `
-	) as a JOIN cow b ON event_item.cow_id = c.id WHERE 1 = 1 `
+	) as a JOIN cow b ON a.cow_id = b.id WHERE 1 = 1 `
 
-	completeSql := fmt.Sprintf("%s %s ORDER BY a.plan_day DESC LIMIT %d OFFSET %d", sql, whereSql, pagination.PageSize, pagination.PageOffset)
+	completeSql := fmt.Sprintf("%s %s ORDER BY a.plan_day ASC LIMIT %d OFFSET %d", sql, whereSql, pagination.PageSize, pagination.PageOffset)
 	if err = s.DB.Raw(completeSql).Find(&calendarToDoList).Error; err != nil {
 		return nil, err
 	}
@@ -126,7 +127,7 @@ func (s *StoreEntry) getCalendarCowList(
 	pagination *pasturePb.PaginationModel,
 	pastureId int64,
 ) (interface{}, error) {
-	req := &pasturePb.ItemsRequest{EndDay: showDay, CalendarType: calendarType, Status: pasturePb.IsShow_No, PastureId: int32(pastureId)}
+	req := &pasturePb.ItemsRequest{EndDay: showDay, CalendarType: calendarType, PastureId: int32(pastureId)}
 	switch calendarType {
 	case pasturePb.CalendarType_Immunisation: // 免疫
 		return s.ImmunisationCowList(ctx, req, pagination)
@@ -155,33 +156,27 @@ func (s *StoreEntry) ImmunisationCowList(ctx context.Context, req *pasturePb.Ite
 	}
 	eventImmunizationPlanList := make([]*model.EventImmunizationPlan, 0)
 	count := int64(0)
-	pref := s.DB.Model(new(model.EventImmunizationPlan)).
-		Where("status = ?", pasturePb.IsShow_No).
-		Where("pasture_id = ?", userModel.AppPasture.Id)
-	if req.StartDay != "" {
-		dateTime := util.TimeParseLocalUnix(req.StartDay)
-		pref.Where("plan_day >= ?", dateTime)
-	}
-
-	if req.EndDay != "" {
-		dateTime := util.TimeParseLocalEndUnix(req.EndDay)
-		pref.Where("plan_day <= ?", dateTime)
+	pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventImmunizationPlan).TableName())).
+		Select("a.id,a.cow_id,a.plan_day,a.plan_name as immunization_plan_name,b.pen_name,b.day_age,b.ear_number").
+		Joins(fmt.Sprintf("JOIN %s AS b on a.cow_id = b.id", new(model.Cow).TableName())).
+		Where("a.status = ?", pasturePb.IsShow_No).
+		Where("a.pasture_id = ?", userModel.AppPasture.Id)
+	if req.StartDay != "" && req.EndDay != "" {
+		startTime := util.TimeParseLocalUnix(req.StartDay)
+		endTime := util.TimeParseLocalEndUnix(req.EndDay)
+		pref.Where("a.plan_day between ? and  ?", startTime, endTime)
 	}
 
 	if req.CowId > 0 {
-		pref.Where("cow_id = ?", req.CowId)
+		pref.Where("a.cow_id = ?", req.CowId)
 	}
 
 	if req.ImmunizationId > 0 {
-		pref.Where("plan_id = ?", req.ImmunizationId)
+		pref.Where("a.plan_id = ?", req.ImmunizationId)
 	}
 
 	if req.PenId > 0 {
-		pref.Where("pen_id = ?", req.PenId)
-	}
-
-	if req.Status > 0 {
-		pref.Where("status = ?", req.Status)
+		pref.Where("b.pen_id = ?", req.PenId)
 	}
 
 	if err = pref.Order("id desc").
@@ -208,7 +203,6 @@ func (s *StoreEntry) ImmunisationCowList(ctx context.Context, req *pasturePb.Ite
 				"dayAge":               "日龄",
 				"planDay":              "免疫时间",
 				"immunizationPlanName": "免疫名称",
-				"status":               "状态",
 			},
 			List: model.EventImmunizationPlanSlice(eventImmunizationPlanList).ToPB(),
 		},
@@ -224,8 +218,8 @@ func (s *StoreEntry) SameTimeCowList(ctx context.Context, req *pasturePb.ItemsRe
 	sameTimeBodyList := make([]*model.SameTimeItemBody, 0)
 	count := int64(0)
 	pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventCowSameTime).TableName())).
-		Select(`a.id,a.cow_id,a.ear_number,a.pen_name,a.status,a.same_time_type,b.breed_status,a.same_time_name,
-		b.cow_type,b.day_age,b.calving_age,b.abortion_age,b.last_calving_at,b.last_abortion_at`).
+		Select(`a.id,a.cow_id,a.ear_number,a.pen_name,a.status,a.same_time_type,b.breed_status,a.same_time_name,a.plan_day,
+		b.cow_type,b.day_age,b.calving_age,b.abortion_age,b.last_calving_at,b.last_abortion_at,b.lact,b.pen_name,b.mating_times`).
 		Joins("left join cow as b on a.cow_id = b.id").
 		Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
 		Where("a.pasture_id = ?", userModel.AppPasture.Id).
@@ -236,22 +230,13 @@ func (s *StoreEntry) SameTimeCowList(ctx context.Context, req *pasturePb.ItemsRe
 		pref.Where("a.plan_day <= ?", dateTime)
 	}
 
-	if req.CalendarType > 0 {
-		pref.Where("a.same_time_type = ?", req.CalendarType)
-	}
-
 	if req.CowType > 0 {
 		pref.Where("b.cow_type = ?", req.CowType)
 	}
 
-	if req.Status > 0 {
-		pref.Where("a.status = ?", pasturePb.IsShow_No)
-	}
-
-	if err = pref.Order("a.id desc").Count(&count).
+	if err = pref.Order("a.plan_day ASC").Count(&count).
 		Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
-		Order("id desc").
 		Find(&sameTimeBodyList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -271,6 +256,7 @@ func (s *StoreEntry) SameTimeCowList(ctx context.Context, req *pasturePb.ItemsRe
 				"earNumber":        "耳标号",
 				"breedStatusName":  "繁殖状态",
 				"cowTypeName":      "牛只类型",
+				"planDayAtFormat":  "执行日期",
 				"penName":          "栏舍",
 				"lact":             "胎次",
 				"calvingAge":       "产后天数",
@@ -304,11 +290,11 @@ func (s *StoreEntry) PregnancyCheckCowList(ctx context.Context, req *pasturePb.I
 
 	if req.EndDay != "" {
 		dateTime := util.TimeParseLocalEndUnix(req.EndDay)
-		pref.Where("plan_day <= ?", dateTime)
+		pref.Where("a.plan_day <= ?", dateTime)
 	}
 
 	if req.CowType > 0 {
-		pref.Where("cow_type = ?", req.CowType)
+		pref.Where("a.cow_type = ?", req.CowType)
 	}
 
 	if req.Status > 0 {
@@ -316,14 +302,13 @@ func (s *StoreEntry) PregnancyCheckCowList(ctx context.Context, req *pasturePb.I
 	}
 
 	if req.PregnantCheckType > 0 {
-		pref.Where("pregnant_check_name = ?", model.PregnantCheckNameValueMap[req.PregnantCheckType])
+		pref.Where("a.pregnant_check_name = ?", model.PregnantCheckNameValueMap[req.PregnantCheckType])
 	}
 
-	if err = pref.Order("id desc").
+	if err = pref.Order("a.plan_day ASC").
 		Count(&count).
 		Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
-		Order("id desc").
 		Find(&newPregnancyCheckItems).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -377,11 +362,7 @@ func (s *StoreEntry) WeaningCowList(ctx context.Context, req *pasturePb.ItemsReq
 		pref.Where("a.plan_day <= ?", dateTime)
 	}
 
-	if req.Status > 0 {
-		pref.Where("a.status = ?", req.Status)
-	}
-
-	if err = pref.Order("a.id desc").Count(&count).
+	if err = pref.Order("a.plan_day ASC").Count(&count).
 		Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
 		Find(&weaningItems).Error; err != nil {
@@ -427,9 +408,8 @@ func (s *StoreEntry) MatingCowList(ctx context.Context, req *pasturePb.ItemsRequ
         WHEN 4 THEN '同期'
         ELSE '其他'
 		END AS expose_estrus_type_name,
-		b.breed_status,b.cow_type,b.pen_id,b.day_age,b.calving_age,b.abortion_age,c.name as pen_name`).
+		b.breed_status,b.cow_type,b.pen_id,b.day_age,b.calving_age,b.abortion_age,b.pen_name`).
 		Joins("left join cow as b on a.cow_id = b.id").
-		Joins("left join pen as c on a.pen_id = c.id").
 		Where("a.pasture_id = ?", userModel.AppPasture.Id).
 		Where("a.status = ?", pasturePb.IsShow_No)
 
@@ -439,14 +419,10 @@ func (s *StoreEntry) MatingCowList(ctx context.Context, req *pasturePb.ItemsRequ
 	}
 
 	if req.PenId > 0 {
-		pref.Where("a.pen_id = ?", req.PenId)
-	}
-
-	if req.Status > 0 {
-		pref.Where("a.status = ?", req.Status)
+		pref.Where("b.pen_id = ?", req.PenId)
 	}
 
-	if err = pref.Order("a.id desc").
+	if err = pref.Order("a.plan_day ASC").
 		Count(&count).
 		Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
@@ -504,7 +480,7 @@ func (s *StoreEntry) CalvingCowList(ctx context.Context, req *pasturePb.ItemsReq
 		pref.Where("a.status = ?", req.Status)
 	}
 
-	if err := pref.Order("a.id desc").
+	if err = pref.Order("a.plan_day ASC").
 		Count(&count).
 		Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).

+ 4 - 8
module/backend/config_data_breed.go

@@ -351,22 +351,18 @@ func CalendarTypeEnumList(isAll string) []*pasturePb.ConfigOptionsList {
 		Value:    int32(pasturePb.CalendarType_Pregnancy_Check),
 		Label:    "孕检",
 		Disabled: true,
-	}, &pasturePb.ConfigOptionsList{
-		Value:    int32(pasturePb.CalendarType_WorkOrder),
-		Label:    "工单",
-		Disabled: true,
 	}, &pasturePb.ConfigOptionsList{
 		Value:    int32(pasturePb.CalendarType_Weaning),
 		Label:    "断奶",
 		Disabled: true,
-	}, &pasturePb.ConfigOptionsList{
-		Value:    int32(pasturePb.CalendarType_Treatment),
-		Label:    "治疗",
-		Disabled: true,
 	}, &pasturePb.ConfigOptionsList{
 		Value:    int32(pasturePb.CalendarType_Mating),
 		Label:    "配种",
 		Disabled: true,
+	}, &pasturePb.ConfigOptionsList{
+		Value:    int32(pasturePb.CalendarType_Calving),
+		Label:    "产犊",
+		Disabled: true,
 	})
 	return configOptions
 }

+ 14 - 4
module/backend/event_breed.go

@@ -107,6 +107,7 @@ func (s *StoreEntry) CalvingCreate(ctx context.Context, req *pasturePb.EventCalv
 		if err = tx.Model(new(model.EventCalving)).
 			Select("operation_id", "operation_name", "message_id", "message_name", "reality_day", "day_age", "pregnancy_age",
 				"bull_number", "calving_level", "child_number", "status", "is_inducing_childbirth", "pen_id", "dystocia_reason", "remarks").
+			Where("id = ?", newEventCalving.Id).
 			Updates(newEventCalving).Error; err != nil {
 			return xerr.WithStack(err)
 		}
@@ -141,6 +142,7 @@ func (s *StoreEntry) CalvingCreate(ctx context.Context, req *pasturePb.EventCalv
 		cow.EventCalvingUpdate(int64(req.CalvingAt))
 		if err = tx.Model(cow).
 			Select("calving_age", "mating_times", "pregnancy_age", "lact", "breed_status", "is_pregnant", "last_calving_at").
+			Where("id = ?", cow.Id).
 			Updates(cow).Error; err != nil {
 			return xerr.WithStack(err)
 		}
@@ -194,6 +196,7 @@ func (s *StoreEntry) SameTimeCreate(ctx context.Context, req *pasturePb.EventSam
 
 	if err = s.DB.Model(new(model.EventCowSameTime)).
 		Select("status", "drugs_id", "unit", "usage", "remarks", "operation_id", "operation_name").
+		Where("id = ?", eventCowSameTime.Id).
 		Updates(eventCowSameTime).Error; err != nil {
 		return xerr.WithStack(err)
 	}
@@ -479,6 +482,7 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 				lastEventMating.EventReMatingUpdate(int64(req.MatingAt))
 				if err = tx.Model(lastEventMating).
 					Select("mating_result", "mating_result_at", "status").
+					Where("id = ?", lastEventMating.Id).
 					Updates(lastEventMating).Error; err != nil {
 				}
 			}
@@ -489,6 +493,7 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 				lastEventMating.EventUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating, eventMatingCheckModel.OperationUser, userModel.SystemUser)
 				if err = tx.Model(lastEventMating).
 					Select("mating_at", "status", "reality_day", "frozen_semen_number", "operation_id", "operation_name", "message_id", "message_name").
+					Where("id = ?", lastEventMating.Id).
 					Updates(lastEventMating).Error; err != nil {
 					return xerr.WithStack(err)
 				}
@@ -501,6 +506,7 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 				lastEventMating.EventMatingResultUpdate(pasturePb.MatingResult_Empty, int64(req.MatingAt))
 				if err = tx.Model(lastEventMating).
 					Select("mating_result", "mating_result_at").
+					Where("id = ?", lastEventMating.Id).
 					Updates(lastEventMating).Error; err != nil {
 					return xerr.WithStack(err)
 				}
@@ -533,6 +539,7 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 		eventMatingCheckModel.FrozenSemen.EventQuantityUpdate(req.FrozenSemenCount)
 		if err = tx.Model(eventMatingCheckModel.FrozenSemen).
 			Select("quantity").
+			Where("id = ?", eventMatingCheckModel.FrozenSemen.Id).
 			Updates(eventMatingCheckModel.FrozenSemen).Error; err != nil {
 			return xerr.WithStack(err)
 		}
@@ -549,6 +556,7 @@ func (s *StoreEntry) MatingCowUpdate(ctx context.Context, pastureId int64, cow *
 	cow.EventMatingUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating)
 	if err := s.DB.Model(cow).
 		Select("last_mating_at", "mating_times", "last_bull_number", "first_mating_at", "is_pregnant", "breed_status").
+		Where("id = ?", cow.Id).
 		Updates(cow).Error; err != nil {
 		return xerr.WithStack(err)
 	}
@@ -601,20 +609,22 @@ func (s *StoreEntry) WeaningBatch(ctx context.Context, req *pasturePb.EventWeani
 
 	if err = s.DB.Transaction(func(tx *gorm.DB) error {
 		cowInfo := &model.Cow{}
-		for _, v := range eventWeaningList {
-			v.EventUpdate(int64(req.WeaningAt), int32(cowWeightMap[cowInfo.Id]*1000), req.Remarks, req.PenId, operation, userModel.SystemUser)
+		for _, eventWeaning := range eventWeaningList {
+			eventWeaning.EventUpdate(int64(req.WeaningAt), int32(cowWeightMap[cowInfo.Id]*1000), req.Remarks, req.PenId, operation, userModel.SystemUser)
 			if err = tx.Model(new(model.EventWeaning)).
 				Select("status", "reality_day", "operation_id", "operation_name", "message_id", "message_name", "remarks", "after_pen_id").
-				Updates(v).Error; err != nil {
+				Where("id = ?", eventWeaning.Id).
+				Updates(eventWeaning).Error; err != nil {
 				return xerr.WithStack(err)
 			}
-			cowInfo, err = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, v.CowId)
+			cowInfo, err = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, eventWeaning.CowId)
 			if err != nil {
 				return xerr.WithStack(err)
 			}
 			cowInfo.EventWeaningUpdate(int64(req.WeaningAt), req.PenId, int64(cowWeightMap[cowInfo.Id]*1000))
 			if err = tx.Model(new(model.Cow)).
 				Select("pen_id", "current_weight", "weaning_at", "last_weight_at").
+				Where("id = ?", cowInfo.Id).
 				Updates(cowInfo).Error; err != nil {
 				return xerr.WithStack(err)
 			}

+ 11 - 9
module/backend/goods.go

@@ -224,23 +224,25 @@ func (s *StoreEntry) NeckRingList(ctx context.Context, req *pasturePb.SearchNeck
 	neckRingLogList := make([]*model.NeckRing, 0)
 	var count int64 = 0
 
-	pref := s.DB.Model(new(model.NeckRing)).
-		Where("status >= ?", pasturePb.NeckRingStatus_Unbind).
-		Where("pasture_id = ?", userModel.AppPasture.Id).
-		Where("neck_ring_number != ''")
+	pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.NeckRing).TableName())).
+		Select("a.*,COALESCE(b.pen_name, '') AS pen_name").
+		Joins("LEFT JOIN cow as b ON a.cow_id = b.id").
+		Where("a.status >= ?", pasturePb.NeckRingStatus_Unbind).
+		Where("a.pasture_id = ?", userModel.AppPasture.Id).
+		Where("a.neck_ring_number != ''")
 	if req.Status > 0 {
-		pref.Where("status = ?", req.Status)
+		pref.Where("a.status = ?", req.Status)
 	}
 
 	if req.CowId > 0 {
-		pref.Where("cow_id = ?", req.CowId)
+		pref.Where("a.cow_id = ?", req.CowId)
 	}
 
 	if req.Number != "" {
-		pref.Where("number like ?", fmt.Sprintf("%s%s%s", "%", req.Number, "%"))
+		pref.Where("a.number like ?", fmt.Sprintf("%s%s%s", "%", req.Number, "%"))
 	}
 
-	if err = pref.Order("id desc").
+	if err = pref.Order("a.id desc").
 		Count(&count).
 		Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
@@ -253,7 +255,7 @@ func (s *StoreEntry) NeckRingList(ctx context.Context, req *pasturePb.SearchNeck
 		Code: http.StatusOK,
 		Msg:  "ok",
 		Data: &pasturePb.SearchNeckRingData{
-			List:     model.NeckRingSlice(neckRingLogList).ToPB(neckRingStatusMap, s.DB, GetCowPenInfoByCowId),
+			List:     model.NeckRingSlice(neckRingLogList).ToPB(neckRingStatusMap),
 			Total:    int32(count),
 			PageSize: pagination.PageSize,
 			Page:     pagination.Page,

+ 0 - 16
module/backend/sql.go

@@ -5,7 +5,6 @@ import (
 	"errors"
 	"fmt"
 	"kpt-pasture/model"
-	"kpt-pasture/store/kptstore"
 	"strings"
 
 	"gitee.com/xuyiping_admin/pkg/logger/zaplog"
@@ -480,21 +479,6 @@ func (s *StoreEntry) FindIndicatorsDetailsList(ctx context.Context) ([]*model.In
 	}
 	return list, nil
 }
-
-func GetCowPenInfoByCowId(DB *kptstore.DB, cowId int64) *model.Pen {
-	penData := &model.Pen{}
-	if err := DB.Model(new(model.Cow)).
-		Select("b.*").
-		Table(fmt.Sprintf("%s as a", new(model.Cow).TableName())).
-		Joins(fmt.Sprintf("left join %s as b on a.pen_id = b.id", new(model.Pen).TableName())).
-		Where("a.id = ?", cowId).
-		Where("a.pen_id > ?", 0).
-		First(penData).Error; err != nil {
-		return nil
-	}
-	return penData
-}
-
 func (s *StoreEntry) GetCowLastEvent(pastureId, cowId int64, eventCategoryId pasturePb.EventCategory_Kind) *model.EventCowLog {
 	newEventCowLog := &model.EventCowLog{CowId: cowId}
 	pref := s.DB.Table(newEventCowLog.TableName()).

+ 9 - 11
module/crontab/cow_cron.go

@@ -227,10 +227,6 @@ func (e *Entry) SameTimePlan() error {
 
 	currWeek := time.Now().Weekday()
 	for _, sameTime := range sameTimeList {
-		if sameTime == nil {
-			continue
-		}
-
 		if time.Weekday(sameTime.WeekType) != currWeek {
 			continue
 		}
@@ -238,24 +234,26 @@ func (e *Entry) SameTimePlan() error {
 		cowList := make([]*model.Cow, 0)
 		pref := e.DB.Model(new(model.Cow)).
 			Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
-			Where("sex = ?", pasturePb.Genders_Male).
-			Where("pasture_id = ?", sameTime.PastureId)
+			Where("sex = ?", pasturePb.Genders_Female).
+			Where("pasture_id = ?", sameTime.PastureId).
+			Where("is_pregnant = ?", pasturePb.IsShow_No)
 
 		switch sameTime.CowType {
 		case pasturePb.SameTimeCowType_Breeding_Calf:
-			pref.Where("calving_age >= ?", sameTime.PostpartumDaysStart).
-				Where("calving_age <= ?", sameTime.PostpartumDaysEnd).
-				Where("is_pregnant = ?", pasturePb.IsShow_No)
+			pref.Where("calving_age BETWEEN ? AND ?", sameTime.PostpartumDaysStart, sameTime.PostpartumDaysEnd).
+				Where("lact > ?", 0)
 		case pasturePb.SameTimeCowType_Empty:
 			pref.Where(
 				e.DB.Where("breed_status = ?", pasturePb.BreedStatus_Empty).
 					Or("breed_status = ?", pasturePb.BreedStatus_Abort),
-			).Where("is_pregnant = ?", pasturePb.IsShow_No)
+			)
 		default:
 			continue
 		}
 
-		if err := pref.Find(&cowList).Error; err != nil {
+		if err := pref.Where(`NOT EXISTS (SELECT 1 FROM event_cow_same_time WHERE event_cow_same_time.cow_id = cow.id 
+				AND event_cow_same_time.status = ?)`, pasturePb.IsShow_No).
+			Find(&cowList).Error; err != nil {
 			zaplog.Error("crontab", zap.Any("err", err), zap.Any("sameTime", sameTime))
 			return xerr.WithStack(err)
 		}

+ 22 - 7
module/crontab/work_cron.go

@@ -3,6 +3,7 @@ package crontab
 import (
 	"encoding/json"
 	"kpt-pasture/model"
+	"sort"
 	"time"
 
 	"gorm.io/gorm"
@@ -33,23 +34,31 @@ func (e *Entry) GenerateCalendarBySameTimePlan(cowList []*model.Cow, sameTime *m
 		return nil
 	}
 
+	collateNodes := make([]*pasturePb.CollateNode, 0)
+	err = json.Unmarshal([]byte(sameTime.CollateNodes), &collateNodes)
+	if err != nil {
+		return xerr.WithStack(err)
+	}
+
+	// 排序
+	sort.Slice(collateNodes, func(i, j int) bool {
+		return collateNodes[i].Id < collateNodes[j].Id
+	})
+
+	showDay := time.Now()
 	newSameTimeCowDetailList := make([]*model.EventCowSameTime, 0)
 	newEventMatingList := make([]*model.EventMating, 0)
-	collateNodes := make([]*pasturePb.CollateNode, 0)
-	var _ = json.Unmarshal([]byte(sameTime.CollateNodes), &collateNodes)
-	nowTime := time.Now()
 	for i, collateNode := range collateNodes {
-		showDay := nowTime
 		if i > 0 {
-			showDay = nowTime.Add(time.Hour * 24 * time.Duration(collateNode.NextNodeDay))
+			showDay = showDay.AddDate(0, 0, int(collateNode.NextNodeDay))
 		}
-
 		calendarType := pasturePb.CalendarType_PG
 		histCount := int64(0)
 		if collateNode.SameTimeType == pasturePb.SameTimeType_TAI {
 			calendarType = pasturePb.CalendarType_Mating
 			histCount = e.GetTowardTaiCowSum(sameTime.PastureId)
-			newEventMatingList = append(newEventMatingList, model.NewEventMatingList(sameTime.PastureId, newCowList, showDay.Unix(), pasturePb.ExposeEstrusType_Same_Time)...)
+			newEventMatingItems := model.NewEventMatingList(sameTime.PastureId, newCowList, showDay.Unix(), pasturePb.ExposeEstrusType_Same_Time)
+			newEventMatingList = append(newEventMatingList, newEventMatingItems...)
 		} else {
 			if collateNode.SameTimeType == pasturePb.SameTimeType_RnGH {
 				calendarType = pasturePb.CalendarType_RnGH
@@ -63,6 +72,12 @@ func (e *Entry) GenerateCalendarBySameTimePlan(cowList []*model.Cow, sameTime *m
 		e.CreatedCalendar(sameTime.PastureId, calendarType, showDay.Format(model.LayoutDate2), allCount)
 	}
 
+	zaplog.Info("GenerateCalendarBySameTimePlan",
+		zap.Any("cowList", cowList),
+		zap.Any("newSameTimeCowDetailList", newSameTimeCowDetailList),
+		zap.Any("newEventMatingList", newEventMatingList),
+	)
+
 	if err = e.DB.Transaction(func(tx *gorm.DB) error {
 		// 创建牛只同期详情表
 		if len(newSameTimeCowDetailList) > 0 {

+ 19 - 7
util/util_test.go

@@ -1,10 +1,13 @@
 package util
 
 import (
+	"encoding/json"
 	"fmt"
 	"testing"
 	"time"
 
+	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
+
 	"github.com/stretchr/testify/assert"
 )
 
@@ -507,13 +510,22 @@ func TestGetNeckRingActiveTimer(t *testing.T) {
 }
 
 func Test_demo(t *testing.T) {
-	start := int64(1739548799)
-	end := int64(1739548800)
-	ad := SubDays(start, end)
-	fmt.Println(ad)
 
-	a := "2025-01-01"
-	b := "2025-03-01"
+	s := `[{"id":1,"sameTimeName":"PG保健1","sameTimeType":1,"nextNodeDay":7,"nextId":2,"showDays":"7 ~ 14","sumStart":7,"sumEnd":14},{"id":2,"sameTimeName":"PG保健2","sameTimeType":1,"nextNodeDay":7,"nextId":3,"showDays":"14 ~ 21","sumStart":14,"sumEnd":21},{"id":3,"sameTimeName":"PG保健3","sameTimeType":1,"nextNodeDay":3,"nextId":4,"showDays":"21 ~ 28","sumStart":21,"sumEnd":28},{"id":4,"sameTimeName":"RnGH1","sameTimeType":3,"nextNodeDay":7,"nextId":5,"showDays":"24 - 31","sumStart":24,"sumEnd":31},{"id":5,"sameTimeName":"PG同期1","sameTimeType":2,"nextNodeDay":2,"nextId":6,"showDays":"31 - 38","sumStart":31,"sumEnd":38},{"id":6,"sameTimeName":"RnGH2","sameTimeType":3,"nextNodeDay":1,"nextId":7,"showDays":"33 - 40","sumStart":33,"sumEnd":40},{"id":7,"sameTimeName":"TAI输精","sameTimeType":4,"showDays":"34 - 41","sumStart":34,"sumEnd":41}]`
+	collateNodes := make([]*pasturePb.CollateNode, 0)
+	err := json.Unmarshal([]byte(s), &collateNodes)
+	if err != nil {
+		fmt.Println(err)
+		return
+	}
+
+	nowTime := time.Now()
+	for i, collateNode := range collateNodes {
+		showDay := nowTime
+		if i > 0 {
+			showDay = nowTime.AddDate(0, 0, int(collateNode.NextNodeDay))
+		}
+		fmt.Println(collateNode.NextNodeDay, showDay.Format("2006-01-02"))
+	}
 
-	fmt.Println(GetDaysBetween(a, b))
 }