Browse Source

pasture: 增加牧场id

Yi 3 months ago
parent
commit
1b4bd4319a
55 changed files with 836 additions and 545 deletions
  1. 5 5
      dep/di_crontab.go
  2. 1 1
      go.mod
  3. 2 0
      go.sum
  4. 8 3
      http/handler/pasture/seme_time.go
  5. 13 0
      http/middleware/sso.go
  6. 4 3
      model/calendar.go
  7. 3 1
      model/calving_calf.go
  8. 15 2
      model/cow.go
  9. 2 0
      model/cow_pregnant.go
  10. 0 35
      model/cow_same_time.go
  11. 7 6
      model/disease.go
  12. 2 0
      model/drugs.go
  13. 3 1
      model/event_abortion.go
  14. 5 3
      model/event_body_score.go
  15. 5 3
      model/event_calving.go
  16. 32 0
      model/event_cow_die_out.go
  17. 2 0
      model/event_cow_disease.go
  18. 2 0
      model/event_cow_log.go
  19. 5 3
      model/event_cow_same_time.go
  20. 17 0
      model/event_cow_treatment.go
  21. 2 1
      model/event_departure.go
  22. 3 1
      model/event_enter.go
  23. 1 0
      model/event_estrus.go
  24. 14 12
      model/event_immunization_plan.go
  25. 6 3
      model/event_mating.go
  26. 5 3
      model/event_pregnant_check.go
  27. 5 3
      model/event_weaning.go
  28. 2 0
      model/immunization_plan.go
  29. 2 0
      model/medical_equipment.go
  30. 4 2
      model/neck_ring.go
  31. 2 0
      model/neck_ring_bind_log.go
  32. 10 0
      model/pasture_list.go
  33. 21 12
      model/prescription.go
  34. 2 1
      model/prescription_drugs.go
  35. 2 0
      model/same_time.go
  36. 3 6
      model/system_basic.go
  37. 6 5
      model/system_user.go
  38. 2 0
      model/work_order_master.go
  39. 51 19
      module/backend/analysis.go
  40. 30 11
      module/backend/calendar.go
  41. 9 3
      module/backend/cow.go
  42. 32 25
      module/backend/event_base.go
  43. 85 77
      module/backend/event_breed.go
  44. 33 14
      module/backend/event_breed_more.go
  45. 12 7
      module/backend/event_check.go
  46. 6 1
      module/backend/event_cow_log.go
  47. 93 61
      module/backend/event_health.go
  48. 29 13
      module/backend/goods.go
  49. 2 2
      module/backend/interface.go
  50. 77 35
      module/backend/prescription.go
  51. 61 48
      module/backend/sql.go
  52. 52 41
      module/crontab/cow_cron.go
  53. 0 1
      module/crontab/interface.go
  54. 19 10
      module/crontab/other.go
  55. 20 62
      module/crontab/work_cron.go

+ 5 - 5
dep/di_crontab.go

@@ -72,11 +72,11 @@ func EntryCrontab(dependency CrontabDependency) *cron.Crontab {
 		panic(err)
 	}
 
-	err = newCrontab.Bind("CowPregnant", cs.CowPregnant, dependency.CrontabHub.CowPregnant)
-	if err != nil {
-		panic(err)
-	}
-
+	/*	err = newCrontab.Bind("CowPregnant", cs.CowPregnant, dependency.CrontabHub.CowPregnant)
+		if err != nil {
+			panic(err)
+		}
+	*/
 	err = newCrontab.Bind("NeckRing", cs.NeckRing, dependency.CrontabHub.NeckRingOriginalMergeData)
 	if err != nil {
 		panic(err)

+ 1 - 1
go.mod

@@ -3,7 +3,7 @@ module kpt-pasture
 go 1.17
 
 require (
-	gitee.com/xuyiping_admin/go_proto v0.0.0-20241226082956-7a730dffe7ba
+	gitee.com/xuyiping_admin/go_proto v0.0.0-20241230072900-e3918c6dc9ee
 	gitee.com/xuyiping_admin/pkg v0.0.0-20241108060137-caea58c59f5b
 	github.com/dgrijalva/jwt-go v3.2.0+incompatible
 	github.com/eclipse/paho.mqtt.golang v1.4.3

+ 2 - 0
go.sum

@@ -96,6 +96,8 @@ gitee.com/xuyiping_admin/go_proto v0.0.0-20241226082350-bd279d6d7998 h1:66soxkvW
 gitee.com/xuyiping_admin/go_proto v0.0.0-20241226082350-bd279d6d7998/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
 gitee.com/xuyiping_admin/go_proto v0.0.0-20241226082956-7a730dffe7ba h1:6j33896HgXCH4UBcFpVqqM3sEy1QvEm5Q8VtcBWxC1k=
 gitee.com/xuyiping_admin/go_proto v0.0.0-20241226082956-7a730dffe7ba/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20241230072900-e3918c6dc9ee h1:x5daNVOieKpmVAREZAFuuFaqjJlDBHJ2dw0J1dyhfzc=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20241230072900-e3918c6dc9ee/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
 gitee.com/xuyiping_admin/pkg v0.0.0-20241108060137-caea58c59f5b h1:w05MxH7yqveRlaRbxHhbif5YjPrJFodRPfOjYhXn7Zk=
 gitee.com/xuyiping_admin/pkg v0.0.0-20241108060137-caea58c59f5b/go.mod h1:8tF25X6pE9WkFCczlNAC0K2mrjwKvhhp02I7o0HtDxY=
 github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=

+ 8 - 3
http/handler/pasture/seme_time.go

@@ -107,15 +107,20 @@ func SystemBasicList(c *gin.Context) {
 }
 
 func SystemBasicEdit(c *gin.Context) {
-	var req pasturePb.BaseDataConfig
+	var req pasturePb.BaseDataConfigBatch
 	if err := ginutil.BindProto(c, &req); err != nil {
 		apierr.AbortBadRequest(c, http.StatusBadRequest, err)
 		return
 	}
 
 	if err := valid.ValidateStruct(&req,
-		valid.Field(&req.Id, valid.Required),
-		valid.Field(&req.Name, valid.Required),
+		valid.Field(&req.Item, valid.Required, valid.Each(valid.By(func(value interface{}) error {
+			s := value.(pasturePb.BaseDataConfig)
+			return valid.ValidateStruct(&s,
+				valid.Field(&s.Id, valid.Required),
+				valid.Field(&s.Name, valid.Required),
+			)
+		}))),
 	); err != nil {
 		apierr.AbortBadRequest(c, http.StatusBadRequest, err)
 		return

+ 13 - 0
http/middleware/sso.go

@@ -2,6 +2,7 @@ package middleware
 
 import (
 	"kpt-pasture/config"
+	"strconv"
 
 	commonPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/common"
 	"gitee.com/xuyiping_admin/pkg/apierr"
@@ -17,6 +18,7 @@ const (
 	Authorization = "Authorization"
 	ToKenPrefix   = "Bearer "
 	UserName      = "userName"
+	PastureId     = "PastureId"
 	XRequestId    = "X-Request-Id"
 )
 
@@ -33,6 +35,11 @@ func GetXRequestId(c *gin.Context) string {
 	return item
 }
 
+func GetPastureId(c *gin.Context) (int64, error) {
+	item := c.Request.Header.Get(PastureId)
+	return strconv.ParseInt(item, 10, 64)
+}
+
 func unauthorized(c *gin.Context) {
 	c.AbortWithStatusJSON(http.StatusUnauthorized, apierr.WithContext(c, commonPb.Error_UNAUTHORIZED))
 }
@@ -63,8 +70,14 @@ func RequireAdmin() gin.HandlerFunc {
 			unauthorized(c)
 			return
 		}
+		/*pastureId, err := GetPastureId(c)
+		if err != nil {
+			unauthorized(c)
+			return
+		}*/
 
 		c.Set(UserName, userName)
+		//c.Set(PastureId, pastureId)
 		c.Set(XRequestId, GetXRequestId(c))
 		c.Next()
 	}

+ 4 - 3
model/calendar.go

@@ -2,13 +2,13 @@ package model
 
 import (
 	"fmt"
-	"time"
 
 	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 )
 
 type Calendar struct {
 	Id           int64                       `json:"id"`
+	PastureId    int64                       `json:"pastureId"`
 	Name         string                      `json:"name"`
 	CalendarType pasturePb.CalendarType_Kind `json:"calendarType"`
 	Count        int32                       `json:"count"`
@@ -23,12 +23,13 @@ func (w *Calendar) TableName() string {
 	return "calendar"
 }
 
-func NewCalendar(name string, calendarType pasturePb.CalendarType_Kind, count int32) *Calendar {
+func NewCalendar(pastureId int64, name string, calendarType pasturePb.CalendarType_Kind, showDay string, count int32) *Calendar {
 	return &Calendar{
+		PastureId:    pastureId,
 		Name:         name,
 		Count:        count,
 		CalendarType: calendarType,
-		ShowDay:      time.Now().Format(LayoutDate2),
+		ShowDay:      showDay,
 		IsShow:       pasturePb.IsShow_Ok,
 	}
 }

+ 3 - 1
model/calving_calf.go

@@ -4,6 +4,7 @@ import pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 
 type CalvingCalf struct {
 	Id            int64                  `json:"id"`
+	PastureId     int64                  `json:"pastureId"`
 	CalvingId     int64                  `json:"calvingId"`
 	CowId         int64                  `json:"cow_id"`
 	BirthAt       int64                  `json:"birthAt"`
@@ -26,12 +27,13 @@ func (e *CalvingCalf) TableName() string {
 	return "calving_calf"
 }
 
-func NewEventCalvingCalf(motherId, calvingId, calvingAt int64, req *pasturePb.CalfItem) *CalvingCalf {
+func NewEventCalvingCalf(pastureId, motherId, calvingId, calvingAt int64, req *pasturePb.CalfItem) *CalvingCalf {
 	isAdoption := req.IsAdoption
 	if req.IsLive == pasturePb.IsShow_No {
 		isAdoption = pasturePb.IsShow_No
 	}
 	return &CalvingCalf{
+		PastureId:     pastureId,
 		EarNumber:     req.EarNumber,
 		CalvingId:     calvingId,
 		CowId:         int64(req.CowId),

+ 15 - 2
model/cow.go

@@ -11,6 +11,7 @@ import (
 
 type Cow struct {
 	Id                  int64                          `json:"id"`
+	PastureId           int64                          `json:"pastureId"`
 	Sex                 pasturePb.Genders_Kind         `json:"sex"`
 	NeckRingNumber      string                         `json:"neckRingNumber"`
 	EarNumber           string                         `json:"earNumber"`
@@ -100,11 +101,23 @@ func (c *Cow) EventWeightUpdate(weight int64, weightAt int64) {
 	c.CurrentWeight = weight
 }
 
-// EventDiseaseUpdate 疾病更新
-func (c *Cow) EventDiseaseUpdate(healthStatus pasturePb.HealthStatus_Kind) {
+// EventHealthStatusUpdate 健康状态更新
+func (c *Cow) EventHealthStatusUpdate(healthStatus pasturePb.HealthStatus_Kind) {
 	c.HealthStatus = healthStatus
 }
 
+// EventPenUpdate 更新栏舍
+func (c *Cow) EventPenUpdate(pen *Pen) {
+	c.PenId = pen.Id
+	c.PenName = pen.Name
+}
+
+// EventEarNumberUpdate 更新脖环
+func (c *Cow) EventEarNumberUpdate(newEarNumber string) {
+	c.EarOldNumber = c.EarNumber
+	c.EarNumber = newEarNumber
+}
+
 type CowSlice []*Cow
 
 func (c CowSlice) ToPB(

+ 2 - 0
model/cow_pregnant.go

@@ -4,6 +4,7 @@ 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"`
@@ -21,6 +22,7 @@ func (c *CowPregnant) TableName() string {
 
 func NewCowPregnant(cow *Cow) *CowPregnant {
 	return &CowPregnant{
+		PastureId:    cow.PastureId,
 		CowId:        cow.Id,
 		Lact:         cow.Lact,
 		DayAge:       cow.DayAge,

+ 0 - 35
model/cow_same_time.go

@@ -1,35 +0,0 @@
-package model
-
-import pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
-
-type CowSameTime struct {
-	Id             int64                         `json:"id"`
-	SameTimeId     int64                         `json:"sameTimeId"`
-	CowId          int64                         `json:"cowId"`
-	Lact           int32                         `json:"lact"`
-	SameTimeStatus pasturePb.SameTimeStatus_Kind `json:"sameTimeStatus"`
-	CreatedAt      int64                         `json:"createdAt"`
-	UpdatedAt      int64                         `json:"updatedAt"`
-}
-
-func (c *CowSameTime) TableName() string {
-	return "cow_same_time"
-}
-
-func NewCowSameTime(cow *Cow, sameTime *SameTime) *CowSameTime {
-	return &CowSameTime{
-		SameTimeId:     sameTime.Id,
-		CowId:          cow.Id,
-		Lact:           cow.Lact,
-		SameTimeStatus: pasturePb.SameTimeStatus_No_Start,
-	}
-}
-
-func NewCowSameTimeList(cowList []*Cow, sameTime *SameTime) []*CowSameTime {
-	sameTimeCowList := make([]*CowSameTime, 0)
-	for _, cow := range cowList {
-		sameTimeCowList = append(sameTimeCowList, NewCowSameTime(cow, sameTime))
-
-	}
-	return sameTimeCowList
-}

+ 7 - 6
model/disease.go

@@ -8,15 +8,16 @@ import (
 
 type Disease struct {
 	Id              int64                 `json:"id"`
+	PastureId       int64                 `json:"pastureId"`
 	Name            string                `json:"name"`
 	Symptoms        string                `json:"symptoms"`
-	DiseaseType     int32                 `json:"disease_type"`
-	DiseaseTypeName string                `json:"disease_type_name"`
-	IsShow          pasturePb.IsShow_Kind `json:"is_show"`
+	DiseaseType     int32                 `json:"diseaseType"`
+	DiseaseTypeName string                `json:"diseaseTypeName"`
+	IsShow          pasturePb.IsShow_Kind `json:"isShow"`
 	Remarks         string                `json:"remarks"`
-	OperationId     int64                 `json:"operation_id"`
-	CreatedAt       int64                 `json:"created_at"`
-	UpdatedAt       int64                 `json:"updated_at"`
+	OperationId     int64                 `json:"operationId"`
+	CreatedAt       int64                 `json:"createdAt"`
+	UpdatedAt       int64                 `json:"updatedAt"`
 }
 
 func (d *Disease) TableName() string {

+ 2 - 0
model/drugs.go

@@ -4,6 +4,7 @@ import pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 
 type Drugs struct {
 	Id              int64                       `json:"id"`
+	PastureId       int64                       `json:"pastureId"`
 	Name            string                      `json:"name"`
 	CategoryId      pasturePb.DrugCategory_Kind `json:"categoryId"`
 	CategoryName    string                      `json:"categoryName"`
@@ -33,6 +34,7 @@ func (d *Drugs) TableName() string {
 
 func NewDrugs(req *pasturePb.SearchDrugsList, currentUser *SystemUser) *Drugs {
 	return &Drugs{
+		PastureId:       currentUser.PastureId,
 		Name:            req.Name,
 		CategoryId:      req.CategoryId,
 		CategoryName:    req.CategoryName,

+ 3 - 1
model/event_abortion.go

@@ -8,6 +8,7 @@ import (
 
 type EventAbortion struct {
 	Id                  int64                          `json:"id"`
+	PastureId           int64                          `json:"pastureId"`
 	CowId               int64                          `json:"cowId"`
 	Lact                int32                          `json:"lact"`
 	CowType             pasturePb.CowType_Kind         `json:"cowType"`
@@ -29,8 +30,9 @@ func (e *EventAbortion) TableName() string {
 	return "event_abortion"
 }
 
-func NewEventAbortion(cow *Cow, req *pasturePb.EventAbortionRequest, abortionReasonMap map[pasturePb.AbortionReasons_Kind]string) *EventAbortion {
+func NewEventAbortion(pastureId int64, cow *Cow, req *pasturePb.EventAbortionRequest, abortionReasonMap map[pasturePb.AbortionReasons_Kind]string) *EventAbortion {
 	return &EventAbortion{
+		PastureId:           pastureId,
 		CowId:               int64(req.CowId),
 		Lact:                cow.Lact,
 		CowType:             cow.CowType,

+ 5 - 3
model/event_body_score.go

@@ -4,6 +4,7 @@ import pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 
 type EventBodyScore struct {
 	Id            int64  `json:"id"`
+	PastureId     int64  `json:"pastureId"`
 	CowId         int64  `json:"cowId"`
 	EarNumber     string `json:"earNumber"`
 	Score         int32  `json:"score"`
@@ -23,8 +24,9 @@ func (e *EventBodyScore) TableName() string {
 	return "event_body_score"
 }
 
-func NewEventBodyScore(cow *Cow, currentSystemUser *SystemUser, req *pasturePb.BodyScoreEventRequest) *EventBodyScore {
+func NewEventBodyScore(cow *Cow, currentUser *SystemUser, req *pasturePb.BodyScoreEventRequest) *EventBodyScore {
 	return &EventBodyScore{
+		PastureId:     currentUser.PastureId,
 		CowId:         cow.Id,
 		EarNumber:     cow.EarNumber,
 		Score:         req.Score,
@@ -32,8 +34,8 @@ func NewEventBodyScore(cow *Cow, currentSystemUser *SystemUser, req *pasturePb.B
 		DayAge:        cow.GetDayAge(),
 		ScoreAt:       int64(req.ScoreAt),
 		Remarks:       req.Remarks,
-		MessageId:     currentSystemUser.Id,
-		MessageName:   currentSystemUser.Name,
+		MessageId:     currentUser.Id,
+		MessageName:   currentUser.Name,
 		OperationId:   int64(req.OperationId),
 		OperationName: req.OperationName,
 	}

+ 5 - 3
model/event_calving.go

@@ -9,6 +9,7 @@ import (
 
 type EventCalving struct {
 	Id                   int64                         `json:"id"`
+	PastureId            int64                         `json:"pastureId"`
 	CowId                int64                         `json:"cowId"`
 	CowType              pasturePb.CowType_Kind        `json:"cowType"`
 	CowKind              pasturePb.CowKind_Kind        `json:"cowKind"`
@@ -55,8 +56,9 @@ func (e *EventCalving) Update(operationUser *SystemUser, req *pasturePb.EventCal
 	e.DystociaReason = req.DystociaReason
 }
 
-func NewEventCalving(cow *Cow) *EventCalving {
+func NewEventCalving(pastureId int64, cow *Cow) *EventCalving {
 	return &EventCalving{
+		PastureId:  pastureId,
 		CowId:      cow.Id,
 		CowKind:    cow.CowKind,
 		CowType:    cow.CowType,
@@ -69,10 +71,10 @@ func NewEventCalving(cow *Cow) *EventCalving {
 	}
 }
 
-func NewEventCalvingList(cowList []*Cow) []*EventCalving {
+func NewEventCalvingList(pastureId int64, cowList []*Cow) []*EventCalving {
 	eventCalvingList := make([]*EventCalving, 0)
 	for _, cow := range cowList {
-		eventCalvingList = append(eventCalvingList, NewEventCalving(cow))
+		eventCalvingList = append(eventCalvingList, NewEventCalving(pastureId, cow))
 	}
 	return eventCalvingList
 }

+ 32 - 0
model/event_cow_die_out.go

@@ -0,0 +1,32 @@
+package model
+
+type EventCowDieOut struct {
+	Id            int64  `json:"id"`
+	PastureId     int64  `json:"pastureId"`
+	CowId         int64  `json:"cowId"`
+	KindType      int32  `json:"kindType"`
+	Reasons       string `json:"reasons"`
+	RemoveAt      int64  `json:"removeAt"`
+	Remarks       string `json:"remarks"`
+	OperationId   int64  `json:"operationId"`
+	OperationName string `json:"operationName"`
+	CreatedAt     int64  `json:"createdAt"`
+	UpdatedAt     int64  `json:"updatedAt"`
+}
+
+func (e *EventCowDieOut) TableName() string {
+	return "event_cow_die_out"
+}
+
+func NewEventCowDieOut(operationUser *SystemUser) *EventCowDieOut {
+	return &EventCowDieOut{
+		PastureId:     0,
+		CowId:         0,
+		KindType:      0,
+		Reasons:       "",
+		RemoveAt:      0,
+		Remarks:       "",
+		OperationId:   operationUser.Id,
+		OperationName: operationUser.Name,
+	}
+}

+ 2 - 0
model/event_cow_disease.go

@@ -8,6 +8,7 @@ import (
 
 type EventCowDisease struct {
 	Id                    int64                       `json:"id"`
+	PastureId             int64                       `json:"pastureId"`
 	CowId                 int64                       `json:"cowId"`
 	CowType               pasturePb.CowType_Kind      `json:"cowType"`
 	Lact                  int32                       `json:"lact"`
@@ -75,6 +76,7 @@ func (e *EventCowDisease) EventCurableUpdate(cureAt int64) {
 
 func NewEventCowDisease(cow *Cow, disease *Disease, req *pasturePb.EventCowDiseaseRequest, operation, currUser *SystemUser) *EventCowDisease {
 	return &EventCowDisease{
+		PastureId:       currUser.PastureId,
 		CowId:           cow.Id,
 		CowType:         cow.CowType,
 		Lact:            cow.Lact,

+ 2 - 0
model/event_cow_log.go

@@ -10,6 +10,7 @@ const ShardTableNumber = 6
 
 type EventCowLog struct {
 	Id               int64                    `json:"id"`
+	PastureId        int64                    `json:"pastureId"`
 	CowId            int64                    `json:"cowId"`
 	DayAge           int32                    `json:"dayAge"`
 	Lact             int32                    `json:"lact"`
@@ -59,6 +60,7 @@ func NewEventCowLog(req *EventCowLogModel) *EventCowLog {
 		operationName = req.OperationUser.Name
 	}
 	return &EventCowLog{
+		PastureId:        req.Cow.PastureId,
 		CowId:            req.Cow.Id,
 		DayAge:           req.Cow.GetDayAge(),
 		Lact:             req.Cow.Lact,

+ 5 - 3
model/event_cow_same_time.go

@@ -8,6 +8,7 @@ import (
 
 type EventCowSameTime struct {
 	Id            int64                       `json:"id"`
+	PastureId     int64                       `json:"pastureId"`
 	CowId         int64                       `json:"cowId"`
 	CowType       pasturePb.CowType_Kind      `json:"cowType"`
 	PenId         int32                       `json:"penId"`
@@ -48,8 +49,9 @@ func (s *EventCowSameTime) Update(drugs *Drugs, usage float32, remarks string, c
 	s.MessageName = currentUser.Name
 }
 
-func NewEventCowSameTime(cow *Cow, planTime int64, sameTime *SameTime, sameTimeType pasturePb.SameTimeType_Kind) *EventCowSameTime {
+func NewEventCowSameTime(pastureId int64, cow *Cow, planTime int64, sameTime *SameTime, sameTimeType pasturePb.SameTimeType_Kind) *EventCowSameTime {
 	return &EventCowSameTime{
+		PastureId:    pastureId,
 		CowId:        cow.Id,
 		Lact:         cow.Lact,
 		CowType:      cow.CowType,
@@ -63,10 +65,10 @@ func NewEventCowSameTime(cow *Cow, planTime int64, sameTime *SameTime, sameTimeT
 	}
 }
 
-func NewEventCowSameTimeList(cowList []*Cow, sameTime *SameTime, planTime int64, sameTimeType pasturePb.SameTimeType_Kind) []*EventCowSameTime {
+func NewEventCowSameTimeList(pastureId int64, cowList []*Cow, sameTime *SameTime, planTime int64, sameTimeType pasturePb.SameTimeType_Kind) []*EventCowSameTime {
 	res := make([]*EventCowSameTime, len(cowList))
 	for i, cow := range cowList {
-		res[i] = NewEventCowSameTime(cow, planTime, sameTime, sameTimeType)
+		res[i] = NewEventCowSameTime(pastureId, cow, planTime, sameTime, sameTimeType)
 	}
 	return res
 }

+ 17 - 0
model/event_cow_treatment.go

@@ -11,6 +11,7 @@ import (
 
 type EventCowTreatment struct {
 	Id                 int64                          `json:"id"`
+	PastureId          int64                          `json:"pastureId"`
 	CowId              int64                          `json:"cowId"`
 	CowDiseaseId       int64                          `json:"cowDiseaseId"`
 	DiseaseId          int64                          `json:"diseaseId"`
@@ -43,6 +44,7 @@ func NewEventCowTreatment(
 ) *EventCowTreatment {
 	b, _ := json.Marshal(req.PrescriptionDetail)
 	return &EventCowTreatment{
+		PastureId:          currentUser.PastureId,
 		CowId:              int64(req.CowId),
 		CowDiseaseId:       int64(req.Id),
 		DiseaseId:          int64(req.DiseaseId),
@@ -61,6 +63,21 @@ func NewEventCowTreatment(
 	}
 }
 
+func NewEventCowCurableTreatment(currUser, operationUser *SystemUser, cowDisease *EventCowDisease, remarks string, curableAt int64) *EventCowTreatment {
+	return &EventCowTreatment{
+		PastureId:       currUser.PastureId,
+		CowId:           cowDisease.CowId,
+		CowDiseaseId:    cowDisease.Id,
+		DiseaseId:       int64(cowDisease.DiseaseId),
+		DiseaseName:     cowDisease.DiseaseName,
+		TreatmentResult: pasturePb.TreatmentResult_Curable,
+		OperationId:     operationUser.Id,
+		OperationName:   operationUser.Name,
+		Remarks:         remarks,
+		TreatmentAt:     curableAt,
+	}
+}
+
 type EventCowTreatmentSlice []*EventCowTreatment
 
 func (e EventCowTreatmentSlice) ToPB(eventCowDiseaseList []*EventCowDisease) []*pasturePb.EventCowTreatment {

+ 2 - 1
model/event_departure.go

@@ -4,6 +4,7 @@ import pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 
 type EventDeparture struct {
 	Id            int64                        `json:"id"`
+	PastureId     int64                        `json:"pastureId"`
 	CowId         int64                        `json:"cowId"`
 	Lact          int32                        `json:"lact"`
 	DayAge        int32                        `json:"dayAge"`
@@ -24,7 +25,7 @@ func (e *EventDeparture) TableName() string {
 	return "event_departure"
 }
 
-func NewEventDeparture(cow *Cow, req *pasturePb.EventDeparture, reasonName string, currentUser, operationUser *SystemUser) *EventDeparture {
+func NewEventDeparture(pastureId int64, cow *Cow, req *pasturePb.EventDeparture, reasonName string, currentUser, operationUser *SystemUser) *EventDeparture {
 	return &EventDeparture{
 		CowId:         cow.Id,
 		Lact:          cow.Lact,

+ 3 - 1
model/event_enter.go

@@ -9,6 +9,7 @@ import (
 
 type EventEnter struct {
 	Id               int64                      `json:"id"`
+	PastureId        int64                      `json:"pastureId"`
 	BatchNumber      string                     `json:"batchNumber"`
 	EarNumber        string                     `json:"earNumber"`
 	CowId            int64                      `json:"cowId"`
@@ -44,8 +45,9 @@ type EventEnter struct {
 func (e *EventEnter) TableName() string {
 	return "event_enter"
 }
-func NewEventEnter(cowId int64, req *pasturePb.EventEnterRequest) *EventEnter {
+func NewEventEnter(pastureId, cowId int64, req *pasturePb.EventEnterRequest) *EventEnter {
 	return &EventEnter{
+		PastureId:        pastureId,
 		EarNumber:        req.EarNumber,
 		CowId:            cowId,
 		Sex:              req.Sex,

+ 1 - 0
model/event_estrus.go

@@ -9,6 +9,7 @@ import (
 
 type EventEstrus struct {
 	Id                int64                           `json:"id"`
+	PastureId         int64                           `json:"pastureId"`
 	CowId             int64                           `json:"cowId"`
 	Lact              int32                           `json:"lact"`
 	ExposeEstrusType  pasturePb.ExposeEstrusType_Kind `json:"exposeEstrusType"`

+ 14 - 12
model/event_immunization_plan.go

@@ -9,6 +9,7 @@ import (
 
 type EventImmunizationPlan struct {
 	Id            int64                  `json:"id"`
+	PastureId     int64                  `json:"pastureId"`
 	CowId         int64                  `json:"cowId"`
 	Lact          int32                  `json:"lact"`
 	DayAge        int32                  `json:"dayAge"`
@@ -43,18 +44,19 @@ func NewCowImmunizationPlan(cow *Cow, pen *Pen, immunizationPlan *ImmunizationPl
 	todayStartTime := util.TimeParseLocalUnix(todayTime)
 	todayEndTime := util.TimeParseLocalEndUnix(todayTime)
 	return &EventImmunizationPlan{
-		CowId:    cow.Id,
-		Lact:     cow.Lact,
-		DayAge:   cow.DayAge,
-		CowKind:  cow.CowKind,
-		CowType:  cow.CowType,
-		PenId:    cow.PenId,
-		PenName:  pen.Name,
-		PlanId:   immunizationPlan.Id,
-		PlanName: immunizationPlan.Name,
-		PlanDay:  todayStartTime,
-		EndDay:   todayEndTime,
-		Status:   pasturePb.IsShow_No,
+		PastureId: immunizationPlan.PastureId,
+		CowId:     cow.Id,
+		Lact:      cow.Lact,
+		DayAge:    cow.DayAge,
+		CowKind:   cow.CowKind,
+		CowType:   cow.CowType,
+		PenId:     cow.PenId,
+		PenName:   pen.Name,
+		PlanId:    immunizationPlan.Id,
+		PlanName:  immunizationPlan.Name,
+		PlanDay:   todayStartTime,
+		EndDay:    todayEndTime,
+		Status:    pasturePb.IsShow_No,
 	}
 }
 

+ 6 - 3
model/event_mating.go

@@ -8,6 +8,7 @@ import (
 
 type EventMating struct {
 	Id                int64                           `json:"id"`
+	PastureId         int64                           `json:"pastureId"`
 	CowId             int64                           `json:"cowId"`
 	DayAge            int32                           `json:"dayAge"`
 	Lact              int32                           `json:"lact"`
@@ -69,7 +70,7 @@ func EventMatingUpdateMap(matingAt int64, bullNumber string, operationUser, curr
 	}
 }
 
-func NewEventMating(cow *Cow, planDay int64, exposeEstrusType pasturePb.ExposeEstrusType_Kind) *EventMating {
+func NewEventMating(pastureId int64, cow *Cow, planDay int64, exposeEstrusType pasturePb.ExposeEstrusType_Kind) *EventMating {
 	return &EventMating{
 		CowId:            cow.Id,
 		Lact:             cow.Lact,
@@ -88,6 +89,7 @@ func NewEventMating(cow *Cow, planDay int64, exposeEstrusType pasturePb.ExposeEs
 // NewEventMating2 自然发情的牛只
 func NewEventMating2(cow *Cow, req *pasturePb.EventMating, currentUser *SystemUser) *EventMating {
 	return &EventMating{
+		PastureId:         currentUser.PastureId,
 		CowId:             cow.Id,
 		Lact:              cow.Lact,
 		DayAge:            cow.GetDayAge(),
@@ -109,10 +111,11 @@ func NewEventMating2(cow *Cow, req *pasturePb.EventMating, currentUser *SystemUs
 	}
 }
 
-func NewEventMatingList(cowList []*Cow, planDay int64, exposeEstrusType pasturePb.ExposeEstrusType_Kind) []*EventMating {
+// NewEventMatingList 同情配种
+func NewEventMatingList(pastureId int64, cowList []*Cow, planDay int64, exposeEstrusType pasturePb.ExposeEstrusType_Kind) []*EventMating {
 	var matingList []*EventMating
 	for _, cow := range cowList {
-		matingList = append(matingList, NewEventMating(cow, planDay, exposeEstrusType))
+		matingList = append(matingList, NewEventMating(pastureId, cow, planDay, exposeEstrusType))
 	}
 	return matingList
 }

+ 5 - 3
model/event_pregnant_check.go

@@ -9,6 +9,7 @@ import (
 
 type EventPregnantCheck struct {
 	Id                  int64                              `json:"id"`
+	PastureId           int64                              `json:"pastureId"`
 	CowId               int64                              `json:"cowId"`
 	CowType             pasturePb.CowType_Kind             `json:"cowType"`
 	PenId               int32                              `json:"penId"`
@@ -55,12 +56,13 @@ func (e *EventPregnantCheck) EventUpdate(
 	e.Status = pasturePb.IsShow_Ok
 }
 
-func NewEventPregnantCheck(cow *Cow, penMap map[int32]*Pen, pregnantCheckName string) *EventPregnantCheck {
+func NewEventPregnantCheck(pastureId int64, cow *Cow, penMap map[int32]*Pen, pregnantCheckName string) *EventPregnantCheck {
 	penName := ""
 	if pen, ok := penMap[cow.PenId]; ok {
 		penName = pen.Name
 	}
 	return &EventPregnantCheck{
+		PastureId:         pastureId,
 		CowId:             cow.Id,
 		CowType:           cow.CowType,
 		PenId:             cow.PenId,
@@ -75,13 +77,13 @@ func NewEventPregnantCheck(cow *Cow, penMap map[int32]*Pen, pregnantCheckName st
 	}
 }
 
-func NewEventPregnantCheckList(cowList []*Cow, penMap map[int32]*Pen, pregnantCheckName string) []*EventPregnantCheck {
+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 {
 			continue
 		}
-		res[i] = NewEventPregnantCheck(cow, penMap, pregnantCheckName)
+		res[i] = NewEventPregnantCheck(pastureId, cow, penMap, pregnantCheckName)
 	}
 	return res
 }

+ 5 - 3
model/event_weaning.go

@@ -9,6 +9,7 @@ import (
 
 type EventWeaning struct {
 	Id            int64                 `json:"id"`
+	PastureId     int64                 `json:"pastureId"`
 	CowId         int64                 `json:"cowId"`
 	PlanDay       int64                 `json:"planDay"`
 	EndDay        int64                 `json:"endDay"`
@@ -40,8 +41,9 @@ func (e *EventWeaning) EventUpdate(weaningAt int64, remarks string, afterPenId i
 	e.AfterPenId = afterPenId
 }
 
-func NewEventWeaning(cowId int64, penId int32) *EventWeaning {
+func NewEventWeaning(pastureId, cowId int64, penId int32) *EventWeaning {
 	return &EventWeaning{
+		PastureId:   pastureId,
 		CowId:       cowId,
 		PlanDay:     util.TimeParseLocalUnix(time.Now().Format(LayoutDate2)),
 		EndDay:      util.TimeParseLocalEndUnix(time.Now().Format(LayoutDate2)),
@@ -50,10 +52,10 @@ func NewEventWeaning(cowId int64, penId int32) *EventWeaning {
 	}
 }
 
-func NewEventWeaningList(cowList []*Cow) []*EventWeaning {
+func NewEventWeaningList(pastureId int64, cowList []*Cow) []*EventWeaning {
 	var weaningList = make([]*EventWeaning, 0)
 	for _, cow := range cowList {
-		weaningList = append(weaningList, NewEventWeaning(cow.Id, cow.PenId))
+		weaningList = append(weaningList, NewEventWeaning(pastureId, cow.Id, cow.PenId))
 	}
 	return weaningList
 }

+ 2 - 0
model/immunization_plan.go

@@ -6,6 +6,7 @@ import (
 
 type ImmunizationPlan struct {
 	Id                   int64                                 `json:"id"`
+	PastureId            int64                                 `json:"pastureId"`
 	Name                 string                                `json:"name"`
 	CowType              pasturePb.CowType_Kind                `json:"cowType"`
 	Conditions           pasturePb.ImmunizationConditions_Kind `json:"conditions"`
@@ -25,6 +26,7 @@ func (i *ImmunizationPlan) TableName() string {
 
 func NewImmunizationPlan(systemUser *SystemUser, req *pasturePb.ImmunizationRequest) *ImmunizationPlan {
 	return &ImmunizationPlan{
+		PastureId:            systemUser.PastureId,
 		Name:                 req.Name,
 		CowType:              req.CowType,
 		Conditions:           req.Conditions,

+ 2 - 0
model/medical_equipment.go

@@ -4,6 +4,7 @@ import pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 
 type MedicalEquipment struct {
 	Id            int64               `json:"id"`
+	PastureId     int64               `json:"pastureId"`
 	Name          string              `json:"name"`
 	Producer      string              `json:"producer"`
 	BatchNumber   string              `json:"batch_number"`
@@ -24,6 +25,7 @@ func (m *MedicalEquipment) TableName() string {
 
 func NewMedicalEquipment(req *pasturePb.SearchMedicalEquipmentList, currentUser *SystemUser) *MedicalEquipment {
 	return &MedicalEquipment{
+		PastureId:     currentUser.PastureId,
 		Name:          req.Name,
 		Producer:      req.Producer,
 		BatchNumber:   req.BatchNumber,

+ 4 - 2
model/neck_ring.go

@@ -9,6 +9,7 @@ import (
 
 type NeckRing struct {
 	Id            int64                         `json:"id"`
+	PastureId     int64                         `json:"pastureId"`
 	Number        string                        `json:"number"`
 	CowId         int64                         `json:"cowId"`
 	WearAt        int64                         `json:"wearAt"`
@@ -24,13 +25,14 @@ func (n *NeckRing) TableName() string {
 	return "neck_ring"
 }
 
-func (n *NeckRing) Update(cowId int64) {
+func (n *NeckRing) EventBindUpdate(cowId int64) {
 	n.CowId = cowId
 	n.WearAt = time.Now().Unix()
 }
 
-func NewNeckRing(number string, cowId int64, operationUser *SystemUser) *NeckRing {
+func NewNeckRing(pastureId int64, number string, cowId int64, operationUser *SystemUser) *NeckRing {
 	return &NeckRing{
+		PastureId:     pastureId,
 		Number:        number,
 		CowId:         cowId,
 		WearAt:        time.Now().Unix(),

+ 2 - 0
model/neck_ring_bind_log.go

@@ -4,6 +4,7 @@ import "time"
 
 type NeckRingBindLog struct {
 	Id            int64  `json:"id"`
+	PastureId     int64  `json:"pastureId"`
 	Number        string `json:"number"`
 	CowId         int64  `json:"cowId"`
 	BindAt        int64  `json:"bindAt"`
@@ -20,6 +21,7 @@ func (n *NeckRingBindLog) TableName() string {
 
 func NewNeckRingBindLog(number string, cowId int64, operationUser *SystemUser) *NeckRingBindLog {
 	return &NeckRingBindLog{
+		PastureId:     operationUser.PastureId,
 		Number:        number,
 		BindAt:        time.Now().Unix(),
 		CowId:         cowId,

+ 10 - 0
model/pasture_list.go

@@ -0,0 +1,10 @@
+package model
+
+type PastureList struct {
+	Id       int64  `json:"id"`
+	Name     string `json:"name"`
+	Province string `json:"province"`
+	City     string `json:"city"`
+	County   string `json:"county"`
+	Address  string `json:"address"`
+}

+ 21 - 12
model/prescription.go

@@ -9,18 +9,19 @@ import (
 
 type Prescription struct {
 	Id                int32                 `json:"id"`
+	PastureId         int64                 `json:"pastureId"`
 	Name              string                `json:"name"`
-	ApplicableDisease string                `json:"applicable_disease"`
-	UseDays           int32                 `json:"use_days"`
-	UseCount          int32                 `json:"use_count"`
-	MeatExpiredDays   int32                 `json:"meat_expired_days"`
-	MilkExpiredDays   int32                 `json:"milk_expired_days"`
-	IsShow            pasturePb.IsShow_Kind `json:"is_show"`
+	ApplicableDisease string                `json:"applicableDisease"`
+	UseDays           int32                 `json:"useDays"`
+	UseCount          int32                 `json:"useCount"`
+	MeatExpiredDays   int32                 `json:"meatExpiredDays"`
+	MilkExpiredDays   int32                 `json:"milkExpiredDays"`
+	IsShow            pasturePb.IsShow_Kind `json:"isShow"`
 	Remarks           string                `json:"remarks"`
-	OperationId       int64                 `json:"operation_id"`
-	OperationName     string                `json:"operation_name"`
-	CreatedAt         int64                 `json:"created_at"`
-	UpdatedAt         int64                 `json:"updated_at"`
+	OperationId       int64                 `json:"operationId"`
+	OperationName     string                `json:"operationName"`
+	CreatedAt         int64                 `json:"createdAt"`
+	UpdatedAt         int64                 `json:"updatedAt"`
 }
 
 func (p *Prescription) TableName() string {
@@ -31,9 +32,17 @@ func (p *Prescription) EventUseCountUpdate() {
 	p.UseCount += 1
 }
 
-func NewPrescription(req *pasturePb.PrescriptionRequest, applicableDisease string, useDays,
-	meatExpiredDays, milkExpiredDays int32, systemUser *SystemUser) *Prescription {
+func NewPrescription(
+	pastureId int64,
+	req *pasturePb.PrescriptionRequest,
+	applicableDisease string,
+	useDays,
+	meatExpiredDays,
+	milkExpiredDays int32,
+	systemUser *SystemUser,
+) *Prescription {
 	return &Prescription{
+		PastureId:         pastureId,
 		Name:              req.Name,
 		ApplicableDisease: applicableDisease,
 		UseDays:           useDays,

+ 2 - 1
model/prescription_drugs.go

@@ -4,6 +4,7 @@ import pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 
 type PrescriptionDrugs struct {
 	Id             int32                 `json:"id"`
+	PastureId      int64                 `json:"pasture_id"`
 	PrescriptionId int32                 `json:"prescription_id"`
 	DrugsId        int64                 `json:"drugs_id"`
 	DrugsName      string                `json:"drugs_name"`
@@ -21,7 +22,7 @@ func (p *PrescriptionDrugs) TableName() string {
 	return "prescription_drugs"
 }
 
-func NewPrescriptionDrugs(prescriptionId int32, list []*pasturePb.PrescriptionDrugsList) []*PrescriptionDrugs {
+func NewPrescriptionDrugs(pastureId int64, prescriptionId int32, list []*pasturePb.PrescriptionDrugsList) []*PrescriptionDrugs {
 	res := make([]*PrescriptionDrugs, len(list))
 	for i, v := range list {
 		res[i] = &PrescriptionDrugs{

+ 2 - 0
model/same_time.go

@@ -11,6 +11,7 @@ import (
 
 type SameTime struct {
 	Id                  int64                          `json:"id"`
+	PastureId           int64                          `json:"pastureId"`
 	Name                string                         `json:"name"`
 	WeekType            pasturePb.Week_Kind            `json:"weekType"`
 	CowType             pasturePb.SameTimeCowType_Kind `json:"cowType"`
@@ -45,6 +46,7 @@ func NewSameTime(currentUser *SystemUser, req *pasturePb.SearchSameTimeList) *Sa
 		CollateNodes:        string(collateNodes),
 		Remarks:             req.Remarks,
 		OperationId:         currentUser.Id,
+		PastureId:           currentUser.PastureId,
 	}
 }
 

+ 3 - 6
model/system_basic.go

@@ -29,6 +29,7 @@ var PregnantCheckNameValueMap = map[int32]string{
 
 type SystemBasic struct {
 	Id            int32                    `json:"id"`
+	PastureId     int64                    `json:"pastureId"`
 	Name          string                   `json:"name"`
 	CategoryName  string                   `json:"categoryName"`
 	CategoryId    int32                    `json:"categoryId"`
@@ -48,16 +49,12 @@ func (s *SystemBasic) TableName() string {
 	return "system_basic"
 }
 
-func (s *SystemBasic) EditUpdate(minValue, maxValue int32, weekValue pasturePb.Week_Kind, currentUser *SystemUser) {
+func (s *SystemBasic) EditUpdate(pastureId int64, minValue, maxValue int32, weekValue pasturePb.Week_Kind, currentUser *SystemUser) {
 	s.MinValue = minValue
-	if s.ValueType == pasturePb.ValueType_Range {
-		s.MaxValue = maxValue
-	}
-
+	s.MaxValue = maxValue
 	if s.WeekValue > -1 {
 		s.WeekValue = weekValue
 	}
-
 	s.OperationId = int32(currentUser.Id)
 	s.OperationName = currentUser.Name
 }

+ 6 - 5
model/system_user.go

@@ -10,17 +10,18 @@ import (
 
 type SystemUser struct {
 	Id        int64                  `json:"id"`
+	PastureId int64                  `json:"pastureId"`
 	Name      string                 `json:"name"`
-	NickName  string                 `json:"nick_name"`
+	NickName  string                 `json:"nickName"`
 	Mobile    string                 `json:"mobile"`
 	Password  string                 `json:"password"`
 	Avatar    string                 `json:"avatar"`
-	RoleId    int64                  `json:"role_id"`
-	DeptId    int64                  `json:"dept_id"`
+	RoleId    int64                  `json:"roleId"`
+	DeptId    int64                  `json:"deptId"`
 	Remarks   string                 `json:"remarks"`
 	Gender    pasturePb.Genders_Kind `json:"gender"`
-	IsShow    pasturePb.IsShow_Kind  `json:"is_show"`
-	IsDelete  pasturePb.IsShow_Kind  `json:"is_delete"`
+	IsShow    pasturePb.IsShow_Kind  `json:"isShow"`
+	IsDelete  pasturePb.IsShow_Kind  `json:"isDelete"`
 	CreatedAt int64                  `json:"created_at"`
 	UpdatedAt int64                  `json:"updated_at"`
 }

+ 2 - 0
model/work_order_master.go

@@ -26,6 +26,7 @@ func AsynqQueueWorkOrder() asynq.Option {
 
 type WorkOrderMaster struct {
 	Id              int64                                 `json:"id"`
+	PastureId       int64                                 `json:"pastureId"`
 	Name            string                                `json:"name"`
 	CategoryId      pasturePb.WorkOrderCategory_Kind      `json:"categoryId"`
 	CategoryName    string                                `json:"categoryName"`
@@ -78,6 +79,7 @@ func NewWorkOrderMaster(
 	}
 
 	return &WorkOrderMaster{
+		PastureId:       curUser.PastureId,
 		Name:            req.Name,
 		CategoryId:      req.CategoryId,
 		CategoryName:    workOrderCategoryMap[req.CategoryId],

+ 51 - 19
module/backend/analysis.go

@@ -17,9 +17,15 @@ import (
 
 // GrowthCurve 生长曲线 获取图表数据
 func (s *StoreEntry) GrowthCurve(ctx context.Context, req *pasturePb.SearchGrowthCurvesRequest) (*pasturePb.GrowthCurvesResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
 	// 查询数据
 	cowList := make([]*model.Cow, 0)
-	pref := s.DB.Model(new(model.Cow)).Where("admission_status = ?", pasturePb.AdmissionStatus_Admission)
+	pref := s.DB.Model(new(model.Cow)).
+		Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
+		Where("pasture_id = ?", currentUser.PastureId)
 	if req.GetCowId() != "" {
 		pref.Where("id IN ?", strings.Split(req.CowId, ","))
 	}
@@ -31,10 +37,10 @@ func (s *StoreEntry) GrowthCurve(ctx context.Context, req *pasturePb.SearchGrowt
 		pref.Where("birth_at BETWEEN ? AND ?", t0.Unix(), t1.Unix()+86399)
 	}
 
-	if err := pref.Find(&cowList).Error; err != nil {
+	if err = pref.Find(&cowList).Error; err != nil {
 		return nil, err
 	}
-	penList, err := s.GetPenList(ctx)
+	penList, err := s.GetPenList(ctx, currentUser.PastureId)
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -85,13 +91,19 @@ func (s *StoreEntry) GrowthCurve(ctx context.Context, req *pasturePb.SearchGrowt
 }
 
 func (s *StoreEntry) WeightRange(ctx context.Context, req *pasturePb.WeightRangeRequest) (*pasturePb.WeightRangeResponse, error) {
-	cowWeightRange := make([]*model.CowWeightRange, 0)
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
 
-	prefix := s.DB.Model(new(model.Cow)).Where("admission_status = ?", pasturePb.AdmissionStatus_Admission)
+	cowWeightRange := make([]*model.CowWeightRange, 0)
+	prefix := s.DB.Model(new(model.Cow)).
+		Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
+		Where("pasture_id = ?", currentUser.PastureId)
 	if req.CowKind > 0 {
 		prefix.Where("cow_kind = ?", req.CowKind)
 	}
-	if err := prefix.Select(`
+	if err = prefix.Select(`
 		CASE 
 			WHEN current_weight BETWEEN 0 AND 50000 THEN '0-50'  
 			WHEN current_weight BETWEEN 50001 AND 100000 THEN '51-100' 
@@ -135,7 +147,9 @@ func (s *StoreEntry) WeightRange(ctx context.Context, req *pasturePb.WeightRange
 		data = append(data, v.Count)
 	}
 	// 牛只详情列表
-	pref := s.DB.Model(new(model.Cow)).Where("admission_status = ?", pasturePb.AdmissionStatus_Admission)
+	pref := s.DB.Model(new(model.Cow)).
+		Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
+		Where("pasture_id = ?", currentUser.PastureId)
 	if req.CowKind > 0 {
 		pref.Where("cow_kind = ?", req.CowKind)
 	}
@@ -144,11 +158,11 @@ func (s *StoreEntry) WeightRange(ctx context.Context, req *pasturePb.WeightRange
 		pref.Where("current_weight BETWEEN  ? AND ? ", req.MinWeight*1000, req.MaxWeight*1000)
 	}
 
-	if err := pref.Find(&cowList).Error; err != nil {
+	if err = pref.Find(&cowList).Error; err != nil {
 		return nil, err
 	}
 
-	penMap := s.PenMap(ctx)
+	penMap := s.PenMap(ctx, currentUser.PastureId)
 	return &pasturePb.WeightRangeResponse{
 		Code:    http.StatusOK,
 		Message: "ok",
@@ -163,24 +177,30 @@ func (s *StoreEntry) WeightRange(ctx context.Context, req *pasturePb.WeightRange
 }
 
 func (s *StoreEntry) MatingTimely(ctx context.Context, req *pasturePb.MatingTimelyRequest) (*model.MatingTimelyResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	matingTimelyChart := make([]*model.MatingTimelyChart, 0)
+	pastureWhereSql := fmt.Sprintf(" AND pasture_id = %d", currentUser.PastureId)
 	sql := `SELECT calving_age,cow_type, DATE_FORMAT(FROM_UNIXTIME(reality_day), '%Y-%m-%d') AS reality_day, lact_group
 		FROM (
 			SELECT calving_age, cow_type,reality_day, '0' AS lact_group
 			FROM event_mating
-			WHERE lact = 0 AND status = 1
+			WHERE lact = 0 AND status = 1 ` + pastureWhereSql + `
 			UNION ALL
 			SELECT calving_age,cow_type, reality_day, '1' AS lact_group
 			FROM event_mating
-			WHERE lact = 1 AND status = 1
+			WHERE lact = 1 AND status = 1 ` + pastureWhereSql + `
 			UNION ALL
 			SELECT calving_age,cow_type,  reality_day, '2' AS lact_group
 			FROM event_mating
-			WHERE lact = 2 AND status = 1
+			WHERE lact = 2 AND status = 1 ` + pastureWhereSql + `
 			UNION ALL
 			SELECT calving_age, cow_type, reality_day, '3+' AS lact_group
 			FROM event_mating
-			WHERE lact >= 3 AND status = 1
+			WHERE lact >= 3 AND status = 1 ` + pastureWhereSql + `
 		) AS subquery WHERE 1 = 1 `
 
 	whereSql := ""
@@ -191,7 +211,7 @@ func (s *StoreEntry) MatingTimely(ctx context.Context, req *pasturePb.MatingTime
 	if req.StartDayAt > 0 && req.EndDayAt > 0 {
 		whereSql += fmt.Sprintf("AND reality_day BETWEEN %d AND %d", req.StartDayAt, req.EndDayAt)
 	}
-	if err := s.DB.Raw(fmt.Sprintf("%s %s", sql, whereSql)).Find(&matingTimelyChart).Error; err != nil {
+	if err = s.DB.Raw(fmt.Sprintf("%s %s", sql, whereSql)).Find(&matingTimelyChart).Error; err != nil {
 		return nil, err
 	}
 
@@ -237,7 +257,7 @@ func (s *StoreEntry) MatingTimely(ctx context.Context, req *pasturePb.MatingTime
 		pref.Where("reality_day BETWEEN ? AND ?", req.StartDayAt, req.EndDayAt)
 	}
 
-	if err := pref.Find(&eventMatingList).Error; err != nil {
+	if err = pref.Find(&eventMatingList).Error; err != nil {
 		return nil, err
 	}
 
@@ -252,6 +272,11 @@ func (s *StoreEntry) MatingTimely(ctx context.Context, req *pasturePb.MatingTime
 }
 
 func (s *StoreEntry) PenWeight(ctx context.Context, req *pasturePb.PenWeightRequest, pagination *pasturePb.PaginationModel) (*pasturePb.PenWeightResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	penWeightList := make([]*model.PenWeight, 0)
 	pref := s.DB.Model(new(model.Cow)).
 		Select(`
@@ -259,11 +284,13 @@ func (s *StoreEntry) PenWeight(ctx context.Context, req *pasturePb.PenWeightRequ
 			CEILING(AVG(current_weight) / 1000 ) AS avg_weight,
 			CEILING(SUM(current_weight) / 1000 ) AS all_weight,
 			COUNT(*) AS cow_count`,
-		).Where("admission_status = ?", pasturePb.AdmissionStatus_Admission)
+		).
+		Where("pasture_id = ?", currentUser.PastureId).
+		Where("admission_status = ?", pasturePb.AdmissionStatus_Admission)
 	if len(req.PenId) > 0 && req.BarId <= 0 {
 		pref.Where("pen_id IN ?", req.PenId)
 	}
-	if err := pref.Group("pen_id").
+	if err = pref.Group("pen_id").
 		Order("pen_id").
 		Find(&penWeightList).Error; err != nil {
 		return nil, err
@@ -296,13 +323,13 @@ func (s *StoreEntry) PenWeight(ctx context.Context, req *pasturePb.PenWeightRequ
 		prefList.Where("pen_id IN ?", req.PenId)
 	}
 
-	if err := prefList.Count(&count).Limit(int(pagination.PageSize)).
+	if err = prefList.Count(&count).Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).Order("pen_id").
 		Find(&cowList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
 
-	penMap := s.PenMap(ctx)
+	penMap := s.PenMap(ctx, currentUser.PastureId)
 	return &pasturePb.PenWeightResponse{
 		Code:    http.StatusOK,
 		Message: "ok",
@@ -317,6 +344,10 @@ func (s *StoreEntry) PenWeight(ctx context.Context, req *pasturePb.PenWeightRequ
 }
 
 func (s *StoreEntry) AbortionRate(ctx context.Context, req *pasturePb.AbortionRateRequest) (*pasturePb.AbortionRateResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
 
 	dayTimeList, err := util.GetMonthsInRange(req.StartDayTime, req.EndDayTime)
 	if err != nil {
@@ -335,6 +366,7 @@ func (s *StoreEntry) AbortionRate(ctx context.Context, req *pasturePb.AbortionRa
 			COUNT(cow_id) AS cow_count,
 			DATE_FORMAT(FROM_UNIXTIME(created_at),'%Y-%m') as month`,
 		).Where("cow_type = ?", req.CowType).
+		Where("pasture_id = ?", currentUser.PastureId).
 		Where("DATE_FORMAT(FROM_UNIXTIME(`created_at`),'%Y-%m-%d') IN ?", lastDayForMonth)
 
 	if req.Lact >= 0 && req.Lact <= 3 {

+ 30 - 11
module/backend/calendar.go

@@ -16,8 +16,9 @@ import (
 func (s *StoreEntry) CalendarToDoList(ctx context.Context, req *pasturePb.CalendarToDoRequest, pagination *pasturePb.PaginationModel) (*pasturePb.CalendarToDoResponse, error) {
 	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil || currentUser.Id <= 0 {
-		return nil, xerr.WithStack(err)
+		return nil, xerr.Custom("当前登录用户失败,请退出重新登录")
 	}
+
 	var count int64 = 0
 	eventItem := make([]*model.EventItem, 0)
 	pref := s.DB.Model(&model.EventItem{})
@@ -27,7 +28,7 @@ func (s *StoreEntry) CalendarToDoList(ctx context.Context, req *pasturePb.Calend
 	}
 
 	if len(req.CowIds) > 0 {
-		cowList, _ := s.ParseCowIds(ctx, req.CowIds)
+		cowList, _ := s.ParseCowIds(ctx, currentUser.PastureId, req.CowIds)
 		cowIds := make([]int64, 0)
 		for _, cow := range cowList {
 			cowIds = append(cowIds, cow.Id)
@@ -58,7 +59,7 @@ func (s *StoreEntry) CalendarToDoList(ctx context.Context, req *pasturePb.Calend
 		return nil, xerr.WithStack(err)
 	}
 
-	penMap := s.PenMap(ctx)
+	penMap := s.PenMap(ctx, currentUser.PastureId)
 	calendarMap := CalendarTypeMap()
 
 	return &pasturePb.CalendarToDoResponse{
@@ -73,10 +74,16 @@ func (s *StoreEntry) CalendarToDoList(ctx context.Context, req *pasturePb.Calend
 	}, nil
 }
 func (s *StoreEntry) CalendarList(ctx context.Context, req *pasturePb.CalendarRequest) (*pasturePb.CalendarResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil || currentUser.Id <= 0 {
+		return nil, xerr.Customf("登录信息异常,请退出重新登录")
+	}
+
 	calendarList := make([]*model.Calendar, 0)
-	if err := s.DB.Model(&model.Calendar{}).
+	if err = s.DB.Model(&model.Calendar{}).
 		Where("show_day >= ?", req.ShowStartDay).
 		Where("show_day <= ?", req.ShowEndDay).
+		Where("pasture_id = ?", currentUser.PastureId).
 		Where("is_show = ?", pasturePb.IsShow_Ok).
 		Find(&calendarList).Error; err != nil {
 		return nil, xerr.WithStack(err)
@@ -93,16 +100,21 @@ func (s *StoreEntry) CalendarTableDetail(
 	req *pasturePb.CalendarTableRequest,
 	pagination *pasturePb.PaginationModel,
 ) (interface{}, error) {
-
 	if req.Start != time.Now().Format(model.LayoutDate2) {
 		return nil, xerr.Custom("只能获取当天的数据")
 	}
 
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil || currentUser.Id <= 0 {
+		return nil, xerr.Customf("登录信息异常,请退出重新登录")
+	}
+
 	newCalendar := &model.Calendar{}
-	if err := s.DB.Model(&model.Calendar{}).
+	if err = s.DB.Model(&model.Calendar{}).
 		Where("calendar_type = ?", req.CalendarType).
 		Where("show_day = ?", req.Start).
 		Where("is_show = ?", pasturePb.IsShow_Ok).
+		Where("pasture_id = ?", currentUser.PastureId).
 		First(newCalendar).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -110,15 +122,17 @@ func (s *StoreEntry) CalendarTableDetail(
 	if newCalendar.Id <= 0 {
 		return nil, xerr.New("不存在该日历数据")
 	}
-	return s.getCalendarCowList(ctx, req.CalendarType, req.Start, pagination)
+	return s.getCalendarCowList(ctx, req.CalendarType, req.Start, pagination, currentUser.PastureId)
 }
 
 func (s *StoreEntry) getCalendarCowList(
 	ctx context.Context,
 	calendarType pasturePb.CalendarType_Kind,
 	showDay string,
-	pagination *pasturePb.PaginationModel) (interface{}, error) {
-	req := &pasturePb.ItemsRequest{EndDay: showDay, CalendarType: calendarType, Status: pasturePb.IsShow_No}
+	pagination *pasturePb.PaginationModel,
+	pastureId int64,
+) (interface{}, error) {
+	req := &pasturePb.ItemsRequest{EndDay: showDay, CalendarType: calendarType, Status: pasturePb.IsShow_No, PastureId: int32(pastureId)}
 	switch calendarType {
 	case pasturePb.CalendarType_Immunisation: // 免疫
 		return s.ImmunisationCowList(ctx, req, pagination)
@@ -145,7 +159,8 @@ func (s *StoreEntry) ImmunisationCowList(ctx context.Context, req *pasturePb.Ite
 	eventImmunizationPlanList := make([]*model.EventImmunizationPlan, 0)
 	count := int64(0)
 	pref := s.DB.Model(&model.EventImmunizationPlan{}).
-		Where("status = ?", pasturePb.IsShow_No)
+		Where("status = ?", pasturePb.IsShow_No).
+		Where("pasture_id = ?", req.PastureId)
 	if req.StartDay != "" {
 		dateTime := util.TimeParseLocalUnix(req.StartDay)
 		pref.Where("plan_day >= ?", dateTime)
@@ -210,6 +225,7 @@ func (s *StoreEntry) SameTimeCowList(ctx context.Context, req *pasturePb.ItemsRe
 		Select("a.id,a.cow_id,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").
 		Joins("left join cow as b on a.cow_id = b.id").
 		Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
+		Where("a.pasture_id = ?", req.PastureId).
 		Where("a.status = ?", pasturePb.IsShow_No)
 
 	if req.EndDay != "" {
@@ -237,7 +253,7 @@ func (s *StoreEntry) SameTimeCowList(ctx context.Context, req *pasturePb.ItemsRe
 		return nil, xerr.WithStack(err)
 	}
 	breedStatusMap := s.CowBreedStatusMap()
-	penMap := s.PenMap(ctx)
+	penMap := s.PenMap(ctx, int64(req.PastureId))
 	sameTimeTypeMap := s.SameTimeTypeMap()
 	return &pasturePb.SameTimeItemResponse{
 		Code:    http.StatusOK,
@@ -275,6 +291,7 @@ func (s *StoreEntry) PregnancyCheckCowList(ctx context.Context, req *pasturePb.I
 		Select("a.id,a.cow_id,a.pen_id,a.status,b.breed_status,b.cow_type,b.day_age,b.calving_age,b.abortion_age,a.bull_id").
 		Joins("left join cow as b on a.cow_id = b.id").
 		Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
+		Where("a.pasture_id = ?", req.PastureId).
 		Where("a.status = ?", pasturePb.IsShow_No)
 
 	if req.EndDay != "" {
@@ -340,6 +357,7 @@ func (s *StoreEntry) WeaningCowList(ctx context.Context, req *pasturePb.ItemsReq
 		Joins("left join cow as b on a.cow_id = b.id").
 		Joins("left join pen as c on a.before_pen_id = c.id").
 		Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
+		Where("a.pasture_id = ?", req.PastureId).
 		Where("a.status = ?", pasturePb.IsShow_No)
 
 	if req.EndDay != "" {
@@ -385,6 +403,7 @@ func (s *StoreEntry) MatingCowList(ctx context.Context, req *pasturePb.ItemsRequ
 		Select("a.id,a.cow_id,a.status,b.breed_status,b.cow_type,b.pen_id,b.day_age,b.calving_age,b.abortion_age,c.name as 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("").
 		Where("a.status = ?", pasturePb.IsShow_No)
 
 	if req.EndDay != "" {

+ 9 - 3
module/backend/cow.go

@@ -12,9 +12,15 @@ import (
 )
 
 func (s *StoreEntry) CowList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchCowListResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	cowList := make([]*model.Cow, 0)
 	var count int64 = 0
-	pref := s.DB.Model(new(model.Cow))
+	pref := s.DB.Model(new(model.Cow)).
+		Where("pasture_id = ?", currentUser.PastureId)
 
 	if len(req.CowId) > 0 {
 		cowIds := strings.Split(req.CowId, ",")
@@ -57,7 +63,7 @@ func (s *StoreEntry) CowList(ctx context.Context, req *pasturePb.SearchEventRequ
 		pref.Where("ear_number = ?", req.EarNumber)
 	}
 
-	if err := pref.Order("id desc").
+	if err = pref.Order("id desc").
 		Count(&count).
 		Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
@@ -65,7 +71,7 @@ func (s *StoreEntry) CowList(ctx context.Context, req *pasturePb.SearchEventRequ
 		return nil, xerr.WithStack(err)
 	}
 
-	penMap := s.PenMap(ctx)
+	penMap := s.PenMap(ctx, currentUser.PastureId)
 	cowTypeMap := s.CowTypeMap()
 	breedStatusMap := s.CowBreedStatusMap()
 	cowKindMap := s.CowKindMap()

+ 32 - 25
module/backend/event_base.go

@@ -16,7 +16,7 @@ import (
 	"gorm.io/gorm"
 )
 
-func (s *StoreEntry) ParseCowIds(ctx context.Context, cowIds string) ([]*model.Cow, error) {
+func (s *StoreEntry) ParseCowIds(ctx context.Context, pastureId int64, cowIds string) ([]*model.Cow, error) {
 	if len(cowIds) == 0 {
 		return nil, xerr.Custom("cow id is required")
 	}
@@ -30,7 +30,7 @@ func (s *StoreEntry) ParseCowIds(ctx context.Context, cowIds string) ([]*model.C
 		cowIdInts = append(cowIdInts, cowId)
 	}
 
-	cowList, err := s.GetCowInfoByCowIds(ctx, cowIdInts)
+	cowList, err := s.GetCowInfoByCowIds(ctx, pastureId, cowIdInts)
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -38,22 +38,28 @@ func (s *StoreEntry) ParseCowIds(ctx context.Context, cowIds string) ([]*model.C
 }
 
 func (s *StoreEntry) EnterList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchEnterEventResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil || currentUser.Id <= 0 {
+		return nil, xerr.Customf("当前用户信息错误,请退出重新登录")
+	}
+
 	eventEnterList := make([]*model.EventEnter, 0)
 	var count int64 = 0
-	pref := s.DB.Model(new(model.EventEnter))
+	pref := s.DB.Model(new(model.EventEnter)).
+		Where("pasture_id = ?", currentUser.PastureId)
 	if len(req.CowId) > 0 {
 		cowIds := strings.Split(req.CowId, ",")
 		pref.Where("cow_id IN ?", cowIds)
 	}
 
-	if err := pref.Order("id desc").
+	if err = pref.Order("id desc").
 		Count(&count).Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
 		Find(&eventEnterList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
 
-	penMap := s.PenMap(ctx)
+	penMap := s.PenMap(ctx, currentUser.PastureId)
 	breedStatusMap := s.CowBreedStatusMap()
 	cowSourceMap := s.CowSourceMap()
 	cowTypeMap := s.CowTypeMap()
@@ -74,17 +80,18 @@ func (s *StoreEntry) EnterList(ctx context.Context, req *pasturePb.SearchEventRe
 func (s *StoreEntry) CreateEnter(ctx context.Context, req *pasturePb.EventEnterRequest) error {
 	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil || currentUser.Id <= 0 {
-		return xerr.Customf("当前用户信息错误")
+		return xerr.Customf("当前用户信息错误,请退出重新登录")
 	}
+
 	req.MessengerId = int32(currentUser.Id)
 	req.MessengerName = currentUser.Name
 	if req.OperationId > 0 {
-		systemUser, _ := s.GetSystemUserById(ctx, int64(req.OperationId))
+		systemUser, _ := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
 		req.OperationName = systemUser.Name
 	}
 
 	newCowData := model.NewCow(req)
-	newEventEnter := model.NewEventEnter(newCowData.Id, req)
+	newEventEnter := model.NewEventEnter(currentUser.PastureId, newCowData.Id, req)
 	if err = s.DB.Transaction(func(tx *gorm.DB) error {
 		if err = tx.Create(newCowData).Error; err != nil {
 			return xerr.WithStack(err)
@@ -136,12 +143,12 @@ func (s *StoreEntry) GroupTransferList(ctx context.Context, req *pasturePb.Searc
 func (s *StoreEntry) CreateGroupTransfer(ctx context.Context, req *pasturePb.TransferGroupEventRequest) (err error) {
 	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil || currentUser.Id <= 0 {
-		return xerr.Customf("当前用户信息错误")
+		return xerr.Customf("当前用户信息错误,请退出重新登录")
 	}
 
 	newEventTransferGroupModelList := make([]*model.EventTransferGroupModel, 0)
 	for _, v := range req.Body {
-		cow, err := s.GetCowInfoByCowId(ctx, int64(v.CowId))
+		cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(v.CowId))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
@@ -149,7 +156,7 @@ func (s *StoreEntry) CreateGroupTransfer(ctx context.Context, req *pasturePb.Tra
 		if cow.PenId == v.TransferInPenId {
 			continue
 		}
-		operationUser, err := s.GetSystemUserById(ctx, int64(v.OperationId))
+		operationUser, err := s.GetSystemUserById(ctx, cow.PastureId, int64(v.OperationId))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
@@ -166,7 +173,7 @@ func (s *StoreEntry) CreateGroupTransfer(ctx context.Context, req *pasturePb.Tra
 	defer func() {
 		if err != nil {
 			for _, etg := range newEventTransferGroupModelList {
-				cowLogs := s.SubmitEventLog(ctx, etg.Cow, pasturePb.EventType_Transfer_Ben, pasturePb.ExposeEstrusType_Invalid, etg.EventTransferGroup)
+				cowLogs := s.SubmitEventLog(ctx, currentUser, etg.Cow, pasturePb.EventType_Transfer_Ben, pasturePb.ExposeEstrusType_Invalid, etg.EventTransferGroup)
 				s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 			}
 		}
@@ -221,23 +228,23 @@ func (s *StoreEntry) CreateBodyScore(ctx context.Context, req *pasturePb.BodySco
 	if len(req.CowId) <= 0 {
 		return xerr.Custom("请选择相关牛只")
 	}
-	currentSystemUser, err := s.GetCurrentSystemUser(ctx)
+	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil {
-		return xerr.Customf("获取当前用户失败: %s", err.Error())
+		return xerr.Custom("获取当前用户失败,请退出重新登录")
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 	req.OperationName = operationUser.Name
 	bodyScourEvent := make([]*model.EventBodyScore, 0)
-	cowList, err := s.ParseCowIds(ctx, req.CowId)
+	cowList, err := s.ParseCowIds(ctx, currentUser.PastureId, req.CowId)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 	for _, cow := range cowList {
-		bodyScourEvent = append(bodyScourEvent, model.NewEventBodyScore(cow, currentSystemUser, req))
+		bodyScourEvent = append(bodyScourEvent, model.NewEventBodyScore(cow, currentUser, req))
 	}
 	if len(bodyScourEvent) <= 0 {
 		return nil
@@ -285,7 +292,7 @@ func (s *StoreEntry) WeightBatch(ctx context.Context, req *pasturePb.EventWeight
 		return xerr.Custom("当前登录用户失败,请退出重新登录")
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
@@ -295,15 +302,15 @@ func (s *StoreEntry) WeightBatch(ctx context.Context, req *pasturePb.EventWeight
 		if err == nil {
 			// 记录事件日志
 			for _, item := range req.WeightItems {
-				cow, _ := s.GetCowInfoByCowId(ctx, int64(item.CowId))
-				cowLogs := s.SubmitEventLog(ctx, cow, pasturePb.EventType_Weight, pasturePb.ExposeEstrusType_Invalid, req)
+				cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(item.CowId))
+				cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Weight, pasturePb.ExposeEstrusType_Invalid, req)
 				s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 			}
 		}
 	}()
 	cow := &model.Cow{}
 	for _, item := range req.WeightItems {
-		cow, err = s.GetCowInfoByCowId(ctx, int64(item.CowId))
+		cow, err = s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(item.CowId))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
@@ -341,13 +348,13 @@ func (s *StoreEntry) DepartureBatch(ctx context.Context, req *pasturePb.EventDep
 	newEventDepartureList := make([]*model.EventDeparture, 0)
 	cow := &model.Cow{}
 	for _, item := range req.Item {
-		cow, err = s.GetCowInfoByCowId(ctx, int64(item.CowId))
+		cow, err = s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(item.CowId))
 		if err != nil {
 			zaplog.Error("DepartureBatch", zap.Any("item", item), zap.Any("err", err))
 			return xerr.Customf("获取牛只信息失败: %d", item.CowId)
 		}
 
-		operationUser, err := s.GetSystemUserById(ctx, int64(item.OperationId))
+		operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(item.OperationId))
 		if err != nil {
 			zaplog.Error("DepartureBatch", zap.Any("item", item), zap.Any("err", err))
 			return xerr.Customf("获取操作人员信息失败: %d", item.OperationId)
@@ -359,7 +366,7 @@ func (s *StoreEntry) DepartureBatch(ctx context.Context, req *pasturePb.EventDep
 		case pasturePb.DepartureType_Out:
 			reasonName = s.OutReasonMap()[pasturePb.OutReason_Kind(item.DepartureReason)]
 		}
-		newEventDepartureList = append(newEventDepartureList, model.NewEventDeparture(cow, item, reasonName, currentUser, operationUser))
+		newEventDepartureList = append(newEventDepartureList, model.NewEventDeparture(currentUser.PastureId, cow, item, reasonName, currentUser, operationUser))
 	}
 
 	if len(newEventDepartureList) <= 0 {
@@ -376,7 +383,7 @@ func (s *StoreEntry) DepartureBatch(ctx context.Context, req *pasturePb.EventDep
 		if item.DepartureType == pasturePb.DepartureType_Out {
 			eventType = pasturePb.EventType_Out
 		}
-		cowLogs := s.SubmitEventLog(ctx, cow, eventType, pasturePb.ExposeEstrusType_Invalid, item)
+		cowLogs := s.SubmitEventLog(ctx, currentUser, cow, eventType, pasturePb.ExposeEstrusType_Invalid, item)
 		s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 	}
 	return nil

+ 85 - 77
module/backend/event_breed.go

@@ -19,18 +19,24 @@ import (
 )
 
 func (s *StoreEntry) CalvingList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchLavingEventResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("用户信息错误,请退出重新登录")
+	}
+
 	lavingList := make([]*model.EventCalvingList, 0)
 	var count int64 = 0
 	pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventCalving).TableName())).
 		Select(`a.*,b.name as pen_name,c.name as staff_member_name`).
 		Joins(fmt.Sprintf("JOIN %s AS b on a.pen_id = b.id", new(model.Pen).TableName())).
-		Joins(fmt.Sprintf("JOIN %s AS c on a.operation_id = c.id", new(model.SystemUser).TableName()))
+		Joins(fmt.Sprintf("JOIN %s AS c on a.operation_id = c.id", new(model.SystemUser).TableName())).
+		Where("pasture_id = ?", currentUser.PastureId)
 	if len(req.CowId) > 0 {
 		cowIds := strings.Split(req.CowId, ",")
 		pref.Where("a.cow_id IN ?", cowIds)
 	}
 
-	if err := pref.Order("a.id desc").
+	if err = pref.Order("a.id desc").
 		Count(&count).Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
 		Find(&lavingList).Error; err != nil {
@@ -42,7 +48,7 @@ func (s *StoreEntry) CalvingList(ctx context.Context, req *pasturePb.SearchEvent
 		calvingIds = append(calvingIds, v.Id)
 	}
 	calvingCalfList := make([]*model.CalvingCalf, 0)
-	if err := s.DB.Model(new(model.CalvingCalf)).
+	if err = s.DB.Model(new(model.CalvingCalf)).
 		Where("calving_id IN ?", calvingIds).
 		Find(&calvingCalfList).Error; err != nil {
 		return nil, xerr.WithStack(err)
@@ -61,13 +67,18 @@ func (s *StoreEntry) CalvingList(ctx context.Context, req *pasturePb.SearchEvent
 }
 
 func (s *StoreEntry) CalvingCreate(ctx context.Context, req *pasturePb.EventCalving) (err error) {
-	cow, err := s.GetCowInfoByCowId(ctx, int64(req.CowId))
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return xerr.Custom("用户信息错误,请退出重新登录")
+	}
+
+	cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(req.CowId))
 	if err != nil {
 		zaplog.Error("CalvingCreate", zap.Any("cow_id", req.CowId), zap.Any("err", err))
 		return xerr.Custom("请选择相关牛只")
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
 	if err != nil {
 		return xerr.Customf("获取操作人员信息失败: %s", err.Error())
 	}
@@ -77,15 +88,15 @@ func (s *StoreEntry) CalvingCreate(ctx context.Context, req *pasturePb.EventCalv
 	defer func() {
 		if err == nil {
 			// 母牛事件日志
-			cowLogs := s.SubmitEventLog(ctx, cow, pasturePb.EventType_Calving, pasturePb.ExposeEstrusType_Invalid, req)
+			cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Calving, pasturePb.ExposeEstrusType_Invalid, req)
 			s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 			// 犊牛事件日志
 			for _, v := range req.CalfItemList {
 				if v.IsLive == pasturePb.IsShow_No || v.IsAdoption == pasturePb.IsShow_No {
 					continue
 				}
-				cow, _ = s.GetCowInfoByCowId(ctx, int64(v.CowId))
-				cowLogs = s.SubmitEventLog(ctx, cow, pasturePb.EventType_Birth, pasturePb.ExposeEstrusType_Invalid, v)
+				cow, _ = s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(v.CowId))
+				cowLogs = s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Birth, pasturePb.ExposeEstrusType_Invalid, v)
 				s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 			}
 		}
@@ -112,7 +123,7 @@ func (s *StoreEntry) CalvingCreate(ctx context.Context, req *pasturePb.EventCalv
 				continue
 			}
 			// 犊牛信息
-			newCalvingCalf := model.NewEventCalvingCalf(int64(req.CowId), newEventCalving.Id, int64(req.CalvingAt), v)
+			newCalvingCalf := model.NewEventCalvingCalf(currentUser.PastureId, int64(req.CowId), newEventCalving.Id, int64(req.CalvingAt), v)
 			// 留养犊牛
 			newCow := model.NewCalfCow(cow.Id, cow.LastBullNumber, newCalvingCalf)
 			if err = tx.Create(newCow).Error; err != nil {
@@ -141,10 +152,16 @@ func (s *StoreEntry) CalvingCreate(ctx context.Context, req *pasturePb.EventCalv
 }
 
 func (s *StoreEntry) EstrusList(ctx context.Context, req *pasturePb.EstrusItemsRequest, pagination *pasturePb.PaginationModel) (*pasturePb.EstrusItemsResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("用户信息错误,请退出重新登录")
+	}
+
 	estrusList := make([]*model.EventEstrus, 0)
 	var count int64 = 0
 	pref := s.DB.Table(new(model.EventEstrus).TableName()).
-		Where("is_show = ?", pasturePb.IsShow_Ok)
+		Where("is_show = ?", pasturePb.IsShow_Ok).
+		Where("pasture_id = ?", currentUser.PastureId)
 	if len(req.CowIds) > 0 {
 		cowIds := strings.Split(util.ArrayInt32ToStrings(req.CowIds, ","), ",")
 		pref.Where("cow_id IN ?", cowIds)
@@ -159,7 +176,7 @@ func (s *StoreEntry) EstrusList(ctx context.Context, req *pasturePb.EstrusItemsR
 		pref.Where("pen_id IN ?", penIds)
 	}
 
-	if err := pref.Order("id desc").
+	if err = pref.Order("id desc").
 		Count(&count).Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
 		Find(&estrusList).Error; err != nil {
@@ -183,9 +200,9 @@ func (s *StoreEntry) EstrusList(ctx context.Context, req *pasturePb.EstrusItemsR
 func (s *StoreEntry) EstrusBatch(ctx context.Context, req *pasturePb.EventEstrus) (err error) {
 	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误")
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
 	}
-	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
 	if err != nil {
 		return xerr.Customf("该用户不存在: %d", req.OperationId)
 	}
@@ -199,8 +216,8 @@ func (s *StoreEntry) EstrusBatch(ctx context.Context, req *pasturePb.EventEstrus
 			return xerr.Custom("牛只信息不存在")
 		}
 
-		newEventMating := model.NewEventMating(cowInfo, time.Now().Unix(), pasturePb.ExposeEstrusType_Neck_Ring)
-		eventEstrus, ok := s.EventEstrusIsExist(ctx, int64(cowId))
+		newEventMating := model.NewEventMating(currentUser.PastureId, cowInfo, time.Now().Unix(), pasturePb.ExposeEstrusType_Neck_Ring)
+		eventEstrus, ok := s.EventEstrusIsExist(ctx, currentUser.PastureId, int64(cowId))
 		if ok {
 			newEventMating.EventEstrusId = eventEstrus.Id
 			newEventMating.MatingTimes = cowInfo.MatingTimes + 1
@@ -223,8 +240,8 @@ func (s *StoreEntry) EstrusBatch(ctx context.Context, req *pasturePb.EventEstrus
 		// 记录牛只事件日志
 		if err == nil {
 			for _, v := range eventMatingList {
-				cow, _ := s.GetCowInfoByCowId(ctx, v.CowId)
-				cowLogs := s.SubmitEventLog(ctx, cow, pasturePb.EventType_Mating, pasturePb.ExposeEstrusType_Neck_Ring, req)
+				cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, v.CowId)
+				cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Mating, pasturePb.ExposeEstrusType_Neck_Ring, req)
 				s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 			}
 		}
@@ -255,44 +272,36 @@ func (s *StoreEntry) EstrusBatch(ctx context.Context, req *pasturePb.EventEstrus
 }
 
 func (s *StoreEntry) SameTimeCreate(ctx context.Context, req *pasturePb.EventSameTime) (err error) {
-	eventCowSameTime, err := s.GetEventCowSameTimeByCowId(ctx, int64(req.CowId))
+	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil {
-		zaplog.Error("SameTimeCreate", zap.Any("err", err), zap.Any("req", req))
-		return xerr.Customf("异常数据")
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
 	}
 
-	drugs := &model.Drugs{}
-	if drugs, err = s.GetDrugsById(ctx, int64(req.DrugsId)); err != nil {
-		zaplog.Error("SameTimeCreate", zap.Any("err", err), zap.Any("req", req))
-		return xerr.Customf("该药品不存在: %d", req.DrugsId)
-	}
-	req.DrugsName = drugs.Name
-
-	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	eventCowSameTime, err := s.GetEventCowSameTimeByCowId(ctx, currentUser.PastureId, int64(req.CowId))
 	if err != nil {
-		return xerr.Custom("当前用户信息错误")
+		zaplog.Error("SameTimeCreate", zap.Any("err", err), zap.Any("req", req))
+		return xerr.Customf("异常数据")
 	}
 
+	drugs := &model.Drugs{}
+	if drugs, err = s.GetDrugsById(ctx, currentUser.PastureId, int64(req.DrugsId)); err != nil {
+		zaplog.Error("SameTimeCreate", zap.Any("err", err), zap.Any("req", req))
+		return xerr.Customf("该药品不存在: %d", req.DrugsId)
+	}
+	req.DrugsName = drugs.Name
 	eventCowSameTime.Update(drugs, req.Usage, req.Remarks, operationUser, currentUser)
+
 	defer func() {
 		if err == nil {
 			// 记录牛只事件日志
-			cow, _ := s.GetCowInfoByCowId(ctx, eventCowSameTime.CowId)
-			cowLogs := s.SubmitEventLog(ctx, cow, pasturePb.EventType_Seme_Time, pasturePb.ExposeEstrusType_Same_Time, req)
+			cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, eventCowSameTime.CowId)
+			cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Seme_Time, pasturePb.ExposeEstrusType_Same_Time, req)
 			s.DB.Table(cowLogs.TableName()).Create(cowLogs)
-
-			if err = s.DB.Model(new(model.CowSameTime)).
-				Where("cow_id = ?", eventCowSameTime.CowId).
-				Where("same_time_id = ?", eventCowSameTime.Id).
-				Where("same_time_status = ?", pasturePb.SameTimeStatus_No_Start).
-				Update("same_time_status", pasturePb.SameTimeStatus_In_Progress).Error; err != nil {
-				zaplog.Error("SameTimeCreate", zap.Any("err", err), zap.Any("req", req))
-			}
 		}
 	}()
 
@@ -306,18 +315,19 @@ func (s *StoreEntry) SameTimeCreate(ctx context.Context, req *pasturePb.EventSam
 }
 
 func (s *StoreEntry) SameTimeBatch(ctx context.Context, req *pasturePb.EventSameTimeBatch) (err error) {
-	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
+	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil {
-		return xerr.Customf("异常数据")
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
 	}
-	req.OperationName = operationUser.Name
 
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
 	if err != nil {
 		return xerr.Customf("异常数据")
 	}
+	req.OperationName = operationUser.Name
+
 	drugs := &model.Drugs{}
-	if drugs, err = s.GetDrugsById(ctx, int64(req.DrugsId)); err != nil {
+	if drugs, err = s.GetDrugsById(ctx, currentUser.PastureId, int64(req.DrugsId)); err != nil {
 		zaplog.Error("SameTimeBatch", zap.Any("err", err), zap.Any("req", req))
 		return xerr.Customf("该药物不存在: %d", req.DrugsId)
 	}
@@ -325,20 +335,22 @@ func (s *StoreEntry) SameTimeBatch(ctx context.Context, req *pasturePb.EventSame
 
 	eventCowSameTimeList := make([]*model.EventCowSameTime, 0)
 	for _, v := range req.CowIds {
-		eventCowSameTime, err := s.GetEventCowSameTimeByCowId(ctx, int64(v))
+		eventCowSameTime, err := s.GetEventCowSameTimeByCowId(ctx, currentUser.PastureId, int64(v))
 		if err != nil {
 			zaplog.Error("SameTimeCreate", zap.Any("err", err), zap.Any("req", req))
 			return xerr.WithStack(err)
 		}
 		eventCowSameTimeList = append(eventCowSameTimeList, eventCowSameTime)
 	}
+
 	defer func() {
 		// 记录牛只事件日志
 		if err == nil {
 			for _, v := range eventCowSameTimeList {
-				cow, _ := s.GetCowInfoByCowId(ctx, v.CowId)
+				cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, v.CowId)
 				cowLogs := s.SubmitEventLog(
 					ctx,
+					currentUser,
 					cow,
 					pasturePb.EventType_Seme_Time,
 					pasturePb.ExposeEstrusType_Same_Time,
@@ -362,14 +374,6 @@ func (s *StoreEntry) SameTimeBatch(ctx context.Context, req *pasturePb.EventSame
 
 	if err = s.DB.Transaction(func(tx *gorm.DB) error {
 		for _, v := range eventCowSameTimeList {
-			if err = tx.Model(new(model.CowSameTime)).
-				Where("cow_id = ?", v.CowId).
-				Where("same_time_id = ?", v.Id).
-				Where("same_time_status = ?", pasturePb.SameTimeStatus_No_Start).
-				Update("same_time_status", pasturePb.SameTimeStatus_In_Progress).Error; err != nil {
-				zaplog.Error("SameTimeCreate", zap.Any("err", err), zap.Any("req", req))
-			}
-
 			// 更新SameTime
 			v.Update(drugs, req.Usage, req.Remarks, currentUser, operationUser)
 			if err = tx.Model(new(model.EventCowSameTime)).
@@ -391,15 +395,20 @@ func (s *StoreEntry) SameTimeList(
 	req *pasturePb.SearchEventRequest,
 	pagination *pasturePb.PaginationModel,
 ) (*pasturePb.SearchSameTimeResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	cowSameTimeList := make([]*model.EventCowSameTime, 0)
 	var count int64 = 0
-	pref := s.DB.Table(new(model.EventCowSameTime).TableName())
+	pref := s.DB.Table(new(model.EventCowSameTime).TableName()).Where("pasture_id = ?", currentUser.PastureId)
 	if req.CowId != "" {
 		cowIds := strings.Split(req.CowId, ",")
 		pref.Where("cow_id IN ?", cowIds)
 	}
 
-	if err := pref.Count(&count).
+	if err = pref.Count(&count).
 		Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
 		Find(&cowSameTimeList).Error; err != nil {
@@ -420,17 +429,23 @@ func (s *StoreEntry) SameTimeList(
 }
 
 func (s *StoreEntry) MatingList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.MatingEventResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	matingList := make([]*model.EventMating, 0)
 	var count int64 = 0
 	pref := s.DB.Model(new(model.EventMating)).
 		Where("mating_result > ?", pasturePb.MatingResult_Invalid).
-		Where("status = ?", pasturePb.IsShow_No)
+		Where("status = ?", pasturePb.IsShow_No).
+		Where("pasture_id = ?", currentUser.PastureId)
 	if len(req.CowId) > 0 {
 		cowIds := strings.Split(req.CowId, ",")
 		pref.Where("cow_id IN ?", cowIds)
 	}
 
-	if err := pref.Order("id desc").
+	if err = pref.Order("id desc").
 		Count(&count).Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
 		Find(&matingList).Error; err != nil {
@@ -539,8 +554,8 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 		if err != nil {
 			// 记录事件日志
 			for _, cowId := range cowIds {
-				cow, _ := s.GetCowInfoByCowId(ctx, cowId)
-				cowLogs := s.SubmitEventLog(ctx, cow, pasturePb.EventType_Mating, req.ExposeEstrusType, req)
+				cow, _ := s.GetCowInfoByCowId(ctx, eventCheckModel.CurrentUser.PastureId, cowId)
+				cowLogs := s.SubmitEventLog(ctx, eventCheckModel.CurrentUser, cow, pasturePb.EventType_Mating, req.ExposeEstrusType, req)
 				s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 			}
 		}
@@ -594,13 +609,6 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 			return xerr.WithStack(err)
 		}
 
-		// 如果有同期牛只,则修改为已结束状态
-		if err = tx.Model(new(model.CowSameTime)).
-			Where("cow_id IN ?", cowIds).
-			UpdateColumn("same_time_status", pasturePb.SameTimeStatus_End).Error; err != nil {
-			return xerr.WithStack(err)
-		}
-
 		// 更新牛只的繁殖状态为配种
 		if err = tx.Model(new(model.Cow)).
 			Where("id IN ?", cowIds).
@@ -650,6 +658,11 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 }
 
 func (s *StoreEntry) WeaningBatch(ctx context.Context, req *pasturePb.EventWeaningBatchRequest) (err error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	if len(req.Item) <= 0 {
 		return nil
 	}
@@ -668,12 +681,7 @@ func (s *StoreEntry) WeaningBatch(ctx context.Context, req *pasturePb.EventWeani
 		return xerr.WithStack(err)
 	}
 
-	operation, err := s.GetSystemUserById(ctx, int64(req.OperationId))
-	if err != nil {
-		return xerr.WithStack(err)
-	}
-
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	operation, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
@@ -681,8 +689,8 @@ func (s *StoreEntry) WeaningBatch(ctx context.Context, req *pasturePb.EventWeani
 	defer func() {
 		if err != nil {
 			for _, cowId := range cowIds {
-				cow, _ := s.GetCowInfoByCowId(ctx, cowId)
-				cowLogs := s.SubmitEventLog(ctx, cow, pasturePb.EventType_Weaning, pasturePb.ExposeEstrusType_Invalid, req)
+				cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, cowId)
+				cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Weaning, pasturePb.ExposeEstrusType_Invalid, req)
 				s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 			}
 		}
@@ -698,7 +706,7 @@ func (s *StoreEntry) WeaningBatch(ctx context.Context, req *pasturePb.EventWeani
 				Updates(v).Error; err != nil {
 				return xerr.WithStack(err)
 			}
-			cowInfo, err = s.GetCowInfoByCowId(ctx, v.CowId)
+			cowInfo, err = s.GetCowInfoByCowId(ctx, currentUser.PastureId, v.CowId)
 			if err != nil {
 				return xerr.WithStack(err)
 			}

+ 33 - 14
module/backend/event_breed_more.go

@@ -14,15 +14,21 @@ import (
 )
 
 func (s *StoreEntry) PregnantCheckList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.PregnantCheckEventResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	pregnantCheckList := make([]*model.EventPregnantCheck, 0)
 	var count int64 = 0
-	pref := s.DB.Table(new(model.EventPregnantCheck).TableName())
+	pref := s.DB.Table(new(model.EventPregnantCheck).TableName()).
+		Where("pasture_id = ?", currentUser.PastureId)
 	if len(req.CowId) > 0 {
 		cowIds := strings.Split(req.CowId, ",")
 		pref.Where("cow_id IN ?", cowIds)
 	}
 
-	if err := pref.Order("id desc").
+	if err = pref.Order("id desc").
 		Count(&count).Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
 		Find(&pregnantCheckList).Error; err != nil {
@@ -44,13 +50,14 @@ func (s *StoreEntry) PregnantCheckList(ctx context.Context, req *pasturePb.Searc
 }
 
 func (s *StoreEntry) PregnantCheckCreateBatch(ctx context.Context, req *pasturePb.EventPregnantCheckBatch) (err error) {
-	pregnantCheckBatchModelList, err := s.PregnantCheckDataCheck(ctx, req)
+	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil {
-		return xerr.WithStack(err)
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
 	}
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+
+	pregnantCheckBatchModelList, err := s.PregnantCheckDataCheck(ctx, req)
 	if err != nil {
-		return xerr.Customf("获取当前用户失败: %s", err.Error())
+		return xerr.WithStack(err)
 	}
 
 	cowIds := make([]int64, 0)
@@ -65,8 +72,8 @@ func (s *StoreEntry) PregnantCheckCreateBatch(ctx context.Context, req *pastureP
 		if err == nil {
 			// 提交事件日志
 			for _, cowId := range cowIds {
-				cow, _ := s.GetCowInfoByCowId(ctx, cowId)
-				cowLogs := s.SubmitEventLog(ctx, cow, pasturePb.EventType_Pregnancy_Check, pasturePb.ExposeEstrusType_Invalid, req)
+				cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, cowId)
+				cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Pregnancy_Check, pasturePb.ExposeEstrusType_Invalid, req)
 				s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 			}
 		}
@@ -125,19 +132,24 @@ func (s *StoreEntry) PregnantCheckCreateBatch(ctx context.Context, req *pastureP
 }
 
 func (s *StoreEntry) AbortionCreate(ctx context.Context, req *pasturePb.EventAbortionRequest) error {
-	cow, err := s.GetCowInfoByCowId(ctx, int64(req.CowId))
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
+	cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(req.CowId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 
-	systemUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
+	systemUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 
 	req.OperationName = systemUser.Name
 	abortionReasonsMap := s.AbortionReasonsMap()
-	newEventAbortion := model.NewEventAbortion(cow, req, abortionReasonsMap)
+	newEventAbortion := model.NewEventAbortion(currentUser.PastureId, cow, req, abortionReasonsMap)
 
 	lastCowMating := &model.EventMating{}
 	if err = s.DB.Model(new(model.EventMating)).Where("cow_id = ?", cow.Id).
@@ -152,7 +164,7 @@ func (s *StoreEntry) AbortionCreate(ctx context.Context, req *pasturePb.EventAbo
 
 	defer func() {
 		if err != nil {
-			cowLogs := s.SubmitEventLog(ctx, cow, pasturePb.EventType_Abort, pasturePb.ExposeEstrusType_Invalid, req)
+			cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Abort, pasturePb.ExposeEstrusType_Invalid, req)
 			s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 		}
 	}()
@@ -187,6 +199,7 @@ func (s *StoreEntry) AbortionCreateBatch(ctx context.Context, req *pasturePb.Eve
 	if len(req.Item) <= 0 {
 		return xerr.WithStack(xerr.New("流产数据不能为空"))
 	}
+
 	errors := make(map[int32]error)
 	for _, v := range req.Item {
 		if err := s.AbortionCreate(ctx, v); err != nil {
@@ -206,15 +219,21 @@ func (s *StoreEntry) AbortionList(
 	req *pasturePb.SearchEventRequest,
 	pagination *pasturePb.PaginationModel,
 ) (*pasturePb.EventAbortionResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	abortionList := make([]*model.EventAbortion, 0)
 	var count int64 = 0
-	pref := s.DB.Model(new(model.EventAbortion))
+	pref := s.DB.Model(new(model.EventAbortion)).
+		Where("pasture_id = ?", currentUser.PastureId)
 	if len(req.CowId) > 0 {
 		cowIds := strings.Split(req.CowId, ",")
 		pref.Where("cow_id IN ?", cowIds)
 	}
 
-	if err := pref.Order("id desc").
+	if err = pref.Order("id desc").
 		Count(&count).Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
 		Find(&abortionList).Error; err != nil {

+ 12 - 7
module/backend/event_check.go

@@ -42,19 +42,19 @@ func (s *StoreEntry) MatingCreateCheck(ctx context.Context, req *pasturePb.Event
 		return nil, xerr.Custom("请选择相关牛只")
 	}
 
-	cowList, err := s.ParseCowIds(ctx, req.CowIds)
+	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil {
-		return nil, xerr.WithStack(err)
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
+	cowList, err := s.ParseCowIds(ctx, currentUser.PastureId, req.CowIds)
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
 
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
 	if err != nil {
-		return nil, xerr.Customf("获取当前用户失败: %s", err.Error())
+		return nil, xerr.WithStack(err)
 	}
 
 	for _, cow := range cowList {
@@ -93,15 +93,20 @@ func (s *StoreEntry) PregnantCheckDataCheck(ctx context.Context, req *pasturePb.
 		return nil, xerr.Custom("请选择相关牛只")
 	}
 
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	pregnantCheckBatchModelList := make([]*PregnantCheckBatchModel, 0)
 	for _, pregnantCheckData := range req.Item {
-		operationUser, err := s.GetSystemUserById(ctx, int64(pregnantCheckData.OperationId))
+		operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(pregnantCheckData.OperationId))
 		if err != nil {
 			zaplog.Error("PregnantCheckDataCheck", zap.Any("id", pregnantCheckData.OperationId), zap.Any("error", err.Error()))
 			return nil, xerr.Customf("获取操作人员信息失败")
 		}
 		pregnantCheckData.OperationName = operationUser.Name
-		cow, err := s.GetCowInfoByCowId(ctx, int64(pregnantCheckData.CowId))
+		cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(pregnantCheckData.CowId))
 		if err != nil {
 			return nil, xerr.WithStack(err)
 		}

+ 6 - 1
module/backend/event_cow_log.go

@@ -9,8 +9,13 @@ import (
 	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 )
 
+type EventEventLogHandle interface {
+	SubmitEventLog()
+}
+
 func (s *StoreEntry) SubmitEventLog(
 	ctx context.Context,
+	currentUser *model.SystemUser,
 	cow *model.Cow,
 	eventType pasturePb.EventType_Kind,
 	exposeEstrusType pasturePb.ExposeEstrusType_Kind,
@@ -20,7 +25,7 @@ func (s *StoreEntry) SubmitEventLog(
 		desc, remarks = "", ""
 		eventTypeName = s.EventTypeMap()[eventType]
 		eventAt       = int64(0)
-		penMap        = s.PenMap(ctx)
+		penMap        = s.PenMap(ctx, currentUser.PastureId)
 		cowTypeMap    = s.CowTypeMap()
 		operationUser = &model.SystemUser{}
 	)

+ 93 - 61
module/backend/event_health.go

@@ -19,40 +19,45 @@ import (
 
 // CowDiseaseCreate 牛只发病提交
 func (s *StoreEntry) CowDiseaseCreate(ctx context.Context, req *pasturePb.EventCowDiseaseRequest, source string) error {
+	currUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return xerr.Custom("登录信息错误,请退出重新登录")
+	}
 	// 牛只信息
-	cow, err := s.GetCowInfoByCowId(ctx, int64(req.CowId))
+	cow, err := s.GetCowInfoByCowId(ctx, currUser.PastureId, int64(req.CowId))
 	if err != nil {
 		return xerr.Customf("牛只信息错误: %d", req.CowId)
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, currUser.PastureId, int64(req.OperationId))
 	if err != nil {
 		return xerr.Customf("请检查操作人信息")
 	}
 
-	currUser, err := s.GetCurrentSystemUser(ctx)
-	if err != nil {
-		return xerr.Custom("登录信息错误,请退出重新登录")
-	}
-
-	disease, err := s.GetDiseaseById(ctx, req.DiseaseId)
+	disease, err := s.GetDiseaseById(ctx, currUser.PastureId, req.DiseaseId)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 
 	newEventCowDisease := model.NewEventCowDisease(cow, disease, req, operationUser, currUser)
 	defer func() {
-		if req.PenId > 0 {
-			s.UpdateCowPenId(ctx, int64(req.CowId), int64(req.PenId))
-		}
-
 		// 更新牛只健康状态
 		if newEventCowDisease.HealthStatus == pasturePb.HealthStatus_Disease || newEventCowDisease.HealthStatus == pasturePb.HealthStatus_Treatment {
+			cow.EventHealthStatusUpdate(pasturePb.HealthStatus_Disease)
 			s.DB.Model(new(model.Cow)).
+				Select("health_status").
 				Where("id = ?", req.CowId).
-				Updates(map[string]interface{}{
-					"health_status": pasturePb.HealthStatus_Disease,
-				})
+				Updates(cow)
+		}
+
+		if req.PenId > 0 {
+			penMap := s.PenMap(ctx, currUser.PastureId)
+			penData, ok := penMap[req.PenId]
+			if !ok {
+				return
+			}
+			cow.EventPenUpdate(penData)
+			s.DB.Model(new(model.Cow)).Select("pen_id,pen_name").Where("id = ?", cow.Id).Updates(cow)
 		}
 	}()
 	// PC端直接跳过诊断过程
@@ -79,12 +84,12 @@ func (s *StoreEntry) CowDiseaseCreate(ctx context.Context, req *pasturePb.EventC
 		isCreatePrescription = true
 
 		if req.PrescriptionId > 0 {
-			prescription, err = s.GetPrescriptionById(ctx, req.PrescriptionId)
+			prescription, err = s.GetPrescriptionById(ctx, currUser.PastureId, req.PrescriptionId)
 			if err != nil {
 				return xerr.WithStack(err)
 			}
 
-			prescriptionDrugs, err := s.PrescriptionDrugsByPrescriptionId(ctx, prescription.Id)
+			prescriptionDrugs, err := s.PrescriptionDrugsByPrescriptionId(ctx, currUser.PastureId, prescription.Id)
 			if err != nil {
 				return xerr.WithStack(err)
 			}
@@ -100,8 +105,10 @@ func (s *StoreEntry) CowDiseaseCreate(ctx context.Context, req *pasturePb.EventC
 
 		// 已有的处方使用次数+1
 		if req.PrescriptionId > 0 {
-			if err = tx.Model(new(model.Prescription)).Where("id = ?", req.PrescriptionId).
-				Update("use_count", gorm.Expr("use_count + 1")).Error; err != nil {
+			prescription.EventUseCountUpdate()
+			if err = tx.Model(new(model.Prescription)).
+				Where("id = ?", prescription.Id).
+				Updates(prescription).Error; err != nil {
 				return xerr.WithStack(err)
 			}
 		}
@@ -113,14 +120,14 @@ func (s *StoreEntry) CowDiseaseCreate(ctx context.Context, req *pasturePb.EventC
 				ApplicableDiseaseIds: []int32{req.DiseaseId},
 				IsShow:               pasturePb.IsShow_Ok,
 			}
-			newPrescription := model.NewPrescription(newPrescriptionRequest, fmt.Sprintf("%d", disease.Id), 1, 0, 0, currUser)
+			newPrescription := model.NewPrescription(currUser.PastureId, newPrescriptionRequest, fmt.Sprintf("%d", disease.Id), 1, 0, 0, currUser)
 			newPrescription.UseCount += 1
 			if err = tx.Model(new(model.Prescription)).Create(newPrescription).Error; err != nil {
 				return xerr.WithStack(err)
 			}
 			prescription = newPrescription
 
-			newPrescriptionDrugs := model.NewPrescriptionDrugs(prescription.Id, req.PrescriptionDetail)
+			newPrescriptionDrugs := model.NewPrescriptionDrugs(currUser.PastureId, prescription.Id, req.PrescriptionDetail)
 			if err = tx.Model(new(model.PrescriptionDrugs)).Create(newPrescriptionDrugs).Error; err != nil {
 				return xerr.WithStack(err)
 			}
@@ -158,11 +165,16 @@ func (s *StoreEntry) CowDiseaseCreate(ctx context.Context, req *pasturePb.EventC
 
 // CowDiseaseList 发病牛只清单
 func (s *StoreEntry) CowDiseaseList(ctx context.Context, req *pasturePb.SearchEventCowTreatmentRequest, pagination *pasturePb.PaginationModel) (*pasturePb.EventCowDiseaseResponse, error) {
+	currUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("登录信息错误,请退出重新登录")
+	}
+
 	cowDiseaseList := make([]*model.EventCowDisease, 0)
 	var count int64 = 0
 	pref := s.DB.Select("a.*,b.name").Table(fmt.Sprintf("%s as a", new(model.EventCowDisease).TableName())).
 		Joins(fmt.Sprintf("JOIN %s AS b on a.pen_id = b.id", new(model.Pen).TableName())).
-		Where("a.diagnosed_result < ?", pasturePb.IsShow_No)
+		Where("a.diagnosed_result < ?", pasturePb.IsShow_No).Where("a.pasture_id = ?", currUser.PastureId)
 
 	if len(req.CowIds) > 0 {
 		pref.Where("a.cow_id IN ?", req.CowIds)
@@ -192,7 +204,7 @@ func (s *StoreEntry) CowDiseaseList(ctx context.Context, req *pasturePb.SearchEv
 		pref.Where("a.disease_at BETWEEN ? AND ?", req.DiseasedStartAt, req.DiseaseEndAt)
 	}
 
-	if err := pref.Order("a.id desc").
+	if err = pref.Order("a.id desc").
 		Count(&count).Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
 		Find(&cowDiseaseList).Error; err != nil {
@@ -214,22 +226,29 @@ func (s *StoreEntry) CowDiseaseList(ctx context.Context, req *pasturePb.SearchEv
 
 // CowDiseaseDiagnose 发病牛只诊断
 func (s *StoreEntry) CowDiseaseDiagnose(ctx context.Context, req *pasturePb.CowDiagnosedRequest) error {
-	cow, err := s.GetCowInfoByCowId(ctx, int64(req.CowId))
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
+	cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(req.CowId))
 	if err != nil {
 		return xerr.Customf("错误的牛只信息: %d", req.CowId)
 	}
 
 	eventCowDisease := &model.EventCowDisease{}
-	if err = s.DB.Where("cow_id = ?", req.CowId).
+	if err = s.DB.Model(new(model.EventCowDisease)).
+		Where("cow_id = ?", req.CowId).
 		Where("id = ?", req.Id).
 		Where("health_status = ?", pasturePb.HealthStatus_Health).
+		Where("pasture_id = ?", currentUser.PastureId).
 		First(eventCowDisease).Error; err != nil {
+		zaplog.Error("CowDiseaseDiagnose", zap.Any("req", req), zap.Any("currentUser", currentUser))
 		return xerr.Custom("异常牛只数据")
 	}
 
-	currentUser, err := s.GetCurrentSystemUser(ctx)
-	if err != nil {
-		return xerr.WithStack(err)
+	if eventCowDisease == nil || eventCowDisease.Id <= 0 {
+		return xerr.Custom("异常牛只数据")
 	}
 
 	if req.DiagnosedResult == pasturePb.IsShow_No {
@@ -245,11 +264,11 @@ func (s *StoreEntry) CowDiseaseDiagnose(ctx context.Context, req *pasturePb.CowD
 	}
 
 	// 已发病
-	disease, err := s.GetDiseaseById(ctx, req.DiseaseId)
+	disease, err := s.GetDiseaseById(ctx, currentUser.PastureId, req.DiseaseId)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
-	systemUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
+	systemUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
@@ -264,7 +283,7 @@ func (s *StoreEntry) CowDiseaseDiagnose(ctx context.Context, req *pasturePb.CowD
 			return xerr.WithStack(err)
 		}
 
-		cow.EventDiseaseUpdate(pasturePb.HealthStatus_Disease)
+		cow.EventHealthStatusUpdate(pasturePb.HealthStatus_Disease)
 		if err = tx.Model(cow).
 			Select("health_status").
 			Where("id = ?", cow.Id).
@@ -281,8 +300,13 @@ func (s *StoreEntry) CowDiseaseDiagnose(ctx context.Context, req *pasturePb.CowD
 
 // CowDiseaseTreatment 发病牛只治疗
 func (s *StoreEntry) CowDiseaseTreatment(ctx context.Context, req *pasturePb.CowTreatmentRequest) error {
+	currUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	eventCowDisease := &model.EventCowDisease{}
-	if err := s.DB.Where("cow_id = ?", req.CowId).
+	if err = s.DB.Where("cow_id = ?", req.CowId).
 		Where("id = ?", req.Id).
 		First(eventCowDisease).Error; err != nil {
 		return xerr.WithStack(err)
@@ -293,32 +317,29 @@ func (s *StoreEntry) CowDiseaseTreatment(ctx context.Context, req *pasturePb.Cow
 		return xerr.Custom("异常牛只数据")
 	}
 
-	systemUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, currUser.PastureId, int64(req.OperationId))
 	if err != nil {
 		return xerr.Customf("操作人数据异常: %d", req.OperationId)
 	}
 
-	prescription, err := s.GetPrescriptionById(ctx, req.PrescriptionId)
+	prescription, err := s.GetPrescriptionById(ctx, currUser.PastureId, req.PrescriptionId)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 
-	currUser, err := s.GetCurrentSystemUser(ctx)
-	if err != nil {
-		return xerr.WithStack(err)
-	}
-	cow, err := s.GetCowInfoByCowId(ctx, int64(req.CowId))
+	cow, err := s.GetCowInfoByCowId(ctx, currUser.PastureId, int64(req.CowId))
 	if err != nil {
 		return xerr.Customf("异常牛数据: %d", req.CowId)
 	}
 
-	disease, err := s.GetDiseaseById(ctx, eventCowDisease.DiagnoseId)
+	disease, err := s.GetDiseaseById(ctx, currUser.PastureId, eventCowDisease.DiagnoseId)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 	req.DiseaseName = disease.Name
 	req.DiseaseType = disease.DiseaseType
-	prescriptionDrugs, err := s.PrescriptionDrugsByPrescriptionId(ctx, prescription.Id)
+
+	prescriptionDrugs, err := s.PrescriptionDrugsByPrescriptionId(ctx, currUser.PastureId, prescription.Id)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
@@ -348,7 +369,7 @@ func (s *StoreEntry) CowDiseaseTreatment(ctx context.Context, req *pasturePb.Cow
 		healthStatus = pasturePb.HealthStatus_Dead
 	}
 	diseaseTypeMap := s.DiseaseTypeMap()
-	newEventCowTreatment := model.NewEventCowTreatment(prescription, req, diseaseTypeMap, systemUser, currUser)
+	newEventCowTreatment := model.NewEventCowTreatment(prescription, req, diseaseTypeMap, operationUser, currUser)
 	if err = s.DB.Transaction(func(tx *gorm.DB) error {
 		if err = tx.Create(newEventCowTreatment).Error; err != nil {
 			return xerr.WithStack(err)
@@ -363,7 +384,7 @@ func (s *StoreEntry) CowDiseaseTreatment(ctx context.Context, req *pasturePb.Cow
 			return xerr.WithStack(err)
 		}
 
-		cow.EventDiseaseUpdate(healthStatus)
+		cow.EventHealthStatusUpdate(healthStatus)
 		if err = tx.Model(new(model.Cow)).
 			Select("health_status").
 			Where("id = ?", req.CowId).
@@ -387,9 +408,17 @@ func (s *StoreEntry) CowDiseaseTreatment(ctx context.Context, req *pasturePb.Cow
 }
 
 func (s *StoreEntry) DiseaseSuggestPrescription(ctx context.Context, diseaseId int64) (*pasturePb.ConfigOptionsListResponse, error) {
+	currUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	res := make([]*pasturePb.ConfigOptionsList, 0)
 	prescriptionList := make([]*model.Prescription, 0)
-	if err := s.DB.Model(new(model.Prescription)).Where("is_show = ?", pasturePb.IsShow_Ok).Find(&prescriptionList).Error; err != nil {
+	if err = s.DB.Model(new(model.Prescription)).
+		Where("is_show = ?", pasturePb.IsShow_Ok).
+		Where("pasture_id = ?", currUser.PastureId).
+		Find(&prescriptionList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
 
@@ -419,10 +448,15 @@ func (s *StoreEntry) CowDiseaseTreatmentDetail(
 	req *pasturePb.EventCowTreatmentDetailRequest,
 	pagination *pasturePb.PaginationModel,
 ) (*pasturePb.EventCowTreatmentDetailResponse, error) {
+	currUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	eventCowDiseaseList := make([]*model.EventCowDisease, 0)
 	var count int64 = 0
 	pref := s.DB.Model(new(model.EventCowDisease)).
-		Where("cow_id = ?", req.CowId)
+		Where("cow_id = ?", req.CowId).Where("pasture_id = ?", currUser.PastureId)
 
 	if req.DiseaseId > 0 {
 		pref.Where("disease_id = ?", req.DiseaseId)
@@ -432,7 +466,7 @@ func (s *StoreEntry) CowDiseaseTreatmentDetail(
 		pref.Where("disease_at BETWEEN ? AND ?", req.DiseaseStartAt, req.DiseaseEndAt)
 	}
 
-	if err := pref.Count(&count).
+	if err = pref.Count(&count).
 		Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
 		Order("id desc").
@@ -468,9 +502,15 @@ func (s *StoreEntry) CowDiseaseTreatmentDetail(
 }
 
 func (s *StoreEntry) CowDiseaseCurable(ctx context.Context, req *pasturePb.EventCowCurableRequest) error {
+	currUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	eventCowDiseaseList := make([]*model.EventCowDisease, 0)
-	if err := s.DB.Where("id IN ?", req.Ids).
+	if err = s.DB.Where("id IN ?", req.Ids).
 		Where("health_status = ?", pasturePb.HealthStatus_Treatment).
+		Where("pasture_id = ?", currUser.PastureId).
 		Find(&eventCowDiseaseList).Error; err != nil {
 		zaplog.Error("GetEventCowDiseaseList", zap.Any("err", err), zap.Any("req", req))
 		return xerr.Custom("异常数据")
@@ -480,23 +520,15 @@ func (s *StoreEntry) CowDiseaseCurable(ctx context.Context, req *pasturePb.Event
 		return nil
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, currUser.PastureId, int64(req.OperationId))
 	if err != nil {
 		return xerr.Customf("该用户不存在: %d", req.OperationId)
 	}
+
 	eventCowTreatmentList := make([]*model.EventCowTreatment, 0)
 	for _, v := range eventCowDiseaseList {
-		eventCowTreatmentList = append(eventCowTreatmentList, &model.EventCowTreatment{
-			CowId:           v.CowId,
-			CowDiseaseId:    v.Id,
-			DiseaseId:       int64(v.DiseaseId),
-			DiseaseName:     v.DiseaseName,
-			TreatmentResult: pasturePb.TreatmentResult_Curable,
-			OperationId:     operationUser.Id,
-			OperationName:   operationUser.Name,
-			Remarks:         req.Remarks,
-			TreatmentAt:     int64(req.CurableAt),
-		})
+		newEventCowTreatment := model.NewEventCowCurableTreatment(currUser, operationUser, v, req.Remarks, int64(req.CurableAt))
+		eventCowTreatmentList = append(eventCowTreatmentList, newEventCowTreatment)
 	}
 
 	if len(eventCowTreatmentList) <= 0 {
@@ -515,12 +547,12 @@ func (s *StoreEntry) CowDiseaseCurable(ctx context.Context, req *pasturePb.Event
 				return xerr.WithStack(err)
 			}
 
-			cow, err = s.GetCowInfoByCowId(ctx, eventCowDisease.CowId)
+			cow, err = s.GetCowInfoByCowId(ctx, currUser.PastureId, eventCowDisease.CowId)
 			if err != nil {
 				return xerr.WithStack(err)
 			}
 			// 更新牛只健康状态
-			cow.EventDiseaseUpdate(pasturePb.HealthStatus_Curable)
+			cow.EventHealthStatusUpdate(pasturePb.HealthStatus_Curable)
 			if err = tx.Model(cow).
 				Select("health_status").
 				Where("id = ?", eventCowDisease.CowId).

+ 29 - 13
module/backend/goods.go

@@ -16,10 +16,15 @@ import (
 )
 
 func (s *StoreEntry) DrugsList(ctx context.Context, req *pasturePb.SearchDrugsRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchDrugsResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	drugsList := make([]*model.Drugs, 0)
 	var count int64 = 0
 
-	pref := s.DB.Model(new(model.Drugs))
+	pref := s.DB.Model(new(model.Drugs)).Where("pasture_id = ?", currentUser.PastureId)
 	if req.Name != "" {
 		pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
 	}
@@ -32,7 +37,7 @@ func (s *StoreEntry) DrugsList(ctx context.Context, req *pasturePb.SearchDrugsRe
 		pref.Where("category_id = ?", req.CategoryId)
 	}
 
-	if err := pref.Order("id desc").Count(&count).Limit(int(pagination.PageSize)).Offset(int(pagination.PageOffset)).
+	if err = pref.Order("id desc").Count(&count).Limit(int(pagination.PageSize)).Offset(int(pagination.PageOffset)).
 		Find(&drugsList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -52,8 +57,9 @@ func (s *StoreEntry) DrugsList(ctx context.Context, req *pasturePb.SearchDrugsRe
 func (s *StoreEntry) DrugsCreateOrUpdate(ctx context.Context, req *pasturePb.SearchDrugsList) error {
 	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil {
-		return xerr.Custom("登录人信息失效")
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
 	}
+
 	req.CategoryName = s.DrugCategoryMaps()[req.CategoryId]
 	req.UnitName = s.UnitMap()[req.Unit]
 	req.UnitName = s.DrugUsageMaps()[req.Usage]
@@ -73,15 +79,20 @@ func (s *StoreEntry) DrugsCreateOrUpdate(ctx context.Context, req *pasturePb.Sea
 }
 
 func (s *StoreEntry) MedicalEquipmentList(ctx context.Context, req *pasturePb.SearchMedicalEquipmentRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchMedicalEquipmentResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	medicalEquipmentList := make([]*model.MedicalEquipment, 0)
 	var count int64 = 0
 
-	pref := s.DB.Model(new(model.MedicalEquipment))
+	pref := s.DB.Model(new(model.MedicalEquipment)).Where("pasture_id = ?", currentUser.PastureId)
 	if req.Name != "" {
 		pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
 	}
 
-	if err := pref.Order("id desc").Count(&count).Limit(int(pagination.PageSize)).Offset(int(pagination.PageOffset)).
+	if err = pref.Order("id desc").Count(&count).Limit(int(pagination.PageSize)).Offset(int(pagination.PageOffset)).
 		Find(&medicalEquipmentList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -102,7 +113,7 @@ func (s *StoreEntry) MedicalEquipmentList(ctx context.Context, req *pasturePb.Se
 func (s *StoreEntry) MedicalEquipmentCreateOrUpdate(ctx context.Context, req *pasturePb.SearchMedicalEquipmentList) error {
 	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil {
-		return xerr.Custom("登录人信息失效")
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
 	}
 	newDrugs := model.NewMedicalEquipment(req, currentUser)
 	if req.Id <= 0 {
@@ -120,7 +131,7 @@ func (s *StoreEntry) MedicalEquipmentCreateOrUpdate(ctx context.Context, req *pa
 func (s *StoreEntry) NeckRingCreateOrUpdate(ctx context.Context, req *pasturePb.NeckRingCreateRequest) error {
 	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil {
-		return xerr.Custom("登录人信息失效")
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
 	}
 
 	if req.Items == nil || len(req.Items) == 0 {
@@ -132,20 +143,19 @@ func (s *StoreEntry) NeckRingCreateOrUpdate(ctx context.Context, req *pasturePb.
 			switch req.Status {
 			// 绑定
 			case pasturePb.NeckRingOperationStatus_Bind:
-				_, err = s.GetCowInfoByCowId(ctx, int64(v.CowId))
+				_, err = s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(v.CowId))
 				if err != nil {
 					return xerr.Customf("该牛不存在")
 				}
-				neckRing, ok := s.NeckRingIsExist(ctx, v.Number)
+				neckRing, ok := s.NeckRingIsExist(ctx, currentUser.PastureId, v.Number)
 				if !ok {
-					newNeckRing := model.NewNeckRing(v.Number, int64(v.CowId), currentUser)
+					newNeckRing := model.NewNeckRing(currentUser.PastureId, v.Number, int64(v.CowId), currentUser)
 					if err = tx.Create(newNeckRing).Error; err != nil {
 						return xerr.WithStack(err)
 					}
 				}
-
 				if ok {
-					neckRing.Update(int64(v.CowId))
+					neckRing.EventBindUpdate(int64(v.CowId))
 					if err = tx.Model(new(model.NeckRing)).
 						Select("cow_id,wear_at").
 						Where("id = ?", neckRing.Id).
@@ -177,7 +187,7 @@ func (s *StoreEntry) NeckRingCreateOrUpdate(ctx context.Context, req *pasturePb.
 				}
 
 				if err = tx.Model(new(model.Cow)).
-					Where("neck_ring_number = ?", v.Number).
+					Where("ear_number = ?", v.Number).
 					Updates(map[string]interface{}{
 						"neck_ring_number": "",
 					}).Error; err != nil {
@@ -213,11 +223,17 @@ func (s *StoreEntry) NeckRingCreateOrUpdate(ctx context.Context, req *pasturePb.
 }
 
 func (s *StoreEntry) NeckRingList(ctx context.Context, req *pasturePb.SearchNeckRingRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchNeckRingResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	neckRingLogList := make([]*model.NeckRing, 0)
 	var count int64 = 0
 
 	pref := s.DB.Model(new(model.NeckRing)).
 		Where("status >= ?", pasturePb.NeckRingStatus_Unbind).
+		Where("pasture_id = ?", currentUser.PastureId).
 		Where("number != ''")
 	if req.Status > 0 {
 		pref.Where("status = ?", req.Status)

+ 2 - 2
module/backend/interface.go

@@ -129,7 +129,7 @@ type PastureManageService interface {
 	CreatedOrUpdateImmunization(ctx context.Context, req *pasturePb.ImmunizationRequest) error
 	ImmunizationIsShow(ctx context.Context, id int64) error
 
-	SystemBasicEdit(ctx context.Context, req *pasturePb.BaseDataConfig) error
+	SystemBasicEdit(ctx context.Context, req *pasturePb.BaseDataConfigBatch) error
 	SystemBasicList(ctx context.Context) (*pasturePb.SearchBaseDataConfigResponse, error)
 }
 
@@ -202,7 +202,7 @@ type EventService interface {
 	DepartureBatch(ctx context.Context, req *pasturePb.EventDepartureBatch) error
 
 	// SubmitEventLog 记录提交事件结果日志
-	SubmitEventLog(ctx context.Context, cow *model.Cow, eventType pasturePb.EventType_Kind, exposeEstrusType pasturePb.ExposeEstrusType_Kind, req interface{}) *model.EventCowLog
+	SubmitEventLog(ctx context.Context, currentUser *model.SystemUser, cow *model.Cow, eventType pasturePb.EventType_Kind, exposeEstrusType pasturePb.ExposeEstrusType_Kind, req interface{}) *model.EventCowLog
 }
 
 //go:generate mockgen -destination mock/CowService.go -package kptservicemock kpt-pasture/module/backend CowService

+ 77 - 35
module/backend/prescription.go

@@ -238,7 +238,11 @@ func (s *StoreEntry) SearchPrescriptionList(ctx context.Context, req *pasturePb.
 }
 
 func (s *StoreEntry) CreateOrUpdatePrescription(ctx context.Context, req *pasturePb.PrescriptionRequest) error {
-	currUser, _ := s.GetCurrentSystemUser(ctx)
+	currUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	var maxUseDays, maxMeatExpiredDays, maxMilkExpiredDays int32 = 0, 0, 0
 	for _, v := range req.DrugsList {
 		if v.DrugsId <= 0 {
@@ -251,7 +255,7 @@ func (s *StoreEntry) CreateOrUpdatePrescription(ctx context.Context, req *pastur
 			maxUseDays = v.UseDays
 		}
 
-		drugs, err := s.GetDrugsById(ctx, int64(v.DrugsId))
+		drugs, err := s.GetDrugsById(ctx, currUser.PastureId, int64(v.DrugsId))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
@@ -273,16 +277,16 @@ func (s *StoreEntry) CreateOrUpdatePrescription(ctx context.Context, req *pastur
 		}
 		applicableDisease = strings.Join(applicableDiseaseIds, ",")
 	}
-	newPrescription := model.NewPrescription(req, applicableDisease, maxUseDays, maxMeatExpiredDays, maxMilkExpiredDays, currUser)
+	newPrescription := model.NewPrescription(currUser.PastureId, req, applicableDisease, maxUseDays, maxMeatExpiredDays, maxMilkExpiredDays, currUser)
 	if req.Id > 0 {
 		prescription := &model.Prescription{Id: req.Id}
-		if err := s.DB.Model(&model.Prescription{}).First(prescription).Error; err != nil {
+		if err = s.DB.Model(&model.Prescription{}).First(prescription).Error; err != nil {
 			if !errors.Is(err, gorm.ErrRecordNotFound) {
 				return xerr.WithStack(err)
 			}
 		}
-		if err := s.DB.Transaction(func(tx *gorm.DB) error {
-			if err := tx.Model(&model.Prescription{}).Where(map[string]interface{}{
+		if err = s.DB.Transaction(func(tx *gorm.DB) error {
+			if err = tx.Model(&model.Prescription{}).Where(map[string]interface{}{
 				"id": req.Id,
 			}).Updates(map[string]interface{}{
 				"name":               newPrescription.Name,
@@ -295,13 +299,13 @@ func (s *StoreEntry) CreateOrUpdatePrescription(ctx context.Context, req *pastur
 				return xerr.WithStack(err)
 			}
 
-			if err := tx.Model(new(model.PrescriptionDrugs)).Where("prescription_id", req.Id).
+			if err = tx.Model(new(model.PrescriptionDrugs)).Where("prescription_id", req.Id).
 				Update("is_show", pasturePb.IsShow_No).Error; err != nil {
 				return xerr.WithStack(err)
 			}
 			// 创建处方药品
-			newPrescriptionDrugs := model.NewPrescriptionDrugs(req.Id, req.DrugsList)
-			if err := tx.Create(&newPrescriptionDrugs).Error; err != nil {
+			newPrescriptionDrugs := model.NewPrescriptionDrugs(currUser.PastureId, req.Id, req.DrugsList)
+			if err = tx.Create(&newPrescriptionDrugs).Error; err != nil {
 				return xerr.WithStack(err)
 			}
 
@@ -313,14 +317,14 @@ func (s *StoreEntry) CreateOrUpdatePrescription(ctx context.Context, req *pastur
 	}
 
 	// 创建处方
-	if err := s.DB.Transaction(func(tx *gorm.DB) error {
+	if err = s.DB.Transaction(func(tx *gorm.DB) error {
 		// 创建处方
-		if err := tx.Create(&newPrescription).Error; err != nil {
+		if err = tx.Create(&newPrescription).Error; err != nil {
 			return xerr.WithStack(err)
 		}
 		// 创建处方药品
-		newPrescriptionDrugs := model.NewPrescriptionDrugs(newPrescription.Id, req.DrugsList)
-		if err := tx.Create(&newPrescriptionDrugs).Error; err != nil {
+		newPrescriptionDrugs := model.NewPrescriptionDrugs(currUser.PastureId, newPrescription.Id, req.DrugsList)
+		if err = tx.Create(&newPrescriptionDrugs).Error; err != nil {
 			return xerr.WithStack(err)
 		}
 		return nil
@@ -331,12 +335,17 @@ func (s *StoreEntry) CreateOrUpdatePrescription(ctx context.Context, req *pastur
 }
 
 func (s *StoreEntry) PrescriptionDetail(ctx context.Context, id int64) (*pasturePb.PrescriptionDetailResponse, error) {
-	prescriptionData, err := s.GetPrescriptionById(ctx, int32(id))
+	currUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
+	prescriptionData, err := s.GetPrescriptionById(ctx, currUser.PastureId, int32(id))
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
 
-	prescriptionDrugsList, err := s.PrescriptionDrugsByPrescriptionId(ctx, int32(id))
+	prescriptionDrugsList, err := s.PrescriptionDrugsByPrescriptionId(ctx, currUser.PastureId, int32(id))
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -356,14 +365,21 @@ func (s *StoreEntry) PrescriptionDetail(ctx context.Context, id int64) (*pasture
 }
 
 func (s *StoreEntry) ImmunizationList(ctx context.Context, req *pasturePb.ImmunizationRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchImmunizationResponse, error) {
+	currUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	immunizationList := make([]*model.ImmunizationPlan, 0)
 	var count int64 = 0
-	pref := s.DB.Model(new(model.ImmunizationPlan))
+	pref := s.DB.Model(new(model.ImmunizationPlan)).
+		Where("pasture_id = ?", currUser.PastureId).
+		Where("is_show = ?", pasturePb.IsShow_Ok)
 	if req.Name != "" {
 		pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
 	}
 
-	if err := pref.Order("id desc").Count(&count).Limit(int(pagination.PageSize)).Offset(int(pagination.PageOffset)).
+	if err = pref.Order("id desc").Count(&count).Limit(int(pagination.PageSize)).Offset(int(pagination.PageOffset)).
 		Find(&immunizationList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -389,12 +405,17 @@ func (s *StoreEntry) CreatedOrUpdateImmunization(ctx context.Context, req *pastu
 		systemUser   *model.SystemUser
 	)
 
+	currUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	if req.Conditions == pasturePb.ImmunizationConditions_Other_Vaccine_After && req.ImmunizationPlanId <= 0 {
 		return xerr.Custom("请选择具体的免疫计划")
 	}
 
 	if req.ImmunizationPlanId > 0 {
-		otherImmunization, err := s.GetImmunizationById(ctx, int64(req.ImmunizationPlanId))
+		otherImmunization, err := s.GetImmunizationById(ctx, currUser.PastureId, int64(req.ImmunizationPlanId))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
@@ -402,11 +423,11 @@ func (s *StoreEntry) CreatedOrUpdateImmunization(ctx context.Context, req *pastu
 	}
 
 	if req.Id > 0 {
-		immunization, err = s.GetImmunizationById(ctx, int64(req.Id))
+		immunization, err = s.GetImmunizationById(ctx, currUser.PastureId, int64(req.Id))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
-		systemUser, _ = s.GetSystemUserById(ctx, immunization.OperationId)
+		systemUser, _ = s.GetSystemUserById(ctx, currUser.PastureId, immunization.OperationId)
 	} else {
 		systemUser, _ = s.GetCurrentSystemUser(ctx)
 	}
@@ -432,10 +453,18 @@ func (s *StoreEntry) CreatedOrUpdateImmunization(ctx context.Context, req *pastu
 }
 
 func (s *StoreEntry) ImmunizationIsShow(ctx context.Context, id int64) error {
+	currUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	immunizationPlan := &model.ImmunizationPlan{
 		Id: id,
 	}
-	if err := s.DB.First(immunizationPlan).Error; err != nil {
+	if err = s.DB.Model(new(model.ImmunizationPlan)).
+		Where("id = ?", id).
+		Where("pasture_id = ?", currUser.PastureId).
+		First(immunizationPlan).Error; err != nil {
 		if errors.Is(err, gorm.ErrRecordNotFound) {
 			return xerr.Custom("该免疫计划不存在")
 		}
@@ -446,15 +475,22 @@ func (s *StoreEntry) ImmunizationIsShow(ctx context.Context, id int64) error {
 		isShow = pasturePb.IsShow_Ok
 	}
 
-	if err := s.DB.Model(immunizationPlan).Update("is_show", isShow).Error; err != nil {
+	if err = s.DB.Model(immunizationPlan).Update("is_show", isShow).Error; err != nil {
 		return xerr.WithStack(err)
 	}
 	return nil
 }
 
 func (s *StoreEntry) SystemBasicList(ctx context.Context) (*pasturePb.SearchBaseDataConfigResponse, error) {
+	currUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+	}
+
 	systemBasicList := make([]*model.SystemBasic, 0)
-	if err := s.DB.Model(new(model.SystemBasic)).Where("is_show = ?", pasturePb.IsShow_Ok).Find(&systemBasicList).Error; err != nil {
+	if err = s.DB.Model(new(model.SystemBasic)).
+		Where("pasture_id = ?", currUser.PastureId).
+		Where("is_show = ?", pasturePb.IsShow_Ok).Find(&systemBasicList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
 	return &pasturePb.SearchBaseDataConfigResponse{
@@ -467,23 +503,29 @@ func (s *StoreEntry) SystemBasicList(ctx context.Context) (*pasturePb.SearchBase
 	}, nil
 }
 
-func (s *StoreEntry) SystemBasicEdit(ctx context.Context, req *pasturePb.BaseDataConfig) error {
+func (s *StoreEntry) SystemBasicEdit(ctx context.Context, req *pasturePb.BaseDataConfigBatch) error {
 	currentUser, err := s.GetCurrentSystemUser(ctx)
 	if err != nil {
 		return xerr.Custom("当前用户信息错误,请退出重新登录")
 	}
 
-	systemBasic := &model.SystemBasic{Id: req.Id}
-	if err = s.DB.Model(systemBasic).Where("is_show = ?", pasturePb.IsShow_Ok).First(systemBasic).Error; err != nil {
-		zaplog.Error("SystemBasicEdit", zap.Any("err", err), zap.Any("req", req))
-		return xerr.Customf("该配置信息不存在: %d", req.Id)
-	}
-	systemBasic.EditUpdate(req.MinValue, req.MaxValue, req.WeekValue, currentUser)
-	if err = s.DB.Model(systemBasic).Select("min_value,max_value,week_value,operation_id,operation_name").
-		Updates(systemBasic).Error; err != nil {
-		zaplog.Error("SystemBasicEdit", zap.Any("err", err), zap.Any("req", req))
-		return xerr.WithStack(err)
-	}
+	for _, v := range req.Item {
+		systemBasic := &model.SystemBasic{Id: v.Id}
+		if err = s.DB.Model(systemBasic).
+			Where("is_show = ?", pasturePb.IsShow_Ok).
+			Where("pasture_id = ?", currentUser.PastureId).
+			First(systemBasic).Error; err != nil {
+			zaplog.Error("SystemBasicEdit", zap.Any("err", err), zap.Any("req", req))
+			return xerr.Customf("该配置信息不存在: %d", v.Id)
+		}
 
+		systemBasic.EditUpdate(currentUser.PastureId, v.MinValue, v.MaxValue, v.WeekValue, currentUser)
+		if err = s.DB.Model(systemBasic).
+			Select("min_value", "max_value", "week_value", "operation_id", "operation_name").
+			Updates(systemBasic).Error; err != nil {
+			zaplog.Error("SystemBasicEdit", zap.Any("err", err), zap.Any("req", req))
+			return xerr.WithStack(err)
+		}
+	}
 	return nil
 }

+ 61 - 48
module/backend/sql.go

@@ -8,8 +8,6 @@ import (
 	"kpt-pasture/store/kptstore"
 
 	operationPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/operation"
-	"gitee.com/xuyiping_admin/pkg/logger/zaplog"
-	"go.uber.org/zap"
 
 	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 	"gitee.com/xuyiping_admin/pkg/xerr"
@@ -49,7 +47,7 @@ func (s *StoreEntry) GetCurrentSystemUser(ctx context.Context) (*model.SystemUse
 	return systemUser, nil
 }
 
-func (s *StoreEntry) GetSystemUserById(ctx context.Context, userId int64) (*model.SystemUser, error) {
+func (s *StoreEntry) GetSystemUserById(ctx context.Context, pastureId, userId int64) (*model.SystemUser, error) {
 	systemUser := &model.SystemUser{Id: userId}
 	if err := s.DB.Model(new(model.SystemUser)).First(systemUser).Error; err != nil {
 		if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -60,7 +58,7 @@ func (s *StoreEntry) GetSystemUserById(ctx context.Context, userId int64) (*mode
 	return systemUser, nil
 }
 
-func (s *StoreEntry) SystemDeptList(ctx context.Context) ([]*model.SystemDept, error) {
+func (s *StoreEntry) SystemDeptList(ctx context.Context, pastureId int64) ([]*model.SystemDept, error) {
 	deptList := make([]*model.SystemDept, 0)
 	if err := s.DB.Model(new(model.SystemDept)).
 		Where("is_delete = ?", pasturePb.IsShow_Ok).
@@ -70,7 +68,7 @@ func (s *StoreEntry) SystemDeptList(ctx context.Context) ([]*model.SystemDept, e
 	return deptList, nil
 }
 
-func (s *StoreEntry) GetPenById(ctx context.Context, penId int32) (*model.Pen, error) {
+func (s *StoreEntry) GetPenById(ctx context.Context, pastureId int64, penId int32) (*model.Pen, error) {
 	penData := &model.Pen{Id: penId}
 	if err := s.DB.Model(new(model.Pen)).First(penData).Error; err != nil {
 		if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -81,18 +79,19 @@ func (s *StoreEntry) GetPenById(ctx context.Context, penId int32) (*model.Pen, e
 	return penData, nil
 }
 
-func (s *StoreEntry) GetPenList(ctx context.Context) ([]*model.Pen, error) {
+func (s *StoreEntry) GetPenList(ctx context.Context, pastureId int64) ([]*model.Pen, error) {
 	penList := make([]*model.Pen, 0)
 	if err := s.DB.Model(new(model.Pen)).
 		Where("is_delete = ?", pasturePb.IsShow_Ok).
+		Where("pasture_id = ?", pastureId).
 		Find(&penList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
 	return penList, nil
 }
 
-func (s *StoreEntry) PenMap(ctx context.Context) map[int32]*model.Pen {
-	penList, _ := s.GetPenList(ctx)
+func (s *StoreEntry) PenMap(ctx context.Context, pastureId int64) map[int32]*model.Pen {
+	penList, _ := s.GetPenList(ctx, pastureId)
 	penMap := make(map[int32]*model.Pen)
 	for _, v := range penList {
 		penMap[v.Id] = v
@@ -100,9 +99,10 @@ func (s *StoreEntry) PenMap(ctx context.Context) map[int32]*model.Pen {
 	return penMap
 }
 
-func (s *StoreEntry) GetCowInfoByCowId(ctx context.Context, cowId int64) (*model.Cow, error) {
+func (s *StoreEntry) GetCowInfoByCowId(ctx context.Context, pastureId, cowId int64) (*model.Cow, error) {
 	cowData := &model.Cow{Id: cowId}
 	if err := s.DB.Model(new(model.Cow)).
+		Where("pasture_id = ?", pastureId).
 		Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
 		First(cowData).Error; err != nil {
 		if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -113,9 +113,10 @@ func (s *StoreEntry) GetCowInfoByCowId(ctx context.Context, cowId int64) (*model
 	return cowData, nil
 }
 
-func (s *StoreEntry) GetCowInfoByCowIds(ctx context.Context, cowIds []int64) ([]*model.Cow, error) {
+func (s *StoreEntry) GetCowInfoByCowIds(ctx context.Context, pastureId int64, cowIds []int64) ([]*model.Cow, error) {
 	cowList := make([]*model.Cow, 0)
 	if err := s.DB.Model(&model.Cow{}).
+		Where("pasture_id = ?", pastureId).
 		Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
 		Where("id IN ?", cowIds).
 		Find(&cowList).Error; err != nil {
@@ -137,9 +138,13 @@ func (s *StoreEntry) GetTransferReasonInfo(ctx context.Context, reasonId int64)
 	return configTransferPenReasonData, nil
 }
 
-func (s *StoreEntry) GetCowWeightByLastSecond(ctx context.Context, cowId, lastWeightAt int64) (*model.EventWeight, error) {
+func (s *StoreEntry) GetCowWeightByLastSecond(ctx context.Context, pastureId, cowId, lastWeightAt int64) (*model.EventWeight, error) {
 	cowWeightData := &model.EventWeight{}
-	if err := s.DB.Model(new(model.EventWeight)).Where("cow_id = ?", cowId).Where("weight_at < ?", lastWeightAt).First(cowWeightData).Error; err != nil {
+	if err := s.DB.Model(new(model.EventWeight)).
+		Where("pasture_id = ?", pastureId).
+		Where("cow_id = ?", cowId).
+		Where("weight_at < ?", lastWeightAt).
+		First(cowWeightData).Error; err != nil {
 		if errors.Is(err, gorm.ErrRecordNotFound) {
 			return nil, xerr.Customf("该牛只体重数据不存在: %d", cowId)
 		}
@@ -148,11 +153,13 @@ func (s *StoreEntry) GetCowWeightByLastSecond(ctx context.Context, cowId, lastWe
 	return cowWeightData, nil
 }
 
-func (s *StoreEntry) GetDrugsById(ctx context.Context, id int64) (*model.Drugs, error) {
-	drugs := &model.Drugs{Id: id}
-	if err := s.DB.Model(new(model.Drugs)).First(drugs).Error; err != nil {
+func (s *StoreEntry) GetDrugsById(ctx context.Context, pastureId, drugsId int64) (*model.Drugs, error) {
+	drugs := &model.Drugs{Id: drugsId}
+	if err := s.DB.Model(new(model.Drugs)).
+		Where("pasture_id = ?", pastureId).
+		First(drugs).Error; err != nil {
 		if errors.Is(err, gorm.ErrRecordNotFound) {
-			return nil, xerr.Customf("该药品数据不存在: %d", id)
+			return nil, xerr.Customf("该药品数据不存在: %d", drugsId)
 		}
 		return nil, xerr.WithStack(err)
 	}
@@ -161,31 +168,42 @@ func (s *StoreEntry) GetDrugsById(ctx context.Context, id int64) (*model.Drugs,
 
 func (s *StoreEntry) DiseaseTypeList(ctx context.Context) ([]*model.ConfigDiseaseType, error) {
 	diseaseTypeList := make([]*model.ConfigDiseaseType, 0)
-	if err := s.DB.Model(new(model.ConfigDiseaseType)).Where("is_show = ?", pasturePb.IsShow_Ok).Find(&diseaseTypeList).Error; err != nil {
+	if err := s.DB.Model(new(model.ConfigDiseaseType)).
+		Where("is_show = ?", pasturePb.IsShow_Ok).
+		Find(&diseaseTypeList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
 	return diseaseTypeList, nil
 }
 
-func (s *StoreEntry) GetDiseaseById(ctx context.Context, id int32) (*model.Disease, error) {
+func (s *StoreEntry) GetDiseaseById(ctx context.Context, pastureId int64, diseaseId int32) (*model.Disease, error) {
 	newDisease := &model.Disease{}
-	if err := s.DB.Model(new(model.Disease)).Where("id = ?", id).First(newDisease).Error; err != nil {
+	if err := s.DB.Model(new(model.Disease)).
+		Where("pasture_id = ?", pastureId).
+		Where("is_show = ?", pasturePb.IsShow_Ok).
+		Where("id = ?", diseaseId).
+		First(newDisease).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
 	return newDisease, nil
 }
 
-func (s *StoreEntry) DiseaseListByIds(ctx context.Context, ids []int32) ([]*model.Disease, error) {
+func (s *StoreEntry) DiseaseListByIds(ctx context.Context, pastureId int64, ids []int32) ([]*model.Disease, error) {
 	diseaseList := make([]*model.Disease, 0)
-	if err := s.DB.Model(new(model.Disease)).Where("id IN ?", ids).Find(&diseaseList).Error; err != nil {
+	if err := s.DB.Model(new(model.Disease)).
+		Where("pasture_id = ?", pastureId).
+		Where("is_show = ?", pasturePb.IsShow_Ok).
+		Where("id IN ?", ids).Find(&diseaseList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
 	return diseaseList, nil
 }
 
-func (s *StoreEntry) GetPrescriptionById(ctx context.Context, id int32) (*model.Prescription, error) {
+func (s *StoreEntry) GetPrescriptionById(ctx context.Context, pastureId int64, id int32) (*model.Prescription, error) {
 	newPrescription := &model.Prescription{}
-	if err := s.DB.Model(new(model.Prescription)).Where("id = ?", id).
+	if err := s.DB.Model(new(model.Prescription)).
+		Where("id = ?", id).
+		Where("pasture_id = ?", pastureId).
 		Where("is_show = ?", pasturePb.IsShow_Ok).
 		First(&newPrescription).Error; err != nil {
 		return nil, xerr.WithStack(err)
@@ -193,9 +211,11 @@ func (s *StoreEntry) GetPrescriptionById(ctx context.Context, id int32) (*model.
 	return newPrescription, nil
 }
 
-func (s *StoreEntry) PrescriptionDrugsByPrescriptionId(ctx context.Context, prescriptionId int32) ([]*model.PrescriptionDrugs, error) {
+func (s *StoreEntry) PrescriptionDrugsByPrescriptionId(ctx context.Context, pastureId int64, prescriptionId int32) ([]*model.PrescriptionDrugs, error) {
 	newPrescriptionDrugsList := make([]*model.PrescriptionDrugs, 0)
-	if err := s.DB.Model(new(model.PrescriptionDrugs)).Where("prescription_id = ?", prescriptionId).
+	if err := s.DB.Model(new(model.PrescriptionDrugs)).
+		Where("pasture_id = ?", pastureId).
+		Where("prescription_id = ?", prescriptionId).
 		Where("is_show = ?", pasturePb.IsShow_Ok).
 		Find(&newPrescriptionDrugsList).Error; err != nil {
 		return nil, xerr.WithStack(err)
@@ -203,11 +223,14 @@ func (s *StoreEntry) PrescriptionDrugsByPrescriptionId(ctx context.Context, pres
 	return newPrescriptionDrugsList, nil
 }
 
-func (s *StoreEntry) GetImmunizationById(ctx context.Context, id int64) (*model.ImmunizationPlan, error) {
-	immunizationPlan := &model.ImmunizationPlan{Id: id}
-	if err := s.DB.Model(new(model.ImmunizationPlan)).First(immunizationPlan).Error; err != nil {
+func (s *StoreEntry) GetImmunizationById(ctx context.Context, pastureId, planId int64) (*model.ImmunizationPlan, error) {
+	immunizationPlan := &model.ImmunizationPlan{Id: planId}
+	if err := s.DB.Model(new(model.ImmunizationPlan)).
+		Where("pasture_id = ?", pastureId).
+		Where("is_show = ?", pasturePb.IsShow_Ok).
+		First(immunizationPlan).Error; err != nil {
 		if errors.Is(err, gorm.ErrRecordNotFound) {
-			return nil, xerr.Customf("该免疫计划不存在: %d", id)
+			return nil, xerr.Customf("该免疫计划不存在: %d", planId)
 		}
 		return nil, xerr.WithStack(err)
 	}
@@ -216,16 +239,19 @@ func (s *StoreEntry) GetImmunizationById(ctx context.Context, id int64) (*model.
 
 func (s *StoreEntry) GetWorkOrderSubByWorkOrderId(ctx context.Context, workOrderId int64) ([]*model.WorkOrderSub, error) {
 	workOrderSubList := make([]*model.WorkOrderSub, 0)
-	if err := s.DB.Model(new(model.WorkOrderSub)).Where("work_order_id = ?", workOrderId).Find(&workOrderSubList).Error; err != nil {
+	if err := s.DB.Model(new(model.WorkOrderSub)).
+		Where("work_order_id = ?", workOrderId).
+		Find(&workOrderSubList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
 	return workOrderSubList, nil
 }
 
-func (s *StoreEntry) GetEventCowSameTimeByCowId(ctx context.Context, cowId int64) (*model.EventCowSameTime, error) {
+func (s *StoreEntry) GetEventCowSameTimeByCowId(ctx context.Context, pastureId, cowId int64) (*model.EventCowSameTime, error) {
 	eventCowSameTime := &model.EventCowSameTime{}
 	if err := s.DB.Model(new(model.EventCowSameTime)).
 		Where("cow_id = ?", cowId).
+		Where("pasture_id = ?", pastureId).
 		Where("status = ?", pasturePb.IsShow_No).
 		First(eventCowSameTime).Error; err != nil {
 		return nil, xerr.WithStack(err)
@@ -262,21 +288,6 @@ func (s *StoreEntry) GetSystemBasicByName(ctx context.Context, name string) (*mo
 	return systemBasic, nil
 }
 
-// UpdateCowPenId 更新牛舍Id
-func (s *StoreEntry) UpdateCowPenId(ctx context.Context, cowId, penId int64) {
-	if penId == 0 || cowId == 0 {
-		return
-	}
-	cow, err := s.GetCowInfoByCowId(ctx, cowId)
-	if err != nil {
-		zaplog.Error("UpdateCowPenId", zap.Any("cowId", err))
-		return
-	}
-	if err = s.DB.Model(new(model.Cow)).Where("id = ?", cow.Id).Update("pen_id", penId).Error; err != nil {
-		zaplog.Error("UpdateCowPenId", zap.Any("cow_id", cowId), zap.Any("pen_id", penId), zap.Any("err", err))
-	}
-}
-
 func (s *StoreEntry) GetLastEventMating(ctx context.Context, cowId int64) (*model.EventMating, error) {
 	res := &model.EventMating{}
 	if err := s.DB.Model(new(model.EventMating)).
@@ -292,10 +303,11 @@ func (s *StoreEntry) GetLastEventMating(ctx context.Context, cowId int64) (*mode
 	return res, nil
 }
 
-func (s *StoreEntry) EventEstrusIsExist(ctx context.Context, cowId int64) (*model.EventEstrus, bool) {
+func (s *StoreEntry) EventEstrusIsExist(ctx context.Context, pastureId, cowId int64) (*model.EventEstrus, bool) {
 	newEventEstrus := &model.EventEstrus{}
 	if err := s.DB.Model(new(model.EventEstrus)).
 		Where("cow_id = ?", cowId).
+		Where("pasture_id = ?", pastureId).
 		Where("is_show = ? ", pasturePb.IsShow_Ok).
 		First(newEventEstrus).Error; err != nil {
 		if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -375,10 +387,11 @@ func (s *StoreEntry) DiseaseMaps(ctx context.Context) (map[int64]*model.Disease,
 	return res, nil
 }
 
-func (s *StoreEntry) NeckRingIsExist(ctx context.Context, number string) (*model.NeckRing, bool) {
+func (s *StoreEntry) NeckRingIsExist(ctx context.Context, pastureId int64, number string) (*model.NeckRing, bool) {
 	neckRing := &model.NeckRing{}
 	if err := s.DB.Model(new(model.NeckRing)).
 		Where("number = ?", number).
+		Where("pasture_id = ?", pastureId).
 		First(neckRing).Error; err != nil {
 		if errors.Is(err, gorm.ErrRecordNotFound) {
 			return nil, false

+ 52 - 41
module/crontab/cow_cron.go

@@ -59,7 +59,9 @@ func (e *Entry) GenerateAsynqWorkOrder() error {
 // UpdateCowInfo 牛只基本信息维护
 func (e *Entry) UpdateCowInfo() error {
 	cowList := make([]*model.Cow, 0)
-	if err := e.DB.Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).Find(&cowList).Error; err != nil {
+	if err := e.DB.Model(new(model.Cow)).
+		Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
+		Find(&cowList).Error; err != nil {
 		return err
 	}
 	if ok := e.IsExistCrontabLog(UpdateCowInfo); ok {
@@ -96,28 +98,20 @@ func (e *Entry) ImmunizationPlan() error {
 		return nil
 	}
 	planList := make([]*model.ImmunizationPlan, 0)
-	if err := e.DB.Where("is_show = ?", pasturePb.IsShow_Ok).Find(&planList).Error; err != nil {
+	if err := e.DB.Model(new(model.ImmunizationPlan)).
+		Where("is_show = ?", pasturePb.IsShow_Ok).
+		Order("pasture_id").
+		Find(&planList).Error; err != nil {
 		return xerr.WithStack(err)
 	}
 	var todayCount int32 = 0
-	defer func() {
-		var count int64 = 0
-		if err := e.DB.Model(new(model.EventImmunizationPlan)).
-			Where("status = ?", pasturePb.IsShow_Ok).
-			Count(&count).Error; err != nil {
-			zaplog.Error("Crontab", zap.Any("ImmunizationPlanDefer", err))
-		}
-		todayCount += int32(count)
-		if todayCount > 0 {
-			e.CreatedCalendar(pasturePb.CalendarType_Immunisation, todayCount)
-		}
-		e.CreateCrontabLog(ImmunizationPlan)
-	}()
+
 	nowTime := time.Now().Unix()
 	for _, plan := range planList {
 		cowList := make([]*model.Cow, 0)
 		pref := e.DB.Table(fmt.Sprintf("%s as a", new(model.Cow).TableName())).
 			Select("a.*").
+			Where("a.pasture_id = ?", plan.PastureId).
 			Where("a.admission_status = ?", pasturePb.AdmissionStatus_Admission).
 			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)
 		if plan.CowType > 0 {
@@ -152,6 +146,7 @@ func (e *Entry) ImmunizationPlan() error {
 		if len(cowList) <= 0 {
 			continue
 		}
+
 		todayCount += int32(len(cowList))
 		penList, _ := e.GetPenMapList()
 		newImmunizationPlanCowList := model.NewCowImmunizationPlanList(cowList, penList, plan)
@@ -169,6 +164,19 @@ func (e *Entry) ImmunizationPlan() error {
 		}); err != nil {
 			zaplog.Error("ImmunizationPlan", zap.Any("newImmunizationPlanCowList", err), zap.Any("plan", plan), zap.Any("cowList", cowList))
 		}
+
+		var count int64 = 0
+		if err := e.DB.Model(new(model.EventImmunizationPlan)).
+			Where("status = ?", pasturePb.IsShow_Ok).
+			Where("pasture_id = ?", plan.PastureId).
+			Count(&count).Error; err != nil {
+			zaplog.Error("Crontab", zap.Any("ImmunizationPlanDefer", err))
+		}
+		todayCount += int32(count)
+		if todayCount > 0 {
+			e.CreatedCalendar(plan.PastureId, pasturePb.CalendarType_Immunisation, time.Now().Format(model.LayoutDate2), todayCount)
+		}
+		e.CreateCrontabLog(ImmunizationPlan)
 	}
 
 	zaplog.Info("ImmunizationPlan", zap.Any("todayCount", todayCount))
@@ -182,16 +190,18 @@ func (e *Entry) SameTimePlan() error {
 	}
 
 	sameTimeList := make([]*model.SameTime, 0)
-	if err := e.DB.Where("is_show = ?", pasturePb.IsShow_Ok).Find(&sameTimeList).Error; err != nil {
+	if err := e.DB.Model(new(model.SameTime)).
+		Where("is_show = ?", pasturePb.IsShow_Ok).
+		Order("pasture_id").
+		Find(&sameTimeList).Error; err != nil {
 		return xerr.WithStack(err)
 	}
 
-	// 更新日历里面的数据
-	var todayCount int32 = 0
+	if len(sameTimeList) < 0 {
+		return nil
+	}
+
 	defer func() {
-		if todayCount > 0 {
-			e.CreatedCalendar(pasturePb.CalendarType_Immunisation, todayCount)
-		}
 		e.CreateCrontabLog(SameTimePlan)
 	}()
 
@@ -208,7 +218,8 @@ 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("sex = ?", pasturePb.Genders_Male).
+			Where("pasture_id = ?", sameTime.PastureId)
 
 		switch sameTime.CowType {
 		case pasturePb.SameTimeCowType_Breeding_Calf:
@@ -233,8 +244,7 @@ func (e *Entry) SameTimePlan() error {
 			continue
 		}
 
-		currCount, err := e.GenerateCalendarBySameTimePlan(cowList, sameTime)
-		if err != nil {
+		if err := e.GenerateCalendarBySameTimePlan(cowList, sameTime); err != nil {
 			zaplog.Error("crontab",
 				zap.Any("GenerateCalendarBySameTimePlan", err),
 				zap.Any("cowList", cowList),
@@ -242,7 +252,6 @@ func (e *Entry) SameTimePlan() error {
 			)
 			continue
 		}
-		todayCount += currCount
 	}
 	return nil
 }
@@ -306,34 +315,36 @@ func (e *Entry) SystemBasicCrontab() error {
 	}
 
 	currWeekValue := time.Now().Weekday()
-	for _, v := range systemBasicList {
+	for _, systemBasic := range systemBasicList {
 		// 周执行
-		if v.WeekValue >= 0 && time.Weekday(v.WeekValue) != currWeekValue {
+		if systemBasic.WeekValue >= 0 && time.Weekday(systemBasic.WeekValue) != currWeekValue {
 			continue
 		}
 
 		cowList := make([]*model.Cow, 0)
-		pref := e.DB.Model(new(model.Cow)).Where("admission_status = ? ", pasturePb.AdmissionStatus_Admission)
+		pref := e.DB.Model(new(model.Cow)).
+			Where("admission_status = ? ", pasturePb.AdmissionStatus_Admission).
+			Where("pasture_id = ?", systemBasic.PastureId)
 
-		switch v.Name {
+		switch systemBasic.Name {
 		case model.PregnantCheckForFirst:
 			pref.Where("breed_status = ?", pasturePb.BreedStatus_Breeding)
 		case model.PregnantCheckForSecond: // 过滤初检空怀的牛只
 			pref.Where("breed_status = ?", pasturePb.BreedStatus_Pregnant)
 		case model.WeaningAge:
-			pref.Where("day_age = ?", v.MinValue)
+			pref.Where("day_age = ?", systemBasic.MinValue)
 		case model.PregnancyAge:
-			pref.Where("pregnancy_age >= ?", v.MinValue).
+			pref.Where("pregnancy_age >= ?", systemBasic.MinValue).
 				Where("breed_status = ?", pasturePb.BreedStatus_Pregnant)
 		default:
 			continue
 		}
 
-		if v.ValueType == model.ValueTypeFixed {
-			pref.Where("day_age = ?", v.MinValue)
+		if systemBasic.ValueType == model.ValueTypeFixed {
+			pref.Where("day_age = ?", systemBasic.MinValue)
 		}
-		if v.ValueType == model.ValueTypeRange {
-			pref.Where("day_age >= ?", v.MinValue).Where("day_age <= ?", v.MaxValue)
+		if systemBasic.ValueType == model.ValueTypeRange {
+			pref.Where("day_age >= ?", systemBasic.MinValue).Where("day_age <= ?", systemBasic.MaxValue)
 		}
 
 		if err := pref.Find(&cowList).Error; err != nil {
@@ -344,27 +355,27 @@ func (e *Entry) SystemBasicCrontab() error {
 		if len(cowList) <= 0 {
 			continue
 		}
-		e.InitEventData(cowList, v.Name)
+		e.InitEventData(cowList, systemBasic)
 	}
 
 	return nil
 }
 
-func (e *Entry) InitEventData(cowList []*model.Cow, systemBasicName string) {
-	switch systemBasicName {
+func (e *Entry) InitEventData(cowList []*model.Cow, systemBasic *model.SystemBasic) {
+	switch systemBasic.Name {
 	case model.PregnantCheckForFirst, model.PregnantCheckForSecond:
 		penMap, _ := e.GetPenMapList()
-		eventPregnantCheckDataList := model.NewEventPregnantCheckList(cowList, penMap, systemBasicName)
+		eventPregnantCheckDataList := model.NewEventPregnantCheckList(systemBasic.PastureId, cowList, penMap, systemBasic.Name)
 		if err := e.DB.Create(eventPregnantCheckDataList).Error; err != nil {
 			zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventPregnantCheckDataList", eventPregnantCheckDataList))
 		}
 	case model.WeaningAge:
-		eventWeaningDataList := model.NewEventWeaningList(cowList)
+		eventWeaningDataList := model.NewEventWeaningList(systemBasic.PastureId, cowList)
 		if err := e.DB.Create(eventWeaningDataList).Error; err != nil {
 			zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventWeaningDataList", eventWeaningDataList))
 		}
 	case model.PregnancyAge:
-		eventCalvingList := model.NewEventCalvingList(cowList)
+		eventCalvingList := model.NewEventCalvingList(systemBasic.PastureId, cowList)
 		if err := e.DB.Create(eventCalvingList).Error; err != nil {
 			zaplog.Error("crontab", zap.Any("InitEventData", err), zap.Any("eventCalvingList", eventCalvingList))
 		}

+ 0 - 1
module/crontab/interface.go

@@ -33,6 +33,5 @@ type Crontab interface {
 	SameTimePlan() error
 	UpdateSameTime() error
 	SystemBasicCrontab() error
-	CowPregnant() error
 	NeckRingOriginalMergeData() error
 }

+ 19 - 10
module/crontab/other.go

@@ -26,17 +26,20 @@ func (e *Entry) IsExistCrontabLog(name string) bool {
 	return false
 }
 
+var isDelete bool
+
 func (e *Entry) CreateCrontabLog(name string) {
 	// 日志保留15天以内的
 	nowDay := time.Now()
 	defer func() {
-		if nowDay.Day()%15 == 0 {
+		if nowDay.Day()%15 == 0 && !isDelete {
 			beforeDay := nowDay.AddDate(0, 0, -15)
 			beforeDayFormat := beforeDay.Format(model.LayoutDate2)
 			e.DB.Model(&model.CronLog{}).
 				Where("date < ?", beforeDayFormat).
 				Where("name != ?", NeckRingOriginal).
 				Delete(&model.CronLog{})
+			isDelete = true
 		}
 	}()
 	crontabLog := model.NewCronLog(name)
@@ -50,27 +53,32 @@ func (e *Entry) DeleteCrontabLog(name string) {
 }
 
 // CreatedCalendar 创建当天工单日历记录
-func (e *Entry) CreatedCalendar(calendarType pasturePb.CalendarType_Kind, count int32) {
+func (e *Entry) CreatedCalendar(pastureId int64, calendarType pasturePb.CalendarType_Kind, showDay string, count int32) {
 	calendarTypeName := backend.CalendarTypeMap()[calendarType]
-	newCalendar := model.NewCalendar(calendarTypeName, calendarType, count)
-
+	newCalendar := model.NewCalendar(pastureId, calendarTypeName, calendarType, showDay, count)
 	historyCalendar := &model.Calendar{}
 	historyCount := int64(0)
-	if err := e.DB.Model(&model.Calendar{}).Where("calendar_type = ?", calendarType).
-		Where("show_day = ?", time.Now().Format(model.LayoutDate2)).Count(&historyCount).First(historyCalendar).Error; err != nil {
+	if err := e.DB.Model(&model.Calendar{}).
+		Where("calendar_type = ?", calendarType).
+		Where("show_day = ?", showDay).
+		Where("pasture_id = ?", pastureId).
+		Count(&historyCount).
+		First(historyCalendar).Error; err != nil {
 		zaplog.Error("CreatedCalendar", zap.Any("err", err), zap.Any("historyCalendar", historyCalendar))
 	}
 
 	if historyCount <= 0 {
-		if err := e.DB.Model(&model.Calendar{}).Create(newCalendar).Error; err != nil {
+		if err := e.DB.Model(&model.Calendar{}).
+			Create(newCalendar).Error; err != nil {
 			zaplog.Error("CreatedCalendar", zap.Any("err", err), zap.Any("workOrderCalendar", newCalendar))
 		}
 		return
 	}
 
 	if historyCount > 0 {
-		if err := e.DB.Model(&model.Calendar{}).Where("id = ?", historyCalendar.Id).
-			Update("count", count).Error; err != nil {
+		if err := e.DB.Model(&model.Calendar{}).
+			Where("id = ?", historyCalendar.Id).
+			Update("count", count+int32(historyCount)).Error; err != nil {
 			zaplog.Error("CreatedCalendar", zap.Any("err", err), zap.Any("historyCalendar", historyCalendar))
 		}
 	}
@@ -78,7 +86,8 @@ func (e *Entry) CreatedCalendar(calendarType pasturePb.CalendarType_Kind, count
 
 func (e *Entry) IsExistSameTimeCow(cow *model.Cow, sameTime *model.SameTime) bool {
 	var count int64 = 0
-	if err := e.DB.Model(&model.CowSameTime{}).
+	if err := e.DB.Model(&model.EventCowSameTime{}).
+		Where("pasture_id = ?", sameTime.PastureId).
 		Where("cow_id = ?", cow.Id).
 		Where("lact = ?", cow.Lact).
 		Where("same_time_id = ?", sameTime.Id).

+ 20 - 62
module/crontab/work_cron.go

@@ -3,7 +3,6 @@ package crontab
 import (
 	"encoding/json"
 	"kpt-pasture/model"
-	"kpt-pasture/module/backend"
 	"time"
 
 	"gorm.io/gorm"
@@ -17,9 +16,9 @@ import (
 )
 
 // GenerateCalendarBySameTimePlan 生成同期计划的牛只
-func (e *Entry) GenerateCalendarBySameTimePlan(cowList []*model.Cow, sameTime *model.SameTime) (int32, error) {
+func (e *Entry) GenerateCalendarBySameTimePlan(cowList []*model.Cow, sameTime *model.SameTime) (err error) {
 	if len(cowList) <= 0 {
-		return 0, nil
+		return nil
 	}
 
 	newCowList := make([]*model.Cow, 0)
@@ -31,10 +30,9 @@ func (e *Entry) GenerateCalendarBySameTimePlan(cowList []*model.Cow, sameTime *m
 	}
 
 	if len(newCowList) <= 0 || len(sameTime.CollateNodes) <= 0 {
-		return 0, nil
+		return nil
 	}
 
-	calendarList := make([]*model.Calendar, 0)
 	newSameTimeCowDetailList := make([]*model.EventCowSameTime, 0)
 	newEventMatingList := make([]*model.EventMating, 0)
 	collateNodes := make([]*pasturePb.CollateNode, 0)
@@ -47,81 +45,55 @@ func (e *Entry) GenerateCalendarBySameTimePlan(cowList []*model.Cow, sameTime *m
 			showDay = nowTime.Add(time.Hour * 24 * time.Duration(collateNode.NextNodeDay))
 		}
 
-		calendarName := backend.CalendarTypeMap()[pasturePb.CalendarType_PG]
 		calendarType := pasturePb.CalendarType_PG
 		histCount := int64(0)
 		if collateNode.SameTimeType == pasturePb.SameTimeType_TAI {
-			calendarName = backend.CalendarTypeMap()[pasturePb.CalendarType_Mating]
 			calendarType = pasturePb.CalendarType_Mating
-			histCount = e.GetTowardTaiCowSum()
-			newEventMatingList = append(newEventMatingList, model.NewEventMatingList(newCowList, showDay.Unix(), pasturePb.ExposeEstrusType_Same_Time)...)
+			histCount = e.GetTowardTaiCowSum(sameTime.PastureId)
+			newEventMatingList = append(newEventMatingList, model.NewEventMatingList(sameTime.PastureId, newCowList, showDay.Unix(), pasturePb.ExposeEstrusType_Same_Time)...)
 			newEventItemList = append(newEventItemList, model.NewEventItemList(newCowList, calendarType)...)
 		} else {
 			if collateNode.SameTimeType == pasturePb.SameTimeType_RnGH {
-				calendarName = backend.CalendarTypeMap()[pasturePb.CalendarType_RnGH]
 				calendarType = pasturePb.CalendarType_RnGH
 			}
-			histCount = e.GetTowardSameTimeCowSum(sameTime.Id, collateNode.SameTimeType)
-			newEventCowSameTimeList := model.NewEventCowSameTimeList(newCowList, sameTime, showDay.Unix(), collateNode.SameTimeType)
+			histCount = e.GetTowardSameTimeCowSum(sameTime, collateNode.SameTimeType)
+			newEventCowSameTimeList := model.NewEventCowSameTimeList(sameTime.PastureId, newCowList, sameTime, showDay.Unix(), collateNode.SameTimeType)
 			newSameTimeCowDetailList = append(newSameTimeCowDetailList, newEventCowSameTimeList...)
 			newEventItemList = append(newEventItemList, model.NewEventItemList(newCowList, calendarType)...)
 		}
 
-		calendarList = append(calendarList, &model.Calendar{
-			Name:         calendarName,
-			CalendarType: calendarType,
-			Count:        int32(len(newCowList)) + int32(histCount),
-			ShowDay:      time.Unix(showDay.Unix(), 0).Format(model.LayoutDate2),
-			IsShow:       pasturePb.IsShow_Ok,
-		})
+		allCount := int32(len(newCowList)) + int32(histCount)
+		e.CreatedCalendar(sameTime.PastureId, calendarType, showDay.Format(model.LayoutDate2), allCount)
 	}
 
-	newSameTimeCowList := model.NewCowSameTimeList(newCowList, sameTime)
-	if err := e.DB.Transaction(func(tx *gorm.DB) error {
-		// 创建牛只同期日历表
-		if err := tx.Create(calendarList).Error; err != nil {
-			return xerr.WithStack(err)
-		}
-		// 创建牛只同期总表
-		if err := tx.Create(newSameTimeCowList).Error; err != nil {
-			return xerr.WithStack(err)
-		}
+	if err = e.DB.Transaction(func(tx *gorm.DB) error {
 		// 创建牛只同期详情表
-		if err := tx.Create(newSameTimeCowDetailList).Error; err != nil {
+		if err = tx.Create(newSameTimeCowDetailList).Error; err != nil {
 			return xerr.WithStack(err)
 		}
 		// 创建牛只配种表
-		if err := tx.Create(newEventMatingList).Error; err != nil {
+		if err = tx.Create(newEventMatingList).Error; err != nil {
 			return xerr.WithStack(err)
 		}
 		// 创建牛只事件表
-		if err := tx.Create(newEventItemList).Error; err != nil {
+		if err = tx.Create(newEventItemList).Error; err != nil {
 			return xerr.WithStack(err)
 		}
 		return nil
 	}); err != nil {
-		return 0, xerr.WithStack(err)
+		return xerr.WithStack(err)
 	}
 
-	return int32(len(newCowList)), nil
-}
-
-func (e *Entry) getWorkOrderCalendar(name string) []*model.Calendar {
-	res := make([]*model.Calendar, 0)
-	if err := e.DB.Where("name = ?", name).
-		Where("is_show = ?", pasturePb.IsShow_Ok).
-		Find(&res).Error; err != nil {
-		zaplog.Error("getWorkOrderCalendar", zap.Any("err", err))
-	}
-	return res
+	return nil
 }
 
 // GetTowardSameTimeCowSum 获取历史未打激素牛只总数量
-func (e *Entry) GetTowardSameTimeCowSum(sameTimeId int64, sameTimeType pasturePb.SameTimeType_Kind) int64 {
+func (e *Entry) GetTowardSameTimeCowSum(sameTime *model.SameTime, sameTimeType pasturePb.SameTimeType_Kind) int64 {
 	res := int64(0)
 	if err := e.DB.Model(&model.EventCowSameTime{}).
 		Where("status = ?", pasturePb.IsShow_No).
-		Where("same_time_id = ?", sameTimeId).
+		Where("pasture_id = ?", sameTime.PastureId).
+		Where("same_time_id = ?", sameTime.Id).
 		Where("same_time_type = ?", sameTimeType).
 		Count(&res).Error; err != nil {
 		zaplog.Error("GetTowardSameTimeCowSum", zap.Any("err", err))
@@ -130,27 +102,13 @@ func (e *Entry) GetTowardSameTimeCowSum(sameTimeId int64, sameTimeType pasturePb
 }
 
 // GetTowardTaiCowSum 获取历史未配种牛只总数量
-func (e *Entry) GetTowardTaiCowSum() int64 {
+func (e *Entry) GetTowardTaiCowSum(pastureId int64) int64 {
 	res := int64(0)
 	if err := e.DB.Model(&model.EventMating{}).
+		Where("pasture_id = ?", pastureId).
 		Where("status = ?", pasturePb.IsShow_No).
 		Count(&res).Error; err != nil {
 		zaplog.Error("GetTowardTaiCowSum", zap.Any("err", err))
 	}
 	return res
 }
-
-// CowPregnant 月度牛只怀孕清单
-func (e *Entry) CowPregnant() error {
-	cowList := make([]*model.Cow, 0)
-	if err := e.DB.Model(new(model.Cow)).
-		Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
-		Where("is_pregnant = ?", pasturePb.IsShow_Ok).Find(&cowList).Error; err != nil {
-		return xerr.WithStack(err)
-	}
-	cowPregnantList := model.NewCowPregnantList(cowList)
-	if err := e.DB.Create(cowPregnantList).Error; err != nil {
-		return xerr.WithStack(err)
-	}
-	return nil
-}