Pārlūkot izejas kodu

pasture: 牧场切换

Yi 1 mēnesi atpakaļ
vecāks
revīzija
99edc4765a
44 mainītis faili ar 615 papildinājumiem un 470 dzēšanām
  1. 1 1
      go.mod
  2. 4 0
      go.sum
  3. 28 0
      http/handler/system/user.go
  4. 0 30
      http/handler/user.go
  5. 7 9
      http/middleware/auth.go
  6. 5 2
      http/route/system_api.go
  7. 13 0
      model/app_pasture_list.go
  8. 2 2
      model/cow.go
  9. 2 2
      model/drugs.go
  10. 2 2
      model/event_body_score.go
  11. 2 2
      model/event_cow_disease.go
  12. 4 3
      model/event_cow_treatment.go
  13. 2 2
      model/event_mating.go
  14. 3 1
      model/event_transfer_group.go
  15. 2 2
      model/event_weight.go
  16. 2 2
      model/frozen_semen.go
  17. 2 2
      model/immunization_plan.go
  18. 2 2
      model/medical_equipment.go
  19. 2 2
      model/neck_ring_bind_log.go
  20. 3 1
      model/outbound.go
  21. 2 2
      model/same_time.go
  22. 10 5
      model/system_user.go
  23. 2 1
      model/work_order_master.go
  24. 18 18
      module/backend/analysis.go
  25. 19 4
      module/backend/app_pasture.go
  26. 14 14
      module/backend/calendar.go
  27. 2 3
      module/backend/config_data_other.go
  28. 23 23
      module/backend/cow.go
  29. 6 6
      module/backend/enum_options.go
  30. 53 47
      module/backend/event_base.go
  31. 60 59
      module/backend/event_breed.go
  32. 21 14
      module/backend/event_breed_more.go
  33. 13 13
      module/backend/event_check.go
  34. 2 2
      module/backend/event_cow_log.go
  35. 51 43
      module/backend/event_health.go
  36. 58 45
      module/backend/goods.go
  37. 3 3
      module/backend/indicators.go
  38. 4 3
      module/backend/interface.go
  39. 3 3
      module/backend/pasture.go
  40. 58 47
      module/backend/prescription.go
  41. 59 14
      module/backend/sql.go
  42. 28 19
      module/backend/system_service.go
  43. 8 8
      module/backend/test_service.go
  44. 10 7
      module/backend/work.go

+ 1 - 1
go.mod

@@ -3,7 +3,7 @@ module kpt-pasture
 go 1.17
 
 require (
-	gitee.com/xuyiping_admin/go_proto v0.0.0-20250206022501-ea32be0345bd
+	gitee.com/xuyiping_admin/go_proto v0.0.0-20250206052721-b3db038e7785
 	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

+ 4 - 0
go.sum

@@ -142,6 +142,10 @@ gitee.com/xuyiping_admin/go_proto v0.0.0-20250206021619-2b0fc78035bb h1:I0QqA8hs
 gitee.com/xuyiping_admin/go_proto v0.0.0-20250206021619-2b0fc78035bb/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
 gitee.com/xuyiping_admin/go_proto v0.0.0-20250206022501-ea32be0345bd h1:wLHGWLUXJG4Uh0BXyD0VDeq6XnGWqVxxfZxUZHv294I=
 gitee.com/xuyiping_admin/go_proto v0.0.0-20250206022501-ea32be0345bd/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20250206034014-bf215fbc8803 h1:+VDhdJnUBbuC0Tk4WreKOsvsWOCDxdQEGlXA4TbXwOQ=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20250206034014-bf215fbc8803/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20250206052721-b3db038e7785 h1:DmfvtWuaFoSlAX9uQmOXu/JVh7Nqm/u2n/adB/rlBWw=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20250206052721-b3db038e7785/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=

+ 28 - 0
http/handler/system/user.go

@@ -210,3 +210,31 @@ func UserRoleSave(c *gin.Context) {
 		Data: &operationPb.Success{Success: true},
 	})
 }
+
+// GetUserMenu 获取系统用户菜单权限
+func GetUserMenu(c *gin.Context) {
+	res, err := middleware.BackendOperation(c).OpsService.GetSystemUserMenu(c)
+	if err != nil {
+		apierr.ClassifiedAbort(c, err)
+		return
+	}
+	ginutil.JSONResp(c, res)
+}
+
+// Logout 用户登出,
+func Logout(c *gin.Context) {
+	ginutil.JSONResp(c, &operationPb.CommonOK{
+		Code: http.StatusOK,
+		Msg:  "ok",
+		Data: &operationPb.Success{Success: true},
+	})
+}
+
+func PastureList(c *gin.Context) {
+	res, err := middleware.BackendOperation(c).OpsService.SearchUserPastureList(c)
+	if err != nil {
+		apierr.ClassifiedAbort(c, err)
+		return
+	}
+	ginutil.JSONResp(c, res)
+}

+ 0 - 30
http/handler/user.go

@@ -1,30 +0,0 @@
-package handler
-
-import (
-	"kpt-pasture/http/middleware"
-	"net/http"
-
-	operationPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/operation"
-	"gitee.com/xuyiping_admin/pkg/apierr"
-	"gitee.com/xuyiping_admin/pkg/ginutil"
-	"github.com/gin-gonic/gin"
-)
-
-// GetUserMenu 获取系统用户菜单权限
-func GetUserMenu(c *gin.Context) {
-	res, err := middleware.BackendOperation(c).OpsService.GetSystemUserMenu(c)
-	if err != nil {
-		apierr.ClassifiedAbort(c, err)
-		return
-	}
-	ginutil.JSONResp(c, res)
-}
-
-// Logout 用户登出,
-func Logout(c *gin.Context) {
-	ginutil.JSONResp(c, &operationPb.CommonOK{
-		Code: http.StatusOK,
-		Msg:  "ok",
-		Data: &operationPb.Success{Success: true},
-	})
-}

+ 7 - 9
http/middleware/auth.go

@@ -2,7 +2,6 @@ package middleware
 
 import (
 	"kpt-pasture/config"
-	"strconv"
 
 	commonPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/common"
 	"gitee.com/xuyiping_admin/pkg/apierr"
@@ -18,7 +17,7 @@ const (
 	Authorization = "Authorization"
 	ToKenPrefix   = "Bearer "
 	UserName      = "userName"
-	PastureId     = "PastureId"
+	FarmId        = "FarmId"
 	XRequestId    = "X-Request-Id"
 )
 
@@ -35,9 +34,8 @@ 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 GetFarmId(c *gin.Context) string {
+	return c.Request.Header.Get(FarmId)
 }
 
 func unauthorized(c *gin.Context) {
@@ -70,14 +68,14 @@ func RequireAdmin() gin.HandlerFunc {
 			unauthorized(c)
 			return
 		}
-		/*pastureId, err := GetPastureId(c)
-		if err != nil {
+		farmId := GetFarmId(c)
+		if farmId == "" {
 			unauthorized(c)
 			return
-		}*/
+		}
 
 		c.Set(UserName, userName)
-		//c.Set(PastureId, pastureId)
+		c.Set(FarmId, FarmId)
 		c.Set(XRequestId, GetXRequestId(c))
 		c.Next()
 	}

+ 5 - 2
http/route/system_api.go

@@ -51,8 +51,11 @@ func SystemAPI(opts ...func(engine *gin.Engine)) func(s *gin.Engine) {
 		systemRoute.POST("/dept/createOrUpdate", system.DepCreateOrUpdate)
 
 		// 登录用户的相关接口
-		systemRoute.GET("/user/menu", handler.GetUserMenu)
-		systemRoute.POST("/user/logout", handler.Logout)
+		systemRoute.GET("/user/menu", system.GetUserMenu)
+		systemRoute.POST("/user/logout", system.Logout)
+
+		// 牧场
+		systemRoute.POST("/pasture/list", system.PastureList)
 	}
 }
 

+ 13 - 0
model/app_pasture_list.go

@@ -32,3 +32,16 @@ type AppPastureList struct {
 func (a *AppPastureList) TableName() string {
 	return "app_pasture_list"
 }
+
+type AppPastureListSlice []*AppPastureList
+
+func (a AppPastureListSlice) ToPB() []*pasturePb.UserPasture {
+	res := make([]*pasturePb.UserPasture, len(a))
+	for i, d := range a {
+		res[i] = &pasturePb.UserPasture{
+			FarmId: d.FarmId,
+			Name:   d.Name,
+		}
+	}
+	return res
+}

+ 2 - 2
model/cow.go

@@ -319,13 +319,13 @@ func (c CowSlice) ToPB2(penMap map[int32]*Pen, penWeightSlice PenWeightSlice) []
 	return res
 }
 
-func NewCow(current *SystemUser, req *pasturePb.EventEnterRequest) *Cow {
+func NewCow(pastureId int64, current *SystemUser, req *pasturePb.EventEnterRequest) *Cow {
 	var isPregnant = pasturePb.IsShow_No
 	if req.BreedStatus == pasturePb.BreedStatus_Pregnant {
 		isPregnant = pasturePb.IsShow_Ok
 	}
 	return &Cow{
-		PastureId:           current.PastureId,
+		PastureId:           pastureId,
 		Sex:                 req.Sex,
 		EarNumber:           req.EarNumber,
 		PenId:               req.PenId,

+ 2 - 2
model/drugs.go

@@ -32,9 +32,9 @@ func (d *Drugs) TableName() string {
 	return "drugs"
 }
 
-func NewDrugs(req *pasturePb.SearchDrugsList, currentUser *SystemUser) *Drugs {
+func NewDrugs(pastureId int64, req *pasturePb.SearchDrugsList, currentUser *SystemUser) *Drugs {
 	return &Drugs{
-		PastureId:       currentUser.PastureId,
+		PastureId:       pastureId,
 		Name:            req.Name,
 		CategoryId:      req.CategoryId,
 		CategoryName:    req.CategoryName,

+ 2 - 2
model/event_body_score.go

@@ -24,9 +24,9 @@ func (e *EventBodyScore) TableName() string {
 	return "event_body_score"
 }
 
-func NewEventBodyScore(cow *Cow, currentUser *SystemUser, req *pasturePb.BodyScoreEventRequest) *EventBodyScore {
+func NewEventBodyScore(cow *Cow, pastureId int64, currentUser *SystemUser, req *pasturePb.BodyScoreEventRequest) *EventBodyScore {
 	return &EventBodyScore{
-		PastureId:     currentUser.PastureId,
+		PastureId:     pastureId,
 		CowId:         cow.Id,
 		EarNumber:     cow.EarNumber,
 		Score:         req.Score,

+ 2 - 2
model/event_cow_disease.go

@@ -74,9 +74,9 @@ func (e *EventCowDisease) EventCurableUpdate(cureAt int64) {
 	e.DiagnosedResult = pasturePb.IsShow_Ok
 }
 
-func NewEventCowDisease(cow *Cow, disease *Disease, req *pasturePb.EventCowDiseaseRequest, operation, currUser *SystemUser) *EventCowDisease {
+func NewEventCowDisease(pastureId int64, cow *Cow, disease *Disease, req *pasturePb.EventCowDiseaseRequest, operation, currUser *SystemUser) *EventCowDisease {
 	return &EventCowDisease{
-		PastureId:       currUser.PastureId,
+		PastureId:       pastureId,
 		CowId:           cow.Id,
 		CowType:         cow.CowType,
 		Lact:            cow.Lact,

+ 4 - 3
model/event_cow_treatment.go

@@ -37,6 +37,7 @@ func (e *EventCowTreatment) TableName() string {
 }
 
 func NewEventCowTreatment(
+	pastureId int64,
 	prescription *Prescription,
 	req *pasturePb.CowTreatmentRequest,
 	diseaseTypeMap map[int32]string,
@@ -44,7 +45,7 @@ func NewEventCowTreatment(
 ) *EventCowTreatment {
 	b, _ := json.Marshal(req.PrescriptionDetail)
 	return &EventCowTreatment{
-		PastureId:          currentUser.PastureId,
+		PastureId:          pastureId,
 		CowId:              int64(req.CowId),
 		CowDiseaseId:       int64(req.Id),
 		DiseaseId:          int64(req.DiseaseId),
@@ -63,9 +64,9 @@ func NewEventCowTreatment(
 	}
 }
 
-func NewEventCowCurableTreatment(currUser, operationUser *SystemUser, cowDisease *EventCowDisease, remarks string, curableAt int64) *EventCowTreatment {
+func NewEventCowCurableTreatment(pastureId int64, currUser, operationUser *SystemUser, cowDisease *EventCowDisease, remarks string, curableAt int64) *EventCowTreatment {
 	return &EventCowTreatment{
-		PastureId:       currUser.PastureId,
+		PastureId:       pastureId,
 		CowId:           cowDisease.CowId,
 		CowDiseaseId:    cowDisease.Id,
 		DiseaseId:       int64(cowDisease.DiseaseId),

+ 2 - 2
model/event_mating.go

@@ -118,9 +118,9 @@ func NewEventMating(pastureId int64, cow *Cow, planDay int64, exposeEstrusType p
 }
 
 // NewEventMatingNaturalEstrus 自然发情的牛只
-func NewEventMatingNaturalEstrus(cow *Cow, req *pasturePb.EventMating, currentUser *SystemUser) *EventMating {
+func NewEventMatingNaturalEstrus(pastureId int64, cow *Cow, req *pasturePb.EventMating, currentUser *SystemUser) *EventMating {
 	return &EventMating{
-		PastureId:         currentUser.PastureId,
+		PastureId:         pastureId,
 		CowId:             cow.Id,
 		Lact:              cow.Lact,
 		DayAge:            cow.GetDayAge(),

+ 3 - 1
model/event_transfer_group.go

@@ -4,6 +4,7 @@ import pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 
 type EventTransferGroup struct {
 	Id                 int64  `json:"id"`
+	PastureId          int64  `json:"pastureId"`
 	CowId              int64  `json:"cowId"`
 	PenInId            int32  `json:"penInId"`
 	PenOutId           int32  `json:"penOutId"`
@@ -30,8 +31,9 @@ type EventTransferGroupModel struct {
 	EventTransferGroup *EventTransferGroup
 }
 
-func NewEventTransferGroup(cow *Cow, req *pasturePb.TransferGroupEventData, transferPenMap map[int32]string, currentUser *SystemUser, operationUser *SystemUser) *EventTransferGroup {
+func NewEventTransferGroup(pastureId int64, cow *Cow, req *pasturePb.TransferGroupEventData, transferPenMap map[int32]string, currentUser *SystemUser, operationUser *SystemUser) *EventTransferGroup {
 	return &EventTransferGroup{
+		PastureId:          pastureId,
 		CowId:              int64(req.CowId),
 		PenInId:            req.TransferInPenId,
 		PenOutId:           cow.PenId,

+ 2 - 2
model/event_weight.go

@@ -31,9 +31,9 @@ func (c *EventWeight) TableName() string {
 	return "event_weight"
 }
 
-func NewEventWeight(cow *Cow, currentUser *SystemUser, weight, height int32, req *pasturePb.EventWeight) *EventWeight {
+func NewEventWeight(pastureId int64, cow *Cow, currentUser *SystemUser, weight, height int32, req *pasturePb.EventWeight) *EventWeight {
 	return &EventWeight{
-		PastureId:     currentUser.PastureId,
+		PastureId:     pastureId,
 		CowId:         cow.Id,
 		EarNumber:     cow.EarNumber,
 		Weight:        weight,

+ 2 - 2
model/frozen_semen.go

@@ -19,9 +19,9 @@ type FrozenSemen struct {
 	UpdatedAt       int64                          `json:"updated_at"`
 }
 
-func NewFrozenSemen(req *pasturePb.SearchFrozenSemenList, currentUser *SystemUser) *FrozenSemen {
+func NewFrozenSemen(pastureId int64, req *pasturePb.SearchFrozenSemenList, currentUser *SystemUser) *FrozenSemen {
 	return &FrozenSemen{
-		PastureId:       currentUser.PastureId,
+		PastureId:       pastureId,
 		Producer:        req.Producer,
 		BullId:          req.BullId,
 		KindId:          req.CowKind,

+ 2 - 2
model/immunization_plan.go

@@ -24,9 +24,9 @@ func (i *ImmunizationPlan) TableName() string {
 	return "immunization_plan"
 }
 
-func NewImmunizationPlan(systemUser *SystemUser, req *pasturePb.ImmunizationRequest) *ImmunizationPlan {
+func NewImmunizationPlan(pastureId int64, systemUser *SystemUser, req *pasturePb.ImmunizationRequest) *ImmunizationPlan {
 	return &ImmunizationPlan{
-		PastureId:            systemUser.PastureId,
+		PastureId:            pastureId,
 		Name:                 req.Name,
 		CowType:              req.CowType,
 		Conditions:           req.Conditions,

+ 2 - 2
model/medical_equipment.go

@@ -23,9 +23,9 @@ func (m *MedicalEquipment) TableName() string {
 	return "medical_equipment"
 }
 
-func NewMedicalEquipment(req *pasturePb.SearchMedicalEquipmentList, currentUser *SystemUser) *MedicalEquipment {
+func NewMedicalEquipment(pastureId int64, req *pasturePb.SearchMedicalEquipmentList, currentUser *SystemUser) *MedicalEquipment {
 	return &MedicalEquipment{
-		PastureId:     currentUser.PastureId,
+		PastureId:     pastureId,
 		Name:          req.Name,
 		Producer:      req.Producer,
 		BatchNumber:   req.BatchNumber,

+ 2 - 2
model/neck_ring_bind_log.go

@@ -19,9 +19,9 @@ func (n *NeckRingBindLog) TableName() string {
 	return "neck_ring_bind_log"
 }
 
-func NewNeckRingBindLog(neckRingNumber string, cowId int64, operationUser *SystemUser) *NeckRingBindLog {
+func NewNeckRingBindLog(pastureId int64, neckRingNumber string, cowId int64, operationUser *SystemUser) *NeckRingBindLog {
 	return &NeckRingBindLog{
-		PastureId:      operationUser.PastureId,
+		PastureId:      pastureId,
 		NeckRingNumber: neckRingNumber,
 		BindAt:         time.Now().Unix(),
 		CowId:          cowId,

+ 3 - 1
model/outbound.go

@@ -10,6 +10,7 @@ import (
 
 type Outbound struct {
 	Id               int64                      `json:"id"`
+	PastureId        int64                      `json:"pastureId"`
 	Number           string                     `json:"number"`
 	OutType          pasturePb.OutType_Kind     `json:"outType"`
 	AuditStatus      pasturePb.AuditStatus_Kind `json:"auditStatus"`
@@ -33,8 +34,9 @@ func (o *Outbound) Delete() {
 	o.AuditStatus = pasturePb.AuditStatus_Delete
 }
 
-func NewOutbound(req *pasturePb.OutboundApplyItem, currentUser *SystemUser) *Outbound {
+func NewOutbound(pastureId int64, req *pasturePb.OutboundApplyItem, currentUser *SystemUser) *Outbound {
 	return &Outbound{
+		PastureId:        pastureId,
 		Number:           fmt.Sprintf("%s%s", util.GenerateRandomNumberString(8), time.Now().Format(LayoutDate)),
 		OutType:          req.OutType,
 		AuditStatus:      pasturePb.AuditStatus_Pending,

+ 2 - 2
model/same_time.go

@@ -30,12 +30,13 @@ func (e *SameTime) TableName() string {
 	return "same_time"
 }
 
-func NewSameTime(currentUser *SystemUser, req *pasturePb.SearchSameTimeList) *SameTime {
+func NewSameTime(pastureId int64, currentUser *SystemUser, req *pasturePb.SearchSameTimeList) *SameTime {
 	var collateNodes []byte
 	if len(req.CollateNodes) > 0 {
 		collateNodes, _ = json.Marshal(req.CollateNodes)
 	}
 	return &SameTime{
+		PastureId:           pastureId,
 		Name:                req.Name,
 		WeekType:            req.WeekType,
 		CowType:             req.CowType,
@@ -46,7 +47,6 @@ func NewSameTime(currentUser *SystemUser, req *pasturePb.SearchSameTimeList) *Sa
 		CollateNodes:        string(collateNodes),
 		Remarks:             req.Remarks,
 		OperationId:         currentUser.Id,
-		PastureId:           currentUser.PastureId,
 	}
 }
 

+ 10 - 5
model/system_user.go

@@ -10,7 +10,6 @@ import (
 
 type SystemUser struct {
 	Id              int64                  `json:"id"`
-	PastureId       int64                  `json:"pastureId"`
 	Name            string                 `json:"name"`
 	NickName        string                 `json:"nickName"`
 	Mobile          string                 `json:"mobile"`
@@ -19,10 +18,11 @@ type SystemUser struct {
 	RoleId          int64                  `json:"roleId"`
 	DeptId          int64                  `json:"deptId"`
 	IndicatorsKinds string                 `json:"indicatorsKinds"`
-	Remarks         string                 `json:"remarks"`
 	Gender          pasturePb.Genders_Kind `json:"gender"`
+	PastureIds      string                 `json:"pastureIds"`
 	IsShow          pasturePb.IsShow_Kind  `json:"isShow"`
 	IsDelete        pasturePb.IsShow_Kind  `json:"isDelete"`
+	Remarks         string                 `json:"remarks"`
 	CreatedAt       int64                  `json:"created_at"`
 	UpdatedAt       int64                  `json:"updated_at"`
 }
@@ -51,6 +51,11 @@ func (s *SystemUser) SystemUserFormat(userRoles []*SystemRole, pastures []*opera
 	}
 }
 
+type UserModel struct {
+	SystemUser *SystemUser
+	AppPasture *AppPastureList
+}
+
 type SystemUserSlice []*SystemUser
 
 func (s SystemUserSlice) ToPB(deptList []*SystemDept, roleList []*SystemRole) []*pasturePb.SearchUserRequest {
@@ -102,9 +107,9 @@ func (s *SystemUser) ToPb() *operationPb.AddSystemUser {
 	}
 }
 
-func (c SystemUserSlice) ToPB2() []*pasturePb.ConfigOptionsList {
-	res := make([]*pasturePb.ConfigOptionsList, len(c))
-	for i, d := range c {
+func (s SystemUserSlice) ToPB2() []*pasturePb.ConfigOptionsList {
+	res := make([]*pasturePb.ConfigOptionsList, len(s))
+	for i, d := range s {
 		res[i] = &pasturePb.ConfigOptionsList{
 			Value:    int32(d.Id),
 			Label:    d.Name,

+ 2 - 1
model/work_order_master.go

@@ -50,6 +50,7 @@ func (w *WorkOrderMaster) TableName() string {
 	return "work_order_master"
 }
 func NewWorkOrderMaster(
+	pastureId int64,
 	req *pasturePb.WorkOrderList,
 	curUser *SystemUser,
 	systemUserList []*SystemUser,
@@ -79,7 +80,7 @@ func NewWorkOrderMaster(
 	}
 
 	return &WorkOrderMaster{
-		PastureId:       curUser.PastureId,
+		PastureId:       pastureId,
 		Name:            req.Name,
 		CategoryId:      req.CategoryId,
 		CategoryName:    workOrderCategoryMap[req.CategoryId],

+ 18 - 18
module/backend/analysis.go

@@ -17,7 +17,7 @@ import (
 
 // GrowthCurve 生长曲线 获取图表数据
 func (s *StoreEntry) GrowthCurve(ctx context.Context, req *pasturePb.SearchGrowthCurvesRequest) (*pasturePb.GrowthCurvesResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
 		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
 	}
@@ -25,7 +25,7 @@ func (s *StoreEntry) GrowthCurve(ctx context.Context, req *pasturePb.SearchGrowt
 	cowList := make([]*model.Cow, 0)
 	pref := s.DB.Model(new(model.Cow)).
 		Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
-		Where("pasture_id = ?", currentUser.PastureId)
+		Where("pasture_id = ?", userModel.AppPasture.Id)
 	if req.GetCowId() != "" {
 		pref.Where("id IN ?", strings.Split(req.CowId, ","))
 	}
@@ -40,7 +40,7 @@ func (s *StoreEntry) GrowthCurve(ctx context.Context, req *pasturePb.SearchGrowt
 	if err = pref.Find(&cowList).Error; err != nil {
 		return nil, err
 	}
-	penList, err := s.GetPenList(ctx, currentUser.PastureId)
+	penList, err := s.GetPenList(ctx, userModel.AppPasture.Id)
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -91,15 +91,15 @@ func (s *StoreEntry) GrowthCurve(ctx context.Context, req *pasturePb.SearchGrowt
 }
 
 func (s *StoreEntry) WeightRange(ctx context.Context, req *pasturePb.WeightRangeRequest) (*pasturePb.WeightRangeResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	cowWeightRange := make([]*model.CowWeightRange, 0)
 	prefix := s.DB.Model(new(model.Cow)).
 		Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
-		Where("pasture_id = ?", currentUser.PastureId)
+		Where("pasture_id = ?", userModel.AppPasture.Id)
 	if req.CowKind > 0 {
 		prefix.Where("cow_kind = ?", req.CowKind)
 	}
@@ -149,7 +149,7 @@ func (s *StoreEntry) WeightRange(ctx context.Context, req *pasturePb.WeightRange
 	// 牛只详情列表
 	pref := s.DB.Model(new(model.Cow)).
 		Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).
-		Where("pasture_id = ?", currentUser.PastureId)
+		Where("pasture_id = ?", userModel.AppPasture.Id)
 	if req.CowKind > 0 {
 		pref.Where("cow_kind = ?", req.CowKind)
 	}
@@ -162,7 +162,7 @@ func (s *StoreEntry) WeightRange(ctx context.Context, req *pasturePb.WeightRange
 		return nil, err
 	}
 
-	penMap := s.PenMap(ctx, currentUser.PastureId)
+	penMap := s.PenMap(ctx, userModel.AppPasture.Id)
 	return &pasturePb.WeightRangeResponse{
 		Code: http.StatusOK,
 		Msg:  "ok",
@@ -177,13 +177,13 @@ 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)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	matingTimelyChart := make([]*model.MatingTimelyChart, 0)
-	pastureWhereSql := fmt.Sprintf(" AND pasture_id = %d", currentUser.PastureId)
+	pastureWhereSql := fmt.Sprintf(" AND pasture_id = %d", userModel.AppPasture.Id)
 	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
@@ -272,9 +272,9 @@ 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)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	penWeightList := make([]*model.PenWeight, 0)
@@ -285,7 +285,7 @@ func (s *StoreEntry) PenWeight(ctx context.Context, req *pasturePb.PenWeightRequ
 			CEILING(SUM(current_weight) / 1000 ) AS all_weight,
 			COUNT(*) AS cow_count`,
 		).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Where("admission_status = ?", pasturePb.AdmissionStatus_Admission)
 	if len(req.PenId) > 0 && req.BarId <= 0 {
 		pref.Where("pen_id IN ?", req.PenId)
@@ -329,7 +329,7 @@ func (s *StoreEntry) PenWeight(ctx context.Context, req *pasturePb.PenWeightRequ
 		return nil, xerr.WithStack(err)
 	}
 
-	penMap := s.PenMap(ctx, currentUser.PastureId)
+	penMap := s.PenMap(ctx, userModel.AppPasture.Id)
 	return &pasturePb.PenWeightResponse{
 		Code: http.StatusOK,
 		Msg:  "ok",
@@ -344,9 +344,9 @@ 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)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	dayTimeList, err := util.GetMonthsInRange(req.StartDayTime, req.EndDayTime)
@@ -366,7 +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("pasture_id = ?", userModel.AppPasture.Id).
 		Where("DATE_FORMAT(FROM_UNIXTIME(`created_at`),'%Y-%m-%d') IN ?", lastDayForMonth)
 
 	if req.Lact >= 0 && req.Lact <= 3 {

+ 19 - 4
module/backend/app_pasture.go

@@ -3,17 +3,32 @@ package backend
 import (
 	"context"
 	"kpt-pasture/model"
+	"strings"
+
+	"gitee.com/xuyiping_admin/pkg/xerr"
 
 	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 )
 
-func (s *StoreEntry) FindPastureByFarmId(ctx context.Context, pastureId int64) *model.AppPastureList {
+func (s *StoreEntry) FindPastureByFarmId(ctx context.Context, farmId string) (*model.AppPastureList, error) {
 	res := &model.AppPastureList{}
 	if err := s.DB.Table(new(model.AppPastureList).TableName()).
-		Where("id = ?", pastureId).
+		Where("farm_id = ?", farmId).
 		Where("is_show = ?", pasturePb.IsShow_Ok).
 		First(res).Error; err != nil {
-		return nil
+		return nil, xerr.WithStack(err)
+	}
+	return res, nil
+}
+
+func (s *StoreEntry) FindPastureList(ctx context.Context, pastureIds string) ([]*model.AppPastureList, error) {
+	list := make([]*model.AppPastureList, 0)
+	pastureIntIds := strings.Split(pastureIds, ",")
+	if err := s.DB.Table(new(model.AppPastureList).TableName()).
+		Where("id IN (?)", pastureIntIds).
+		Where("is_show = ?", pasturePb.IsShow_Ok).
+		Find(&list).Error; err != nil {
+		return nil, xerr.WithStack(err)
 	}
-	return res
+	return list, nil
 }

+ 14 - 14
module/backend/calendar.go

@@ -14,9 +14,9 @@ import (
 
 // CalendarToDoList 获取日历待办列表
 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.Custom("当前登录用户失败,请退出重新登录")
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return nil, xerr.WithStack(err)
 	}
 
 	var count int64 = 0
@@ -28,7 +28,7 @@ func (s *StoreEntry) CalendarToDoList(ctx context.Context, req *pasturePb.Calend
 	}
 
 	if len(req.CowIds) > 0 {
-		cowList, _ := s.ParseCowIds(ctx, currentUser.PastureId, req.CowIds)
+		cowList, _ := s.ParseCowIds(ctx, userModel.AppPasture.Id, req.CowIds)
 		cowIds := make([]int64, 0)
 		for _, cow := range cowList {
 			cowIds = append(cowIds, cow.Id)
@@ -59,7 +59,7 @@ func (s *StoreEntry) CalendarToDoList(ctx context.Context, req *pasturePb.Calend
 		return nil, xerr.WithStack(err)
 	}
 
-	penMap := s.PenMap(ctx, currentUser.PastureId)
+	penMap := s.PenMap(ctx, userModel.AppPasture.Id)
 	calendarMap := CalendarTypeMap()
 
 	return &pasturePb.CalendarToDoResponse{
@@ -74,16 +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("登录信息异常,请退出重新登录")
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return nil, xerr.WithStack(err)
 	}
 
 	calendarList := make([]*model.Calendar, 0)
 	if err = s.DB.Model(&model.Calendar{}).
 		Where("show_day >= ?", req.ShowStartDay).
 		Where("show_day <= ?", req.ShowEndDay).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Where("is_show = ?", pasturePb.IsShow_Ok).
 		Find(&calendarList).Error; err != nil {
 		return nil, xerr.WithStack(err)
@@ -104,9 +104,9 @@ func (s *StoreEntry) CalendarTableDetail(
 		return nil, xerr.Custom("只能获取当天的数据")
 	}
 
-	currentUser, err := s.GetCurrentSystemUser(ctx)
-	if err != nil || currentUser.Id <= 0 {
-		return nil, xerr.Customf("登录信息异常,请退出重新登录")
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return nil, xerr.WithStack(err)
 	}
 
 	newCalendar := &model.Calendar{}
@@ -114,7 +114,7 @@ func (s *StoreEntry) CalendarTableDetail(
 		Where("calendar_type = ?", req.CalendarType).
 		Where("show_day = ?", req.Start).
 		Where("is_show = ?", pasturePb.IsShow_Ok).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		First(newCalendar).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -122,7 +122,7 @@ func (s *StoreEntry) CalendarTableDetail(
 	if newCalendar.Id <= 0 {
 		return nil, xerr.New("不存在该日历数据")
 	}
-	return s.getCalendarCowList(ctx, req.CalendarType, req.Start, pagination, currentUser.PastureId)
+	return s.getCalendarCowList(ctx, req.CalendarType, req.Start, pagination, userModel.AppPasture.Id)
 }
 
 func (s *StoreEntry) getCalendarCowList(

+ 2 - 3
module/backend/config_data_other.go

@@ -240,12 +240,11 @@ func (s *StoreEntry) FrozenSemenTypeEnumList(isAll string) []*pasturePb.ConfigOp
 	return configOptions
 }
 
-func (s *StoreEntry) BullNumberEnumList(isAll string, currentUser *model.SystemUser) []*pasturePb.BullOptionsList {
-
+func (s *StoreEntry) BullNumberEnumList(isAll string, pastureId int64) []*pasturePb.BullOptionsList {
 	frozenSemenList := make([]*model.FrozenSemen, 0)
 	bullNumberList := make([]*pasturePb.BullOptionsList, 0)
 	if err := s.DB.Model(new(model.FrozenSemen)).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", pastureId).
 		Where("quantity > 0").
 		Group("bull_id").
 		Find(&frozenSemenList).Error; err != nil {

+ 23 - 23
module/backend/cow.go

@@ -18,13 +18,13 @@ import (
 )
 
 func (s *StoreEntry) Detail(ctx context.Context, req *pasturePb.SearchEventRequest) (*pasturePb.CowInfoResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	cowInfo := make([]*model.Cow, 0)
-	pref := s.DB.Model(new(model.Cow)).Where("pasture_id = ?", currentUser.PastureId).Where("id = ?", req.CowId)
+	pref := s.DB.Model(new(model.Cow)).Where("pasture_id = ?", userModel.AppPasture.Id).Where("id = ?", req.CowId)
 	if req.NeckRingNumber != "" {
 		pref.Where("neck_ring_number = ?", req.NeckRingNumber)
 	}
@@ -38,7 +38,7 @@ func (s *StoreEntry) Detail(ctx context.Context, req *pasturePb.SearchEventReque
 		return nil, xerr.WithStack(err)
 	}
 
-	penMap := s.PenMap(ctx, currentUser.PastureId)
+	penMap := s.PenMap(ctx, userModel.AppPasture.Id)
 	cowTypeMap := s.CowTypeMap()
 	breedStatusMap := s.CowBreedStatusMap()
 	cowKindMap := s.CowKindMap()
@@ -54,15 +54,15 @@ func (s *StoreEntry) Detail(ctx context.Context, req *pasturePb.SearchEventReque
 }
 
 func (s *StoreEntry) List(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchCowListResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	cowList := make([]*model.Cow, 0)
 	var count int64 = 0
 	pref := s.DB.Model(new(model.Cow)).
-		Where("pasture_id = ?", currentUser.PastureId)
+		Where("pasture_id = ?", userModel.AppPasture.Id)
 
 	if len(req.CowId) > 0 {
 		cowIds := strings.Split(req.CowId, ",")
@@ -113,7 +113,7 @@ func (s *StoreEntry) List(ctx context.Context, req *pasturePb.SearchEventRequest
 		return nil, xerr.WithStack(err)
 	}
 
-	penMap := s.PenMap(ctx, currentUser.PastureId)
+	penMap := s.PenMap(ctx, userModel.AppPasture.Id)
 	cowTypeMap := s.CowTypeMap()
 	breedStatusMap := s.CowBreedStatusMap()
 	cowKindMap := s.CowKindMap()
@@ -136,16 +136,16 @@ func (s *StoreEntry) List(ctx context.Context, req *pasturePb.SearchEventRequest
 }
 
 func (s *StoreEntry) EventList(ctx context.Context, req *pasturePb.SearchCowEventListRequest, pagination *pasturePb.PaginationModel) (*pasturePb.CowEventListResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	cow := &model.Cow{}
 	if err = s.DB.Model(cow).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Where("id = ?", req.CowId).First(cow).Error; err != nil {
-		zaplog.Error("EventList", zap.Any("req", req), zap.Any("err", err), zap.Any("currentUser", currentUser))
+		zaplog.Error("EventList", zap.Any("req", req), zap.Any("err", err), zap.Any("userModel", userModel))
 		return nil, xerr.Customf("该牛不存在: %d", req.CowId)
 	}
 
@@ -166,7 +166,7 @@ func (s *StoreEntry) EventList(ctx context.Context, req *pasturePb.SearchCowEven
 		Limit(int(pagination.PageSize)).
 		Offset(int(pagination.PageOffset)).
 		Find(&eventCowLogList).Error; err != nil {
-		zaplog.Error("EventList", zap.Any("req", req), zap.Any("err", err), zap.Any("currentUser", currentUser))
+		zaplog.Error("EventList", zap.Any("req", req), zap.Any("err", err), zap.Any("userModel", userModel))
 		return nil, xerr.WithStack(err)
 	}
 
@@ -185,11 +185,11 @@ func (s *StoreEntry) EventList(ctx context.Context, req *pasturePb.SearchCowEven
 }
 
 func (s *StoreEntry) BehaviorCurve(ctx context.Context, req *pasturePb.CowBehaviorCurveRequest) (*model.CowBehaviorCurveResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
-	cowInfo, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(req.CowId))
+	cowInfo, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(req.CowId))
 	if err != nil {
 		return nil, xerr.Customf("错误的牛只信息: %d", req.CowId)
 	}
@@ -203,7 +203,7 @@ func (s *StoreEntry) BehaviorCurve(ctx context.Context, req *pasturePb.CowBehavi
 	neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
 	if err = s.DB.Table(new(model.NeckActiveHabit).TableName()).
 		Where("neck_ring_number = ?", cowInfo.NeckRingNumber).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Where("heat_date BETWEEN ? AND ?", startDataTime, endDataTime).
 		Order("heat_date, frameid").
 		Find(&neckActiveHabitList).Error; err != nil {
@@ -215,7 +215,7 @@ func (s *StoreEntry) BehaviorCurve(ctx context.Context, req *pasturePb.CowBehavi
 	eventLog := &model.EventCowLog{CowId: cowInfo.Id}
 	if err = s.DB.Table(eventLog.TableName()).
 		Where("cow_id = ?", cowInfo.Id).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Where("event_at BETWEEN ? AND ?", nowDayZero-(30*86400), nowDayZero+86400).
 		Order("event_at").
 		Find(&eventLogList).Error; err != nil {
@@ -236,7 +236,7 @@ func (s *StoreEntry) BehaviorCurve(ctx context.Context, req *pasturePb.CowBehavi
 	estrusList := make([]*model.EventEstrus, 0)
 	if err = s.DB.Table(new(model.EventEstrus).TableName()).
 		Where("cow_id = ?", cowInfo.Id).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Where("estrus_start_date >= ?", startDataTime).
 		Where("estrus_start_date <= ?", endDataTime).
 		Order("estrus_start_date").
@@ -264,11 +264,11 @@ func (s *StoreEntry) BehaviorCurve(ctx context.Context, req *pasturePb.CowBehavi
 }
 
 func (s *StoreEntry) CowGrowthCurve(ctx context.Context, req *pasturePb.CowGrowthCurveRequest) (*pasturePb.CowGrowthCurveResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
-	cowInfo, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(req.CowId))
+	cowInfo, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(req.CowId))
 	if err != nil {
 		return nil, xerr.Customf("错误的牛只信息: %d", req.CowId)
 	}
@@ -276,7 +276,7 @@ func (s *StoreEntry) CowGrowthCurve(ctx context.Context, req *pasturePb.CowGrowt
 	weightList := make([]*model.EventWeight, 0)
 	if err = s.DB.Table(new(model.EventWeight).TableName()).
 		Where("cow_id = ?", cowInfo.Id).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Order("weight_at").
 		Find(&weightList).Error; err != nil {
 		return nil, xerr.WithStack(err)

+ 6 - 6
module/backend/enum_options.go

@@ -129,14 +129,14 @@ func (s *StoreEntry) CowTransferPenReasonOptions(ctx context.Context) (*pastureP
 }
 
 func (s *StoreEntry) SystemUserOptions(ctx context.Context, depId int) (*pasturePb.ConfigOptionsListResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	systemUserList := make([]*model.SystemUser, 0)
 	pref := s.DB.Table(new(model.SystemUser).TableName()).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Where("is_delete = ?", pasturePb.IsShow_Ok).
 		Where("is_show =? ", pasturePb.IsShow_Ok)
 	if depId != -1 && depId > 0 {
@@ -154,15 +154,15 @@ func (s *StoreEntry) SystemUserOptions(ctx context.Context, depId int) (*pasture
 }
 
 func (s *StoreEntry) BullOptions(ctx context.Context) (*pasturePb.BullOptionsListResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	return &pasturePb.BullOptionsListResponse{
 		Code: http.StatusOK,
 		Msg:  "ok",
-		Data: s.BullNumberEnumList("", currentUser),
+		Data: s.BullNumberEnumList("", userModel.AppPasture.Id),
 	}, nil
 }
 

+ 53 - 47
module/backend/event_base.go

@@ -38,15 +38,15 @@ func (s *StoreEntry) ParseCowIds(ctx context.Context, pastureId int64, cowIds st
 }
 
 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("当前用户信息错误,请退出重新登录")
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return nil, xerr.WithStack(err)
 	}
 
 	eventEnterList := make([]*model.EventEnter, 0)
 	var count int64 = 0
 	pref := s.DB.Model(new(model.EventEnter)).
-		Where("pasture_id = ?", currentUser.PastureId)
+		Where("pasture_id = ?", userModel.AppPasture.Id)
 	if len(req.CowId) > 0 {
 		cowIds := strings.Split(req.CowId, ",")
 		pref.Where("cow_id IN ?", cowIds)
@@ -59,7 +59,7 @@ func (s *StoreEntry) EnterList(ctx context.Context, req *pasturePb.SearchEventRe
 		return nil, xerr.WithStack(err)
 	}
 
-	penMap := s.PenMap(ctx, currentUser.PastureId)
+	penMap := s.PenMap(ctx, userModel.AppPasture.Id)
 	breedStatusMap := s.CowBreedStatusMap()
 	cowSourceMap := s.CowSourceMap()
 	cowTypeMap := s.CowTypeMap()
@@ -78,20 +78,20 @@ 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("当前用户信息错误,请退出重新登录")
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return xerr.WithStack(err)
 	}
 
-	req.MessengerId = int32(currentUser.Id)
-	req.MessengerName = currentUser.Name
+	req.MessengerId = int32(userModel.SystemUser.Id)
+	req.MessengerName = userModel.SystemUser.Name
 	if req.OperationId > 0 {
-		systemUser, _ := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
+		systemUser, _ := s.GetSystemUserById(ctx, int64(req.OperationId))
 		req.OperationName = systemUser.Name
 	}
 
-	newCowData := model.NewCow(currentUser, req)
-	newEventEnter := model.NewEventEnter(currentUser.PastureId, newCowData.Id, req)
+	newCowData := model.NewCow(userModel.AppPasture.Id, userModel.SystemUser, req)
+	newEventEnter := model.NewEventEnter(userModel.AppPasture.Id, 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)
@@ -99,12 +99,18 @@ func (s *StoreEntry) CreateEnter(ctx context.Context, req *pasturePb.EventEnterR
 		if err = tx.Create(newEventEnter).Error; err != nil {
 			return xerr.WithStack(err)
 		}
-		eventWeight := model.NewEventWeight(newCowData, currentUser, int32(req.Weight*1000), 0, &pasturePb.EventWeight{
-			WeightAt:      req.EnterAt,
-			Remarks:       "入场体重",
-			OperationId:   req.OperationId,
-			OperationName: req.OperationName,
-		})
+		eventWeight := model.NewEventWeight(
+			userModel.AppPasture.Id,
+			newCowData,
+			userModel.SystemUser,
+			int32(req.Weight*1000),
+			0,
+			&pasturePb.EventWeight{
+				WeightAt:      req.EnterAt,
+				Remarks:       "入场体重",
+				OperationId:   req.OperationId,
+				OperationName: req.OperationName,
+			})
 		if err = tx.Create(eventWeight).Error; err != nil {
 			return xerr.WithStack(err)
 		}
@@ -150,15 +156,15 @@ 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("当前用户信息错误,请退出重新登录")
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return xerr.WithStack(err)
 	}
 
 	newEventTransferGroupModelList := make([]*model.EventTransferGroupModel, 0)
 	transferPenMap := s.TransferPenMap()
 	for _, v := range req.Body {
-		cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(v.CowId))
+		cow, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(v.CowId))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
@@ -166,11 +172,11 @@ func (s *StoreEntry) CreateGroupTransfer(ctx context.Context, req *pasturePb.Tra
 		if cow.PenId == v.TransferInPenId {
 			continue
 		}
-		operationUser, err := s.GetSystemUserById(ctx, cow.PastureId, int64(v.OperationId))
+		operationUser, err := s.GetSystemUserById(ctx, int64(v.OperationId))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
-		newEventTransferGroup := model.NewEventTransferGroup(cow, v, transferPenMap, currentUser, operationUser)
+		newEventTransferGroup := model.NewEventTransferGroup(userModel.AppPasture.Id, cow, v, transferPenMap, userModel.SystemUser, operationUser)
 		newEventTransferGroupModelList = append(newEventTransferGroupModelList, &model.EventTransferGroupModel{
 			Cow:                cow,
 			EventTransferGroup: newEventTransferGroup,
@@ -183,7 +189,7 @@ func (s *StoreEntry) CreateGroupTransfer(ctx context.Context, req *pasturePb.Tra
 	defer func() {
 		if err != nil {
 			for _, etg := range newEventTransferGroupModelList {
-				cowLogs := s.SubmitEventLog(ctx, currentUser, etg.Cow, pasturePb.EventType_Transfer_Ben, pasturePb.ExposeEstrusType_Invalid, etg.EventTransferGroup)
+				cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, etg.Cow, pasturePb.EventType_Transfer_Ben, pasturePb.ExposeEstrusType_Invalid, etg.EventTransferGroup)
 				s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 			}
 		}
@@ -238,23 +244,23 @@ func (s *StoreEntry) CreateBodyScore(ctx context.Context, req *pasturePb.BodySco
 	if len(req.CowId) <= 0 {
 		return xerr.Custom("请选择相关牛只")
 	}
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("获取当前用户失败,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 	req.OperationName = operationUser.Name
 	bodyScourEvent := make([]*model.EventBodyScore, 0)
-	cowList, err := s.ParseCowIds(ctx, currentUser.PastureId, req.CowId)
+	cowList, err := s.ParseCowIds(ctx, userModel.AppPasture.Id, req.CowId)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 	for _, cow := range cowList {
-		bodyScourEvent = append(bodyScourEvent, model.NewEventBodyScore(cow, currentUser, req))
+		bodyScourEvent = append(bodyScourEvent, model.NewEventBodyScore(cow, userModel.AppPasture.Id, userModel.SystemUser, req))
 	}
 	if len(bodyScourEvent) <= 0 {
 		return nil
@@ -297,12 +303,12 @@ func (s *StoreEntry) WeightBatch(ctx context.Context, req *pasturePb.EventWeight
 		return xerr.Custom("请选择相关牛只")
 	}
 
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前登录用户失败,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
@@ -312,15 +318,15 @@ func (s *StoreEntry) WeightBatch(ctx context.Context, req *pasturePb.EventWeight
 		if err == nil {
 			// 记录事件日志
 			for _, item := range req.WeightItems {
-				cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(item.CowId))
-				cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Weight, pasturePb.ExposeEstrusType_Invalid, req)
+				cow, _ := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(item.CowId))
+				cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, 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, currentUser.PastureId, int64(item.CowId))
+		cow, err = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(item.CowId))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
@@ -337,7 +343,7 @@ func (s *StoreEntry) WeightBatch(ctx context.Context, req *pasturePb.EventWeight
 		}
 
 		// 创建牛只的体重记录
-		eventWeight := model.NewEventWeight(cow, currentUser, int32(item.Weight*1000), item.Height, req)
+		eventWeight := model.NewEventWeight(userModel.AppPasture.Id, cow, userModel.SystemUser, int32(item.Weight*1000), item.Height, req)
 		if err = s.DB.Create(eventWeight).Error; err != nil {
 			return xerr.WithStack(err)
 		}
@@ -350,21 +356,21 @@ func (s *StoreEntry) DepartureBatch(ctx context.Context, req *pasturePb.EventDep
 		return xerr.Custom("请选择相关牛只")
 	}
 
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前登录用户失败,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
 	newEventDepartureModelList := make([]*model.EventDepartureModel, 0)
 	cow := &model.Cow{}
 	for _, item := range req.Item {
-		cow, err = s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(item.CowId))
+		cow, err = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, 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, currentUser.PastureId, int64(item.OperationId))
+		operationUser, err := s.GetSystemUserById(ctx, int64(item.OperationId))
 		if err != nil {
 			zaplog.Error("DepartureBatch", zap.Any("item", item), zap.Any("err", err))
 			return xerr.Customf("获取操作人员信息失败: %d", item.OperationId)
@@ -378,7 +384,7 @@ func (s *StoreEntry) DepartureBatch(ctx context.Context, req *pasturePb.EventDep
 		default:
 			return xerr.Custom("未知的离场类型")
 		}
-		newEventDeparture := model.NewEventDeparture(currentUser.PastureId, cow, item, reasonName, currentUser, operationUser)
+		newEventDeparture := model.NewEventDeparture(userModel.AppPasture.Id, cow, item, reasonName, userModel.SystemUser, operationUser)
 		newEventDepartureModelList = append(newEventDepartureModelList, &model.EventDepartureModel{
 			EventDeparture: newEventDeparture,
 			Cow:            cow,
@@ -411,7 +417,7 @@ func (s *StoreEntry) DepartureBatch(ctx context.Context, req *pasturePb.EventDep
 			}
 
 			// 记录事件日志
-			cowLogs := s.SubmitEventLog(ctx, currentUser, item.Cow, eventType, pasturePb.ExposeEstrusType_Invalid, item)
+			cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, item.Cow, eventType, pasturePb.ExposeEstrusType_Invalid, item)
 			tx.Table(cowLogs.TableName()).Create(cowLogs)
 		}
 		return nil
@@ -422,12 +428,12 @@ func (s *StoreEntry) DepartureBatch(ctx context.Context, req *pasturePb.EventDep
 }
 
 func (s *StoreEntry) CowEarNumberUpdate(ctx context.Context, req *pasturePb.EventReplaceEarNumber) (err error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前登录用户失败,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
-	cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(req.CowId))
+	cow, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(req.CowId))
 	if err != nil {
 		return xerr.Custom("未找到该牛只信息")
 	}

+ 60 - 59
module/backend/event_breed.go

@@ -19,9 +19,9 @@ import (
 )
 
 func (s *StoreEntry) CalvingList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchLavingEventResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	lavingList := make([]*model.EventCalvingList, 0)
@@ -30,7 +30,7 @@ func (s *StoreEntry) CalvingList(ctx context.Context, req *pasturePb.SearchEvent
 		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())).
-		Where("pasture_id = ?", currentUser.PastureId)
+		Where("pasture_id = ?", userModel.AppPasture.Id)
 	if len(req.CowId) > 0 {
 		cowIds := strings.Split(req.CowId, ",")
 		pref.Where("a.cow_id IN ?", cowIds)
@@ -67,18 +67,18 @@ func (s *StoreEntry) CalvingList(ctx context.Context, req *pasturePb.SearchEvent
 }
 
 func (s *StoreEntry) CalvingCreate(ctx context.Context, req *pasturePb.EventCalving) (err error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
-	cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(req.CowId))
+	cow, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, 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, currentUser.PastureId, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return xerr.Customf("获取操作人员信息失败: %s", err.Error())
 	}
@@ -88,15 +88,15 @@ func (s *StoreEntry) CalvingCreate(ctx context.Context, req *pasturePb.EventCalv
 	defer func() {
 		if err == nil {
 			// 母牛事件日志
-			cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Calving, pasturePb.ExposeEstrusType_Invalid, req)
+			cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, 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, currentUser.PastureId, int64(v.CowId))
-				cowLogs = s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Birth, pasturePb.ExposeEstrusType_Invalid, v)
+				cow, _ = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(v.CowId))
+				cowLogs = s.SubmitEventLog(ctx, userModel.AppPasture.Id, cow, pasturePb.EventType_Birth, pasturePb.ExposeEstrusType_Invalid, v)
 				s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 			}
 		}
@@ -125,7 +125,7 @@ func (s *StoreEntry) CalvingCreate(ctx context.Context, req *pasturePb.EventCalv
 				continue
 			}
 			// 犊牛信息
-			newCalvingCalf := model.NewEventCalvingCalf(currentUser.PastureId, int64(req.CowId), newEventCalving.Id, int64(req.CalvingAt), v)
+			newCalvingCalf := model.NewEventCalvingCalf(userModel.AppPasture.Id, 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 {
@@ -154,35 +154,35 @@ func (s *StoreEntry) CalvingCreate(ctx context.Context, req *pasturePb.EventCalv
 }
 
 func (s *StoreEntry) SameTimeCreate(ctx context.Context, req *pasturePb.EventSameTime) (err error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 
-	eventCowSameTime, err := s.GetEventCowSameTimeByCowId(ctx, currentUser.PastureId, int64(req.CowId))
+	eventCowSameTime, err := s.GetEventCowSameTimeByCowId(ctx, userModel.AppPasture.Id, int64(req.CowId))
 	if err != nil {
 		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 {
+	if drugs, err = s.GetDrugsById(ctx, userModel.AppPasture.Id, 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.EventUpdate(drugs, req.Usage, req.Remarks, operationUser, currentUser)
+	eventCowSameTime.EventUpdate(drugs, req.Usage, req.Remarks, operationUser, userModel.SystemUser)
 
 	defer func() {
 		if err == nil {
 			// 记录牛只事件日志
-			cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, eventCowSameTime.CowId)
-			cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Seme_Time, pasturePb.ExposeEstrusType_Same_Time, req)
+			cow, _ := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, eventCowSameTime.CowId)
+			cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, cow, pasturePb.EventType_Seme_Time, pasturePb.ExposeEstrusType_Same_Time, req)
 			s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 		}
 	}()
@@ -197,19 +197,19 @@ func (s *StoreEntry) SameTimeCreate(ctx context.Context, req *pasturePb.EventSam
 }
 
 func (s *StoreEntry) SameTimeBatch(ctx context.Context, req *pasturePb.EventSameTimeBatch) (err error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return xerr.Customf("异常数据")
 	}
 	req.OperationName = operationUser.Name
 
 	drugs := &model.Drugs{}
-	if drugs, err = s.GetDrugsById(ctx, currentUser.PastureId, int64(req.DrugsId)); err != nil {
+	if drugs, err = s.GetDrugsById(ctx, userModel.AppPasture.Id, int64(req.DrugsId)); err != nil {
 		zaplog.Error("SameTimeBatch", zap.Any("err", err), zap.Any("req", req))
 		return xerr.Customf("该药物不存在: %d", req.DrugsId)
 	}
@@ -217,7 +217,7 @@ 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, currentUser.PastureId, int64(v))
+		eventCowSameTime, err := s.GetEventCowSameTimeByCowId(ctx, userModel.AppPasture.Id, int64(v))
 		if err != nil {
 			zaplog.Error("SameTimeCreate", zap.Any("err", err), zap.Any("req", req))
 			return xerr.WithStack(err)
@@ -229,10 +229,10 @@ func (s *StoreEntry) SameTimeBatch(ctx context.Context, req *pasturePb.EventSame
 		// 记录牛只事件日志
 		if err == nil {
 			for _, v := range eventCowSameTimeList {
-				cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, v.CowId)
+				cow, _ := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, v.CowId)
 				cowLogs := s.SubmitEventLog(
 					ctx,
-					currentUser,
+					userModel.AppPasture.Id,
 					cow,
 					pasturePb.EventType_Seme_Time,
 					pasturePb.ExposeEstrusType_Same_Time,
@@ -257,7 +257,7 @@ func (s *StoreEntry) SameTimeBatch(ctx context.Context, req *pasturePb.EventSame
 	if err = s.DB.Transaction(func(tx *gorm.DB) error {
 		for _, v := range eventCowSameTimeList {
 			// 更新SameTime
-			v.EventUpdate(drugs, req.Usage, req.Remarks, currentUser, operationUser)
+			v.EventUpdate(drugs, req.Usage, req.Remarks, userModel.SystemUser, operationUser)
 			if err = tx.Model(new(model.EventCowSameTime)).
 				Select("status", "drugs_id", "unit", "usage", "remarks", "operation_id", "operation_name").
 				Where("id = ?", v.Id).
@@ -277,14 +277,14 @@ func (s *StoreEntry) SameTimeList(
 	req *pasturePb.SearchEventRequest,
 	pagination *pasturePb.PaginationModel,
 ) (*pasturePb.SearchSameTimeResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	cowSameTimeList := make([]*model.EventCowSameTime, 0)
 	var count int64 = 0
-	pref := s.DB.Table(new(model.EventCowSameTime).TableName()).Where("pasture_id = ?", currentUser.PastureId)
+	pref := s.DB.Table(new(model.EventCowSameTime).TableName()).Where("pasture_id = ?", userModel.AppPasture.Id)
 	if req.CowId != "" {
 		cowIds := strings.Split(req.CowId, ",")
 		pref.Where("cow_id IN ?", cowIds)
@@ -311,16 +311,16 @@ func (s *StoreEntry) SameTimeList(
 }
 
 func (s *StoreEntry) EstrusList(ctx context.Context, req *pasturePb.EstrusItemsRequest, pagination *pasturePb.PaginationModel) (*pasturePb.EstrusItemsResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	estrusList := make([]*model.EventEstrus, 0)
 	var count int64 = 0
 	pref := s.DB.Table(new(model.EventEstrus).TableName()).
 		Where("is_show = ?", pasturePb.IsShow_Ok).
-		Where("pasture_id = ?", currentUser.PastureId)
+		Where("pasture_id = ?", userModel.AppPasture.Id)
 	if len(req.CowIds) > 0 {
 		cowIds := strings.Split(util.ArrayInt32ToStrings(req.CowIds, ","), ",")
 		pref.Where("cow_id IN ?", cowIds)
@@ -357,11 +357,11 @@ func (s *StoreEntry) EstrusList(ctx context.Context, req *pasturePb.EstrusItemsR
 }
 
 func (s *StoreEntry) EstrusBatchMating(ctx context.Context, req *pasturePb.EventEstrus) (err error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
-	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return xerr.Customf("该用户不存在: %d", req.OperationId)
 	}
@@ -376,8 +376,8 @@ func (s *StoreEntry) EstrusBatchMating(ctx context.Context, req *pasturePb.Event
 			return xerr.Custom("牛只信息不存在")
 		}
 
-		newEventMating := model.NewEventMating(currentUser.PastureId, cowInfo, time.Now().Unix(), pasturePb.ExposeEstrusType_Neck_Ring)
-		eventEstrus, ok, err := s.FindEventEstrusByCowId(ctx, currentUser.PastureId, int64(cowId))
+		newEventMating := model.NewEventMating(userModel.AppPasture.Id, cowInfo, time.Now().Unix(), pasturePb.ExposeEstrusType_Neck_Ring)
+		eventEstrus, ok, err := s.FindEventEstrusByCowId(ctx, userModel.AppPasture.Id, int64(cowId))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
@@ -435,9 +435,9 @@ func (s *StoreEntry) EstrusBatchMating(ctx context.Context, req *pasturePb.Event
 }
 
 func (s *StoreEntry) MatingList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.MatingEventResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	matingList := make([]*model.EventMating, 0)
@@ -445,7 +445,7 @@ func (s *StoreEntry) MatingList(ctx context.Context, req *pasturePb.SearchEventR
 	pref := s.DB.Model(new(model.EventMating)).
 		Where("mating_result > ?", pasturePb.MatingResult_Invalid).
 		Where("status = ?", pasturePb.IsShow_No).
-		Where("pasture_id = ?", currentUser.PastureId)
+		Where("pasture_id = ?", userModel.AppPasture.Id)
 	if len(req.CowId) > 0 {
 		cowIds := strings.Split(req.CowId, ",")
 		pref.Where("cow_id IN ?", cowIds)
@@ -482,18 +482,18 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 	if err = s.DB.Transaction(func(tx *gorm.DB) error {
 		for _, cow := range eventCheckModel.CowList {
 			// 获取牛只最近一次配种信息
-			lastEventMating, ok, err := s.FindLastEventMatingByCowId(ctx, eventCheckModel.CurrentUser.PastureId, cow.Id)
+			lastEventMating, ok, err := s.FindLastEventMatingByCowId(ctx, eventCheckModel.UserModel.AppPasture.Id, cow.Id)
 			if err != nil {
 				return xerr.WithStack(err)
 			}
 
 			// 1. 没有配种信息,(第一次参加配种的牛只,并且没有参与同期的牛只 )
 			if !ok {
-				newMating := model.NewEventMatingNaturalEstrus(cow, req, eventCheckModel.CurrentUser)
+				newMating := model.NewEventMatingNaturalEstrus(eventCheckModel.UserModel.AppPasture.Id, cow, req, eventCheckModel.UserModel.SystemUser)
 				if err = tx.Create(newMating).Error; err != nil {
 					return xerr.WithStack(err)
 				}
-				if err = s.MatingCowUpdate(ctx, cow, eventCheckModel.CurrentUser, req, false); err != nil {
+				if err = s.MatingCowUpdate(ctx, eventCheckModel.UserModel.AppPasture.Id, cow, req, false); err != nil {
 					return xerr.WithStack(err)
 				}
 				continue
@@ -501,7 +501,7 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 
 			// 2. 所有有配种数据的牛只
 			if lastEventMating == nil || lastEventMating.Id <= 0 {
-				zaplog.Error("MatingCreate", zap.Any("cow", cow), zap.Any("CurrentUser", eventCheckModel.CurrentUser))
+				zaplog.Error("MatingCreate", zap.Any("cow", cow), zap.Any("UserModel", eventCheckModel.UserModel))
 				return xerr.Customf("异常牛数据: %d", cow.Id)
 			}
 
@@ -519,7 +519,7 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 			// 2.2.  同期初配
 			IsMatingUpdate := lastEventMating.IsMatingUpdate()
 			if IsMatingUpdate {
-				lastEventMating.EventUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating, eventCheckModel.OperationUser, eventCheckModel.CurrentUser)
+				lastEventMating.EventUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating, eventCheckModel.OperationUser, eventCheckModel.UserModel.SystemUser)
 				if err = tx.Model(lastEventMating).
 					Select("mating_at", "status", "reality_day", "frozen_semen_number", "operation_id", "operation_name", "message_id", "message_name").
 					Where("id = ?", lastEventMating.Id).
@@ -540,8 +540,8 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 					return xerr.WithStack(err)
 				}
 				// 先创建一条新的配种数据
-				newMating := model.NewEventMating(eventCheckModel.CurrentUser.PastureId, cow, int64(req.MatingAt), req.ExposeEstrusType)
-				newMating.EventUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating, eventCheckModel.OperationUser, eventCheckModel.CurrentUser)
+				newMating := model.NewEventMating(eventCheckModel.UserModel.AppPasture.Id, cow, int64(req.MatingAt), req.ExposeEstrusType)
+				newMating.EventUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating, eventCheckModel.OperationUser, eventCheckModel.UserModel.SystemUser)
 				if err = tx.Model(newMating).Create(newMating).Error; err != nil {
 					return xerr.WithStack(err)
 				}
@@ -553,7 +553,7 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 			}
 
 			// 牛只基本中配种信息更新
-			if err = s.MatingCowUpdate(ctx, cow, eventCheckModel.CurrentUser, req, isReMating); err != nil {
+			if err = s.MatingCowUpdate(ctx, eventCheckModel.UserModel.AppPasture.Id, cow, req, isReMating); err != nil {
 				return xerr.WithStack(err)
 			}
 		}
@@ -580,7 +580,7 @@ func (s *StoreEntry) MatingCreate(ctx context.Context, req *pasturePb.EventMatin
 	return nil
 }
 
-func (s *StoreEntry) MatingCowUpdate(ctx context.Context, cow *model.Cow, currentUser *model.SystemUser, req *pasturePb.EventMating, isReMating bool) error {
+func (s *StoreEntry) MatingCowUpdate(ctx context.Context, pastureId int64, cow *model.Cow, req *pasturePb.EventMating, isReMating bool) error {
 	// 牛只基本中配种信息更新
 	cow.EventMatingUpdate(int64(req.MatingAt), req.FrozenSemenNumber, isReMating)
 	if err := s.DB.Model(cow).
@@ -590,7 +590,7 @@ func (s *StoreEntry) MatingCowUpdate(ctx context.Context, cow *model.Cow, curren
 		return xerr.WithStack(err)
 	}
 	// 记录日志
-	cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Mating, req.ExposeEstrusType, req)
+	cowLogs := s.SubmitEventLog(ctx, pastureId, cow, pasturePb.EventType_Mating, req.ExposeEstrusType, req)
 	if err := s.DB.Table(cowLogs.TableName()).Create(cowLogs).Error; err != nil {
 		return xerr.WithStack(err)
 	}
@@ -598,9 +598,9 @@ func (s *StoreEntry) MatingCowUpdate(ctx context.Context, cow *model.Cow, curren
 }
 
 func (s *StoreEntry) WeaningBatch(ctx context.Context, req *pasturePb.EventWeaningBatchRequest) (err error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
 	if len(req.Item) <= 0 {
@@ -621,7 +621,7 @@ func (s *StoreEntry) WeaningBatch(ctx context.Context, req *pasturePb.EventWeani
 		return xerr.WithStack(err)
 	}
 
-	operation, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
+	operation, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
@@ -629,8 +629,8 @@ func (s *StoreEntry) WeaningBatch(ctx context.Context, req *pasturePb.EventWeani
 	defer func() {
 		if err != nil {
 			for _, cowId := range cowIds {
-				cow, _ := s.GetCowInfoByCowId(ctx, currentUser.PastureId, cowId)
-				cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Weaning, pasturePb.ExposeEstrusType_Invalid, req)
+				cow, _ := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, cowId)
+				cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, cow, pasturePb.EventType_Weaning, pasturePb.ExposeEstrusType_Invalid, req)
 				s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 			}
 		}
@@ -639,14 +639,14 @@ func (s *StoreEntry) WeaningBatch(ctx context.Context, req *pasturePb.EventWeani
 	if err = s.DB.Transaction(func(tx *gorm.DB) error {
 		cowInfo := &model.Cow{}
 		for _, v := range eventWeaningList {
-			v.EventUpdate(int64(req.WeaningAt), req.Remarks, req.PenId, operation, currentUser)
+			v.EventUpdate(int64(req.WeaningAt), req.Remarks, req.PenId, operation, userModel.SystemUser)
 			if err = tx.Model(new(model.EventWeaning)).
 				Select("status", "reality_day", "operation_id", "operation_name", "message_id", "message_name", "remarks", "after_pen_id").
 				Where("id = ?", v.Id).
 				Updates(v).Error; err != nil {
 				return xerr.WithStack(err)
 			}
-			cowInfo, err = s.GetCowInfoByCowId(ctx, currentUser.PastureId, v.CowId)
+			cowInfo, err = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, v.CowId)
 			if err != nil {
 				return xerr.WithStack(err)
 			}
@@ -659,8 +659,9 @@ func (s *StoreEntry) WeaningBatch(ctx context.Context, req *pasturePb.EventWeani
 			}
 			// 创建牛只的体重记录
 			newEventWeight := model.NewEventWeight(
+				userModel.AppPasture.Id,
 				cowInfo,
-				currentUser,
+				userModel.SystemUser,
 				int32(cowWeightMap[v.CowId]*1000),
 				0,
 				&pasturePb.EventWeight{

+ 21 - 14
module/backend/event_breed_more.go

@@ -17,7 +17,7 @@ import (
 )
 
 func (s *StoreEntry) PregnantCheckList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.PregnantCheckEventResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
 		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
 	}
@@ -25,7 +25,7 @@ func (s *StoreEntry) PregnantCheckList(ctx context.Context, req *pasturePb.Searc
 	pregnantCheckList := make([]*model.EventPregnantCheck, 0)
 	var count int64 = 0
 	pref := s.DB.Table(new(model.EventPregnantCheck).TableName()).
-		Where("pasture_id = ?", currentUser.PastureId)
+		Where("pasture_id = ?", userModel.AppPasture.Id)
 	if len(req.CowId) > 0 {
 		cowIds := strings.Split(req.CowId, ",")
 		pref.Where("cow_id IN ?", cowIds)
@@ -96,7 +96,14 @@ func (s *StoreEntry) PregnantCheckCreateBatch(ctx context.Context, req *pastureP
 			}
 
 			// 更新孕检事件表
-			item.EventPregnancyCheck.EventUpdate(int64(item.PregnantCheckAt), item.PregnantCheckResult, item.PregnantCheckMethod, item.OperationUser, item.CurrentUser, item.Remarks)
+			item.EventPregnancyCheck.EventUpdate(
+				int64(item.PregnantCheckAt),
+				item.PregnantCheckResult,
+				item.PregnantCheckMethod,
+				item.OperationUser,
+				item.UserModel.SystemUser,
+				item.Remarks,
+			)
 			if err = tx.Model(new(model.EventPregnantCheck)).
 				Select("reality_day,pregnant_check_result,pregnant_check_method,operation_id,operation_name,message_id,message_name,remarks,status").
 				Where("id = ?", item.EventPregnancyCheck.Id).
@@ -105,7 +112,7 @@ func (s *StoreEntry) PregnantCheckCreateBatch(ctx context.Context, req *pastureP
 			}
 
 			// 记录日志
-			cowLogs := s.SubmitEventLog(ctx, item.CurrentUser, item.Cow, pasturePb.EventType_Pregnancy_Check, pasturePb.ExposeEstrusType_Invalid, req)
+			cowLogs := s.SubmitEventLog(ctx, item.UserModel.AppPasture.Id, item.Cow, pasturePb.EventType_Pregnancy_Check, pasturePb.ExposeEstrusType_Invalid, req)
 			tx.Table(cowLogs.TableName()).Create(cowLogs)
 
 			// 更新上次配种结果
@@ -115,7 +122,7 @@ func (s *StoreEntry) PregnantCheckCreateBatch(ctx context.Context, req *pastureP
 
 			// 如果确定是流产
 			if matingResult == pasturePb.MatingResult_Abort {
-				newEventAbortion := model.NewEventAbortion(item.CurrentUser.PastureId, item.Cow, &pasturePb.EventAbortionRequest{
+				newEventAbortion := model.NewEventAbortion(item.UserModel.AppPasture.Id, item.Cow, &pasturePb.EventAbortionRequest{
 					CowId:               int32(item.Cow.Id),
 					AbortionAt:          item.PregnantCheckAt,
 					IsAfterbirth:        pasturePb.IsShow_No,
@@ -140,24 +147,24 @@ func (s *StoreEntry) PregnantCheckCreateBatch(ctx context.Context, req *pastureP
 }
 
 func (s *StoreEntry) AbortionCreate(ctx context.Context, req *pasturePb.EventAbortionRequest) error {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
-	cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(req.CowId))
+	cow, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(req.CowId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 
-	systemUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
+	systemUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 
 	req.OperationName = systemUser.Name
 	req.AbortionReasonsName = s.AbortionReasonsMap()[req.AbortionReasons]
-	newEventAbortion := model.NewEventAbortion(currentUser.PastureId, cow, req, pasturePb.IsShow_No)
+	newEventAbortion := model.NewEventAbortion(userModel.AppPasture.Id, cow, req, pasturePb.IsShow_No)
 
 	lastCowMating := &model.EventMating{}
 	if err = s.DB.Model(new(model.EventMating)).Where("cow_id = ?", cow.Id).
@@ -172,7 +179,7 @@ func (s *StoreEntry) AbortionCreate(ctx context.Context, req *pasturePb.EventAbo
 
 	defer func() {
 		if err != nil {
-			cowLogs := s.SubmitEventLog(ctx, currentUser, cow, pasturePb.EventType_Abort, pasturePb.ExposeEstrusType_Invalid, req)
+			cowLogs := s.SubmitEventLog(ctx, userModel.AppPasture.Id, cow, pasturePb.EventType_Abort, pasturePb.ExposeEstrusType_Invalid, req)
 			s.DB.Table(cowLogs.TableName()).Create(cowLogs)
 		}
 	}()
@@ -228,15 +235,15 @@ func (s *StoreEntry) AbortionList(
 	req *pasturePb.SearchEventRequest,
 	pagination *pasturePb.PaginationModel,
 ) (*pasturePb.EventAbortionResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	abortionList := make([]*model.EventAbortion, 0)
 	var count int64 = 0
 	pref := s.DB.Model(new(model.EventAbortion)).
-		Where("pasture_id = ?", currentUser.PastureId)
+		Where("pasture_id = ?", userModel.AppPasture.Id)
 	if len(req.CowId) > 0 {
 		cowIds := strings.Split(req.CowId, ",")
 		pref.Where("cow_id IN ?", cowIds)

+ 13 - 13
module/backend/event_check.go

@@ -16,7 +16,7 @@ import (
 type EventCheckBatchModel struct {
 	CowList       []*model.Cow
 	FrozenSemen   *model.FrozenSemen
-	CurrentUser   *model.SystemUser
+	UserModel     *model.UserModel
 	OperationUser *model.SystemUser
 }
 
@@ -29,7 +29,7 @@ type PregnantCheckBatchModel struct {
 	PregnantCheckResult pasturePb.PregnantCheckResult_Kind // 孕检结果
 	PregnantCheckMethod pasturePb.PregnantCheckMethod_Kind // 孕检方式
 	Remarks             string
-	CurrentUser         *model.SystemUser
+	UserModel           *model.UserModel
 	LastMating          *model.EventMating
 }
 
@@ -45,9 +45,9 @@ func (s *StoreEntry) MatingCreateCheck(ctx context.Context, req *pasturePb.Event
 		return nil, xerr.Custom("请选择相关牛只")
 	}
 
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	cowIds := make([]int64, 0)
@@ -59,12 +59,12 @@ func (s *StoreEntry) MatingCreateCheck(ctx context.Context, req *pasturePb.Event
 		return nil, xerr.Custom("最多只能选择50只牛只")
 	}
 
-	cowList, err := s.GetCowInfoByCowIds(ctx, currentUser.PastureId, cowIds)
+	cowList, err := s.GetCowInfoByCowIds(ctx, userModel.AppPasture.Id, cowIds)
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -108,7 +108,7 @@ func (s *StoreEntry) MatingCreateCheck(ctx context.Context, req *pasturePb.Event
 	return &EventCheckBatchModel{
 		CowList:       cowList,
 		FrozenSemen:   frozenSemen,
-		CurrentUser:   currentUser,
+		UserModel:     userModel,
 		OperationUser: operationUser,
 	}, nil
 }
@@ -118,20 +118,20 @@ func (s *StoreEntry) PregnantCheckDataCheck(ctx context.Context, req *pasturePb.
 		return nil, xerr.Custom("请选择相关牛只")
 	}
 
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	pregnantCheckBatchModelList := make([]*PregnantCheckBatchModel, 0)
 	for _, pregnantCheckData := range req.Item {
-		operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(pregnantCheckData.OperationId))
+		operationUser, err := s.GetSystemUserById(ctx, 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, currentUser.PastureId, int64(pregnantCheckData.CowId))
+		cow, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(pregnantCheckData.CowId))
 		if err != nil {
 			return nil, xerr.WithStack(err)
 		}
@@ -151,7 +151,7 @@ func (s *StoreEntry) PregnantCheckDataCheck(ctx context.Context, req *pasturePb.
 			return nil, xerr.Customf("该牛只孕检事件数据异常, cowId: %d", pregnantCheckData.CowId)
 		}
 
-		lastEventMating, ok, err := s.FindLastEventMatingByCowId(ctx, currentUser.PastureId, cow.Id)
+		lastEventMating, ok, err := s.FindLastEventMatingByCowId(ctx, userModel.AppPasture.Id, cow.Id)
 		if err != nil || !ok {
 			return nil, xerr.Customf("该牛只配种事件数据异常, cowId: %d", pregnantCheckData.CowId)
 		}
@@ -164,7 +164,7 @@ func (s *StoreEntry) PregnantCheckDataCheck(ctx context.Context, req *pasturePb.
 			PregnantCheckResult: pregnantCheckData.PregnantCheckResult,
 			Remarks:             pregnantCheckData.Remarks,
 			EventPregnancyCheck: itemEventPregnantCheck,
-			CurrentUser:         currentUser,
+			UserModel:           userModel,
 			LastMating:          lastEventMating,
 		})
 	}

+ 2 - 2
module/backend/event_cow_log.go

@@ -14,7 +14,7 @@ import (
 
 func (s *StoreEntry) SubmitEventLog(
 	ctx context.Context,
-	currentUser *model.SystemUser,
+	pastureId int64,
 	cow *model.Cow,
 	eventType pasturePb.EventType_Kind,
 	exposeEstrusType pasturePb.ExposeEstrusType_Kind,
@@ -25,7 +25,7 @@ func (s *StoreEntry) SubmitEventLog(
 		eventTypeName   = s.EventTypeMap()[eventType]
 		eventAt         = int64(0)
 		eventCategoryId = pasturePb.EventCategory_Invalid
-		penMap          = s.PenMap(ctx, currentUser.PastureId)
+		penMap          = s.PenMap(ctx, pastureId)
 		cowTypeMap      = s.CowTypeMap()
 		operationUser   = &model.SystemUser{}
 	)

+ 51 - 43
module/backend/event_health.go

@@ -19,27 +19,27 @@ import (
 
 // CowDiseaseCreate 牛只发病提交
 func (s *StoreEntry) CowDiseaseCreate(ctx context.Context, req *pasturePb.EventCowDiseaseRequest, source string) error {
-	currUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("登录信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 	// 牛只信息
-	cow, err := s.GetCowInfoByCowId(ctx, currUser.PastureId, int64(req.CowId))
+	cow, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(req.CowId))
 	if err != nil {
 		return xerr.Customf("牛只信息错误: %d", req.CowId)
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, currUser.PastureId, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return xerr.Customf("请检查操作人信息")
 	}
 
-	disease, err := s.GetDiseaseById(ctx, currUser.PastureId, req.DiseaseId)
+	disease, err := s.GetDiseaseById(ctx, userModel.AppPasture.Id, req.DiseaseId)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 
-	newEventCowDisease := model.NewEventCowDisease(cow, disease, req, operationUser, currUser)
+	newEventCowDisease := model.NewEventCowDisease(userModel.AppPasture.Id, cow, disease, req, operationUser, userModel.SystemUser)
 	defer func() {
 		// 更新牛只健康状态
 		if newEventCowDisease.HealthStatus == pasturePb.HealthStatus_Disease || newEventCowDisease.HealthStatus == pasturePb.HealthStatus_Treatment {
@@ -51,7 +51,7 @@ func (s *StoreEntry) CowDiseaseCreate(ctx context.Context, req *pasturePb.EventC
 		}
 
 		if req.PenId > 0 {
-			penMap := s.PenMap(ctx, currUser.PastureId)
+			penMap := s.PenMap(ctx, userModel.AppPasture.Id)
 			penData, ok := penMap[req.PenId]
 			if !ok {
 				return
@@ -84,12 +84,12 @@ func (s *StoreEntry) CowDiseaseCreate(ctx context.Context, req *pasturePb.EventC
 		isCreatePrescription = true
 
 		if req.PrescriptionId > 0 {
-			prescription, err = s.GetPrescriptionById(ctx, currUser.PastureId, req.PrescriptionId)
+			prescription, err = s.GetPrescriptionById(ctx, userModel.AppPasture.Id, req.PrescriptionId)
 			if err != nil {
 				return xerr.WithStack(err)
 			}
 
-			prescriptionDrugs, err := s.PrescriptionDrugsByPrescriptionId(ctx, currUser.PastureId, prescription.Id)
+			prescriptionDrugs, err := s.PrescriptionDrugsByPrescriptionId(ctx, userModel.AppPasture.Id, prescription.Id)
 			if err != nil {
 				return xerr.WithStack(err)
 			}
@@ -120,14 +120,22 @@ func (s *StoreEntry) CowDiseaseCreate(ctx context.Context, req *pasturePb.EventC
 				ApplicableDiseaseIds: []int32{req.DiseaseId},
 				IsShow:               pasturePb.IsShow_Ok,
 			}
-			newPrescription := model.NewPrescription(currUser.PastureId, newPrescriptionRequest, fmt.Sprintf("%d", disease.Id), 1, 0, 0, currUser)
+			newPrescription := model.NewPrescription(
+				userModel.AppPasture.Id,
+				newPrescriptionRequest,
+				fmt.Sprintf("%d", disease.Id),
+				1,
+				0,
+				0,
+				userModel.SystemUser,
+			)
 			newPrescription.UseCount += 1
 			if err = tx.Model(new(model.Prescription)).Create(newPrescription).Error; err != nil {
 				return xerr.WithStack(err)
 			}
 			prescription = newPrescription
 
-			newPrescriptionDrugs := model.NewPrescriptionDrugs(currUser.PastureId, prescription.Id, req.PrescriptionDetail)
+			newPrescriptionDrugs := model.NewPrescriptionDrugs(userModel.AppPasture.Id, prescription.Id, req.PrescriptionDetail)
 			if err = tx.Model(new(model.PrescriptionDrugs)).Create(newPrescriptionDrugs).Error; err != nil {
 				return xerr.WithStack(err)
 			}
@@ -150,7 +158,7 @@ func (s *StoreEntry) CowDiseaseCreate(ctx context.Context, req *pasturePb.EventC
 				TreatmentAt:        req.DiseaseAt,
 			}
 
-			newEventCowTreatment = model.NewEventCowTreatment(prescription, newCowTreatmentRequest, diseaseTypeMap, operationUser, currUser)
+			newEventCowTreatment = model.NewEventCowTreatment(userModel.AppPasture.Id, prescription, newCowTreatmentRequest, diseaseTypeMap, operationUser, userModel.SystemUser)
 			// 创建治疗记录
 			if err = tx.Model(new(model.EventCowTreatment)).Create(newEventCowTreatment).Error; err != nil {
 				return xerr.WithStack(err)
@@ -165,16 +173,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)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("登录信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	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.pasture_id = ?", currUser.PastureId)
+		Where("a.diagnosed_result < ?", pasturePb.IsShow_No).Where("a.pasture_id = ?", userModel.AppPasture.Id)
 
 	if len(req.CowIds) > 0 {
 		pref.Where("a.cow_id IN ?", req.CowIds)
@@ -226,12 +234,12 @@ func (s *StoreEntry) CowDiseaseList(ctx context.Context, req *pasturePb.SearchEv
 
 // CowDiseaseDiagnose 发病牛只诊断
 func (s *StoreEntry) CowDiseaseDiagnose(ctx context.Context, req *pasturePb.CowDiagnosedRequest) error {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
-	cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(req.CowId))
+	cow, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(req.CowId))
 	if err != nil {
 		return xerr.Customf("错误的牛只信息: %d", req.CowId)
 	}
@@ -241,9 +249,9 @@ func (s *StoreEntry) CowDiseaseDiagnose(ctx context.Context, req *pasturePb.CowD
 		Where("cow_id = ?", req.CowId).
 		Where("id = ?", req.Id).
 		Where("health_status = ?", pasturePb.HealthStatus_Health).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		First(eventCowDisease).Error; err != nil {
-		zaplog.Error("CowDiseaseDiagnose", zap.Any("req", req), zap.Any("currentUser", currentUser))
+		zaplog.Error("CowDiseaseDiagnose", zap.Any("req", req), zap.Any("userModel", userModel))
 		return xerr.Custom("异常牛只数据")
 	}
 
@@ -253,7 +261,7 @@ func (s *StoreEntry) CowDiseaseDiagnose(ctx context.Context, req *pasturePb.CowD
 
 	if req.DiagnosedResult == pasturePb.IsShow_No {
 		// 未发病更新
-		eventCowDisease.EventUnDiseaseUpdate(currentUser, req.Remarks)
+		eventCowDisease.EventUnDiseaseUpdate(userModel.SystemUser, req.Remarks)
 		if err = s.DB.Model(eventCowDisease).
 			Select("diagnosed_result", "diagnose_operation_id", "diagnose_operation_name", "remarks").
 			Where("id = ?", req.Id).
@@ -264,11 +272,11 @@ func (s *StoreEntry) CowDiseaseDiagnose(ctx context.Context, req *pasturePb.CowD
 	}
 
 	// 已发病
-	disease, err := s.GetDiseaseById(ctx, currentUser.PastureId, req.DiseaseId)
+	disease, err := s.GetDiseaseById(ctx, userModel.AppPasture.Id, req.DiseaseId)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
-	systemUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))
+	systemUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
@@ -300,9 +308,9 @@ 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)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
 	eventCowDisease := &model.EventCowDisease{}
@@ -317,29 +325,29 @@ func (s *StoreEntry) CowDiseaseTreatment(ctx context.Context, req *pasturePb.Cow
 		return xerr.Custom("异常牛只数据")
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, currUser.PastureId, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return xerr.Customf("操作人数据异常: %d", req.OperationId)
 	}
 
-	prescription, err := s.GetPrescriptionById(ctx, currUser.PastureId, req.PrescriptionId)
+	prescription, err := s.GetPrescriptionById(ctx, userModel.AppPasture.Id, req.PrescriptionId)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 
-	cow, err := s.GetCowInfoByCowId(ctx, currUser.PastureId, int64(req.CowId))
+	cow, err := s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(req.CowId))
 	if err != nil {
 		return xerr.Customf("异常牛数据: %d", req.CowId)
 	}
 
-	disease, err := s.GetDiseaseById(ctx, currUser.PastureId, eventCowDisease.DiagnoseId)
+	disease, err := s.GetDiseaseById(ctx, userModel.AppPasture.Id, eventCowDisease.DiagnoseId)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 	req.DiseaseName = disease.Name
 	req.DiseaseType = disease.DiseaseType
 
-	prescriptionDrugs, err := s.PrescriptionDrugsByPrescriptionId(ctx, currUser.PastureId, prescription.Id)
+	prescriptionDrugs, err := s.PrescriptionDrugsByPrescriptionId(ctx, userModel.AppPasture.Id, prescription.Id)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
@@ -369,7 +377,7 @@ func (s *StoreEntry) CowDiseaseTreatment(ctx context.Context, req *pasturePb.Cow
 		healthStatus = pasturePb.HealthStatus_Dead
 	}
 	diseaseTypeMap := s.DiseaseTypeMap()
-	newEventCowTreatment := model.NewEventCowTreatment(prescription, req, diseaseTypeMap, operationUser, currUser)
+	newEventCowTreatment := model.NewEventCowTreatment(userModel.AppPasture.Id, prescription, req, diseaseTypeMap, operationUser, userModel.SystemUser)
 	if err = s.DB.Transaction(func(tx *gorm.DB) error {
 		if err = tx.Create(newEventCowTreatment).Error; err != nil {
 			return xerr.WithStack(err)
@@ -408,16 +416,16 @@ 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)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	res := make([]*pasturePb.ConfigOptionsList, 0)
 	prescriptionList := make([]*model.Prescription, 0)
 	if err = s.DB.Model(new(model.Prescription)).
 		Where("is_show = ?", pasturePb.IsShow_Ok).
-		Where("pasture_id = ?", currUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Find(&prescriptionList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -448,15 +456,15 @@ func (s *StoreEntry) CowDiseaseTreatmentDetail(
 	req *pasturePb.EventCowTreatmentDetailRequest,
 	pagination *pasturePb.PaginationModel,
 ) (*pasturePb.EventCowTreatmentDetailResponse, error) {
-	currUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	eventCowDiseaseList := make([]*model.EventCowDisease, 0)
 	var count int64 = 0
 	pref := s.DB.Model(new(model.EventCowDisease)).
-		Where("cow_id = ?", req.CowId).Where("pasture_id = ?", currUser.PastureId)
+		Where("cow_id = ?", req.CowId).Where("pasture_id = ?", userModel.AppPasture.Id)
 
 	if req.DiseaseId > 0 {
 		pref.Where("disease_id = ?", req.DiseaseId)
@@ -502,15 +510,15 @@ func (s *StoreEntry) CowDiseaseTreatmentDetail(
 }
 
 func (s *StoreEntry) CowDiseaseCurable(ctx context.Context, req *pasturePb.EventCowCurableRequest) error {
-	currUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
 	eventCowDiseaseList := make([]*model.EventCowDisease, 0)
 	if err = s.DB.Where("id IN ?", req.Ids).
 		Where("health_status = ?", pasturePb.HealthStatus_Treatment).
-		Where("pasture_id = ?", currUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Find(&eventCowDiseaseList).Error; err != nil {
 		zaplog.Error("GetEventCowDiseaseList", zap.Any("err", err), zap.Any("req", req))
 		return xerr.Custom("异常数据")
@@ -520,14 +528,14 @@ func (s *StoreEntry) CowDiseaseCurable(ctx context.Context, req *pasturePb.Event
 		return nil
 	}
 
-	operationUser, err := s.GetSystemUserById(ctx, currUser.PastureId, int64(req.OperationId))
+	operationUser, err := s.GetSystemUserById(ctx, int64(req.OperationId))
 	if err != nil {
 		return xerr.Customf("该用户不存在: %d", req.OperationId)
 	}
 
 	eventCowTreatmentList := make([]*model.EventCowTreatment, 0)
 	for _, v := range eventCowDiseaseList {
-		newEventCowTreatment := model.NewEventCowCurableTreatment(currUser, operationUser, v, req.Remarks, int64(req.CurableAt))
+		newEventCowTreatment := model.NewEventCowCurableTreatment(userModel.AppPasture.Id, userModel.SystemUser, operationUser, v, req.Remarks, int64(req.CurableAt))
 		eventCowTreatmentList = append(eventCowTreatmentList, newEventCowTreatment)
 	}
 
@@ -547,7 +555,7 @@ func (s *StoreEntry) CowDiseaseCurable(ctx context.Context, req *pasturePb.Event
 				return xerr.WithStack(err)
 			}
 
-			cow, err = s.GetCowInfoByCowId(ctx, currUser.PastureId, eventCowDisease.CowId)
+			cow, err = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, eventCowDisease.CowId)
 			if err != nil {
 				return xerr.WithStack(err)
 			}

+ 58 - 45
module/backend/goods.go

@@ -16,15 +16,15 @@ import (
 )
 
 func (s *StoreEntry) DrugsList(ctx context.Context, req *pasturePb.SearchDrugsRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchDrugsResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	drugsList := make([]*model.Drugs, 0)
 	var count int64 = 0
 
-	pref := s.DB.Model(new(model.Drugs)).Where("pasture_id = ?", currentUser.PastureId)
+	pref := s.DB.Model(new(model.Drugs)).Where("pasture_id = ?", userModel.AppPasture.Id)
 	if req.Name != "" {
 		pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
 	}
@@ -55,16 +55,16 @@ 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)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
 	req.CategoryName = s.DrugCategoryMaps()[req.CategoryId]
 	req.UnitName = s.UnitMap()[req.Unit]
 	req.UnitName = s.DrugUsageMaps()[req.Usage]
 
-	newDrugs := model.NewDrugs(req, currentUser)
+	newDrugs := model.NewDrugs(userModel.AppPasture.Id, req, userModel.SystemUser)
 	if req.Id <= 0 {
 		if err = s.DB.Create(newDrugs).Error; err != nil {
 			return xerr.WithStack(err)
@@ -79,15 +79,15 @@ 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)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	medicalEquipmentList := make([]*model.MedicalEquipment, 0)
 	var count int64 = 0
 
-	pref := s.DB.Model(new(model.MedicalEquipment)).Where("pasture_id = ?", currentUser.PastureId)
+	pref := s.DB.Model(new(model.MedicalEquipment)).Where("pasture_id = ?", userModel.AppPasture.Id)
 	if req.Name != "" {
 		pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
 	}
@@ -111,11 +111,11 @@ 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)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
-	newDrugs := model.NewMedicalEquipment(req, currentUser)
+	newDrugs := model.NewMedicalEquipment(userModel.AppPasture.Id, req, userModel.SystemUser)
 	if req.Id <= 0 {
 		if err = s.DB.Create(newDrugs).Error; err != nil {
 			return xerr.WithStack(err)
@@ -129,9 +129,9 @@ 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)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
 	if req.Items == nil || len(req.Items) == 0 {
@@ -143,13 +143,13 @@ func (s *StoreEntry) NeckRingCreateOrUpdate(ctx context.Context, req *pasturePb.
 			switch req.Status {
 			// 绑定
 			case pasturePb.NeckRingOperationStatus_Bind:
-				_, err = s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(v.CowId))
+				_, err = s.GetCowInfoByCowId(ctx, userModel.AppPasture.Id, int64(v.CowId))
 				if err != nil {
 					return xerr.Customf("该牛不存在")
 				}
-				neckRing, ok := s.NeckRingIsExist(ctx, currentUser.PastureId, v.Number)
+				neckRing, ok := s.NeckRingIsExist(ctx, userModel.AppPasture.Id, v.Number)
 				if !ok {
-					newNeckRing := model.NewNeckRing(currentUser.PastureId, v.Number, int64(v.CowId), currentUser)
+					newNeckRing := model.NewNeckRing(userModel.AppPasture.Id, v.Number, int64(v.CowId), userModel.SystemUser)
 					if err = tx.Create(newNeckRing).Error; err != nil {
 						return xerr.WithStack(err)
 					}
@@ -164,7 +164,7 @@ func (s *StoreEntry) NeckRingCreateOrUpdate(ctx context.Context, req *pasturePb.
 					}
 				}
 
-				newNeckRingLog := model.NewNeckRingBindLog(v.Number, int64(v.CowId), currentUser)
+				newNeckRingLog := model.NewNeckRingBindLog(userModel.AppPasture.Id, v.Number, int64(v.CowId), userModel.SystemUser)
 				if err = tx.Create(newNeckRingLog).Error; err != nil {
 					return xerr.WithStack(err)
 				}
@@ -223,9 +223,9 @@ 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)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	neckRingLogList := make([]*model.NeckRing, 0)
@@ -233,7 +233,7 @@ func (s *StoreEntry) NeckRingList(ctx context.Context, req *pasturePb.SearchNeck
 
 	pref := s.DB.Model(new(model.NeckRing)).
 		Where("status >= ?", pasturePb.NeckRingStatus_Unbind).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Where("neck_ring_number != ''")
 	if req.Status > 0 {
 		pref.Where("status = ?", req.Status)
@@ -269,9 +269,9 @@ func (s *StoreEntry) NeckRingList(ctx context.Context, req *pasturePb.SearchNeck
 }
 
 func (s *StoreEntry) OutboundApply(ctx context.Context, req *pasturePb.OutboundApplyItem) error {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("登录人信息失效")
+		return xerr.WithStack(err)
 	}
 
 	if len(req.Goods) <= 0 {
@@ -279,11 +279,11 @@ func (s *StoreEntry) OutboundApply(ctx context.Context, req *pasturePb.OutboundA
 	}
 	var outbound *model.Outbound
 	if req.Id > 0 {
-		outbound, err = s.GetOutboundById(ctx, int64(req.Id))
+		outbound, err = s.GetOutboundById(ctx, userModel.AppPasture.Id, int64(req.Id))
 		if err != nil || outbound == nil || outbound.Id <= 0 {
 			return xerr.Customf("该出库单不存在")
 		}
-		if currentUser.Id != int64(outbound.ApplicantId) {
+		if userModel.SystemUser.Id != int64(outbound.ApplicantId) {
 			return xerr.Custom("非申请人,无权修改该出库单")
 		}
 
@@ -292,7 +292,7 @@ func (s *StoreEntry) OutboundApply(ctx context.Context, req *pasturePb.OutboundA
 		}
 	} else {
 		// 创建出库申请
-		outbound = model.NewOutbound(req, currentUser)
+		outbound = model.NewOutbound(userModel.SystemUser.Id, req, userModel.SystemUser)
 	}
 	goodsItems := make([]*pasturePb.OutboundApplyGoodsItem, 0)
 	switch req.OutType {
@@ -385,12 +385,17 @@ func (s *StoreEntry) OutboundApply(ctx context.Context, req *pasturePb.OutboundA
 }
 
 func (s *StoreEntry) OutboundList(ctx context.Context, req *pasturePb.SearchOutboundApplyRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchOutboundApplyResponse, error) {
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return nil, xerr.WithStack(err)
+	}
+
 	startUnix := util.TimeParseLocalUnix(req.StartDayTime)
 	endUnix := util.TimeParseLocalEndUnix(req.EndDayTime)
 
 	var count int64 = 0
 	outboundList := make([]*model.Outbound, 0)
-	pref := s.DB.Model(new(model.Outbound))
+	pref := s.DB.Model(new(model.Outbound)).Where("pasture_id = ?", userModel.AppPasture.Id)
 	if req.OutType > 0 {
 		pref.Where("out_type = ?", req.OutType)
 	}
@@ -439,7 +444,12 @@ func (s *StoreEntry) OutboundList(ctx context.Context, req *pasturePb.SearchOutb
 }
 
 func (s *StoreEntry) OutboundAudit(ctx context.Context, req *pasturePb.OutboundApplyAuditRequest) error {
-	outbound, err := s.GetOutboundById(ctx, int64(req.Id))
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return xerr.WithStack(err)
+	}
+
+	outbound, err := s.GetOutboundById(ctx, userModel.AppPasture.Id, int64(req.Id))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
@@ -456,11 +466,6 @@ func (s *StoreEntry) OutboundAudit(ctx context.Context, req *pasturePb.OutboundA
 		return xerr.Custom("异常出库单")
 	}
 
-	currentUser, err := s.GetCurrentSystemUser(ctx)
-	if err != nil {
-		return xerr.Custom("登录人信息失效")
-	}
-
 	outboundDetails, err := s.GetOutboundDetailByOutboundId(ctx, outbound.Id)
 	if err != nil {
 		return xerr.WithStack(err)
@@ -475,8 +480,8 @@ func (s *StoreEntry) OutboundAudit(ctx context.Context, req *pasturePb.OutboundA
 			Where("id = ?", outbound.Id).
 			Updates(map[string]interface{}{
 				"audit_status":    req.AuditStatus,
-				"examine_id":      currentUser.Id,
-				"examine_name":    currentUser.Name,
+				"examine_id":      userModel.SystemUser.Id,
+				"examine_name":    userModel.SystemUser.Name,
 				"examine_remarks": req.ExamineRemarks,
 				"examine_at":      time.Now().Unix(),
 			}).Error; err != nil {
@@ -515,7 +520,12 @@ func (s *StoreEntry) OutboundAudit(ctx context.Context, req *pasturePb.OutboundA
 }
 
 func (s *StoreEntry) OutboundDetail(ctx context.Context, id int64) (*pasturePb.OutboundDetailResponse, error) {
-	outbound, err := s.GetOutboundById(ctx, id)
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return nil, xerr.WithStack(err)
+	}
+
+	outbound, err := s.GetOutboundById(ctx, userModel.AppPasture.Id, id)
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -558,25 +568,25 @@ func (s *StoreEntry) OutboundDetail(ctx context.Context, id int64) (*pasturePb.O
 }
 
 func (s *StoreEntry) OutboundDelete(ctx context.Context, id int64) error {
-	outbound, err := s.GetOutboundById(ctx, id)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 
-	if outbound == nil {
-		return xerr.Custom("出库单不存在")
+	outbound, err := s.GetOutboundById(ctx, userModel.AppPasture.Id, id)
+	if err != nil {
+		return xerr.WithStack(err)
 	}
 
-	currUser, err := s.GetCurrentSystemUser(ctx)
-	if err != nil {
-		return xerr.Custom("登录信息失效")
+	if outbound == nil {
+		return xerr.Custom("出库单不存在")
 	}
 
 	if !(outbound.AuditStatus == pasturePb.AuditStatus_Pending || outbound.AuditStatus == pasturePb.AuditStatus_Cancel) {
 		return xerr.Custom("出库单无法删除")
 	}
 
-	if currUser.Id != int64(outbound.ApplicantId) {
+	if userModel.SystemUser.Id != int64(outbound.ApplicantId) {
 		return xerr.Custom("非申请人,无权删除出库单")
 	}
 
@@ -624,9 +634,12 @@ func (s *StoreEntry) FrozenSemenList(ctx context.Context, req *pasturePb.FrozenS
 }
 
 func (s *StoreEntry) FrozenSemenCreate(ctx context.Context, req *pasturePb.SearchFrozenSemenList) error {
-	currentUser, _ := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return xerr.WithStack(err)
+	}
 	req.CowKindName = s.CowKindMap()[req.CowKind]
-	newFrozenSemen := model.NewFrozenSemen(req, currentUser)
+	newFrozenSemen := model.NewFrozenSemen(userModel.AppPasture.Id, req, userModel.SystemUser)
 	if err := s.DB.Create(newFrozenSemen).Error; err != nil {
 		return xerr.WithStack(err)
 	}

+ 3 - 3
module/backend/indicators.go

@@ -10,14 +10,14 @@ import (
 )
 
 func (s *StoreEntry) IndicatorsComparison(ctx context.Context, req *pasturePb.IndicatorsComparisonRequest) (*model.IndicatorsComparisonResponse, error) {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	indicatorsDataList := make([]*model.IndicatorsData, 0)
 	pref := s.DB.Model(new(model.IndicatorsData)).
-		Where("pasture_id = ?", currentUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Where("date IN (?)", req.DateList)
 	if req.CategoryKind > 0 {
 		pref.Where("category_type = ?", req.CategoryKind)

+ 4 - 3
module/backend/interface.go

@@ -70,8 +70,6 @@ type SystemService interface {
 	// GetSystemUserMenu 当前登录用户菜单权限
 	GetSystemUserMenu(ctx context.Context) (*pasturePb.SystemUserMenuTreeResponse, error)
 
-	GetCurrentUserName(ctx context.Context) (string, error)
-
 	// SearchSystemRoleList 系统角色相关
 	SearchSystemRoleList(ctx context.Context, req *pasturePb.SearchRoleRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchRoleResponse, error)
 	DeleteSystemRole(ctx context.Context, roleId int64) error
@@ -91,6 +89,9 @@ type SystemService interface {
 	SearchSystemDeptList(ctx context.Context, req *pasturePb.SearchDeptRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchDeptResponse, error)
 	SystemDepDelete(ctx context.Context, id int64) error
 	SystemDeptCreateOrUpdate(ctx context.Context, req *pasturePb.SearchDeptRequest) error
+
+	// SearchUserPastureList 用户相关牧场列表
+	SearchUserPastureList(ctx context.Context) (*pasturePb.SystemUserPastureListResponse, error)
 }
 
 //go:generate mockgen -destination mock/PastureManageService.go -package kptservicemock kpt-pasture/module/backend PastureManageService
@@ -204,7 +205,7 @@ type EventService interface {
 	// CowEarNumberUpdate 修改耳号
 	CowEarNumberUpdate(ctx context.Context, req *pasturePb.EventReplaceEarNumber) error
 	// SubmitEventLog 记录提交事件结果日志
-	SubmitEventLog(ctx context.Context, currentUser *model.SystemUser, cow *model.Cow, eventType pasturePb.EventType_Kind, exposeEstrusType pasturePb.ExposeEstrusType_Kind, req interface{}) *model.EventCowLog
+	SubmitEventLog(ctx context.Context, pastureId int64, 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

+ 3 - 3
module/backend/pasture.go

@@ -45,9 +45,9 @@ func (s *StoreEntry) SearchBarnList(ctx context.Context, req *pasturePb.SearchNa
 }
 
 func (s *StoreEntry) CreateOrUpdateBarn(ctx context.Context, req *pasturePb.SearchBarnList) error {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
 	if req.Id > 0 {
@@ -70,7 +70,7 @@ func (s *StoreEntry) CreateOrUpdateBarn(ctx context.Context, req *pasturePb.Sear
 		"doctrinal_capacity": req.DoctrinalCapacity,
 		"bed_number":         req.BedNumber,
 		"neck_number":        req.NeckNumber,
-		"pasture_id":         currentUser.PastureId,
+		"pasture_id":         userModel.AppPasture.Id,
 		"is_delete":          pasturePb.IsShow_Ok,
 		"is_show":            pasturePb.IsShow_Ok,
 	}).FirstOrCreate(&model.Pen{}).Error; err != nil {

+ 58 - 47
module/backend/prescription.go

@@ -18,19 +18,25 @@ import (
 )
 
 func (s *StoreEntry) CreateOrUpdateSameTime(ctx context.Context, req *pasturePb.SearchSameTimeList) error {
-	currentUser, _ := s.GetCurrentSystemUser(ctx)
-	semeTime := model.NewSameTime(currentUser, req)
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return xerr.WithStack(err)
+	}
+	semeTime := model.NewSameTime(userModel.AppPasture.Id, userModel.SystemUser, req)
 	if req.Id > 0 {
-		if err := s.DB.Model(new(model.SameTime)).Where("id = ?", req.Id).Updates(map[string]interface{}{
-			"name":                  semeTime.Name,
-			"week_type":             semeTime.WeekType,
-			"cow_type":              semeTime.CowType,
-			"postpartum_days_start": semeTime.PostpartumDaysStart,
-			"postpartum_days_end":   semeTime.PostpartumDaysEnd,
-			"collate_nodes":         semeTime.CollateNodes,
-			"is_show":               semeTime.IsShow,
-			"remarks":               semeTime.Remarks,
-		}).Error; err != nil {
+		if err = s.DB.Model(new(model.SameTime)).
+			Where("id = ?", req.Id).
+			Where("pasture_id = ?", userModel.AppPasture.Id).
+			Updates(map[string]interface{}{
+				"name":                  semeTime.Name,
+				"week_type":             semeTime.WeekType,
+				"cow_type":              semeTime.CowType,
+				"postpartum_days_start": semeTime.PostpartumDaysStart,
+				"postpartum_days_end":   semeTime.PostpartumDaysEnd,
+				"collate_nodes":         semeTime.CollateNodes,
+				"is_show":               semeTime.IsShow,
+				"remarks":               semeTime.Remarks,
+			}).Error; err != nil {
 			return xerr.WithStack(err)
 		}
 	} else {
@@ -123,25 +129,29 @@ func (s *StoreEntry) SearchDiseaseList(ctx context.Context, req *pasturePb.Searc
 }
 
 func (s *StoreEntry) CreateOrUpdateDisease(ctx context.Context, req *pasturePb.SearchDiseaseList) error {
-	currUser, _ := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return xerr.WithStack(err)
+	}
 
 	if req.Id > 0 {
 		barn := &model.Disease{Id: int64(req.Id)}
-		if err := s.DB.Model(&model.Disease{}).First(barn).Error; err != nil {
+		if err = s.DB.Model(&model.Disease{}).First(barn).Error; err != nil {
 			if !errors.Is(err, gorm.ErrRecordNotFound) {
 				return xerr.WithStack(err)
 			}
 		}
 	}
-	if err := s.DB.Model(&model.Disease{}).Where(map[string]interface{}{
-		"id": req.Id,
+	if err = s.DB.Model(&model.Disease{}).Where(map[string]interface{}{
+		"id":         req.Id,
+		"pasture_id": userModel.AppPasture.Id,
 	}).Assign(map[string]interface{}{
 		"disease_type": req.DiseaseTypeId,
 		"name":         req.Name,
 		"symptoms":     strings.Join(req.Symptoms, "|"),
 		"remarks":      req.Remarks,
 		"is_show":      pasturePb.IsShow_Ok,
-		"operation_id": currUser.Id,
+		"operation_id": userModel.SystemUser.Id,
 	}).FirstOrCreate(&model.Disease{}).Error; err != nil {
 		return xerr.WithStack(err)
 	}
@@ -238,9 +248,9 @@ func (s *StoreEntry) SearchPrescriptionList(ctx context.Context, req *pasturePb.
 }
 
 func (s *StoreEntry) CreateOrUpdatePrescription(ctx context.Context, req *pasturePb.PrescriptionRequest) error {
-	currUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
 	var maxUseDays, maxMeatExpiredDays, maxMilkExpiredDays int32 = 0, 0, 0
@@ -255,7 +265,7 @@ func (s *StoreEntry) CreateOrUpdatePrescription(ctx context.Context, req *pastur
 			maxUseDays = v.UseDays
 		}
 
-		drugs, err := s.GetDrugsById(ctx, currUser.PastureId, int64(v.DrugsId))
+		drugs, err := s.GetDrugsById(ctx, userModel.AppPasture.Id, int64(v.DrugsId))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
@@ -277,7 +287,7 @@ func (s *StoreEntry) CreateOrUpdatePrescription(ctx context.Context, req *pastur
 		}
 		applicableDisease = strings.Join(applicableDiseaseIds, ",")
 	}
-	newPrescription := model.NewPrescription(currUser.PastureId, req, applicableDisease, maxUseDays, maxMeatExpiredDays, maxMilkExpiredDays, currUser)
+	newPrescription := model.NewPrescription(userModel.AppPasture.Id, req, applicableDisease, maxUseDays, maxMeatExpiredDays, maxMilkExpiredDays, userModel.SystemUser)
 	if req.Id > 0 {
 		prescription := &model.Prescription{Id: req.Id}
 		if err = s.DB.Model(&model.Prescription{}).First(prescription).Error; err != nil {
@@ -304,7 +314,7 @@ func (s *StoreEntry) CreateOrUpdatePrescription(ctx context.Context, req *pastur
 				return xerr.WithStack(err)
 			}
 			// 创建处方药品
-			newPrescriptionDrugs := model.NewPrescriptionDrugs(currUser.PastureId, req.Id, req.DrugsList)
+			newPrescriptionDrugs := model.NewPrescriptionDrugs(userModel.AppPasture.Id, req.Id, req.DrugsList)
 			if err = tx.Create(&newPrescriptionDrugs).Error; err != nil {
 				return xerr.WithStack(err)
 			}
@@ -323,7 +333,7 @@ func (s *StoreEntry) CreateOrUpdatePrescription(ctx context.Context, req *pastur
 			return xerr.WithStack(err)
 		}
 		// 创建处方药品
-		newPrescriptionDrugs := model.NewPrescriptionDrugs(currUser.PastureId, newPrescription.Id, req.DrugsList)
+		newPrescriptionDrugs := model.NewPrescriptionDrugs(userModel.AppPasture.Id, newPrescription.Id, req.DrugsList)
 		if err = tx.Create(&newPrescriptionDrugs).Error; err != nil {
 			return xerr.WithStack(err)
 		}
@@ -335,17 +345,17 @@ func (s *StoreEntry) CreateOrUpdatePrescription(ctx context.Context, req *pastur
 }
 
 func (s *StoreEntry) PrescriptionDetail(ctx context.Context, id int64) (*pasturePb.PrescriptionDetailResponse, error) {
-	currUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
-	prescriptionData, err := s.GetPrescriptionById(ctx, currUser.PastureId, int32(id))
+	prescriptionData, err := s.GetPrescriptionById(ctx, userModel.AppPasture.Id, int32(id))
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
 
-	prescriptionDrugsList, err := s.PrescriptionDrugsByPrescriptionId(ctx, currUser.PastureId, int32(id))
+	prescriptionDrugsList, err := s.PrescriptionDrugsByPrescriptionId(ctx, userModel.AppPasture.Id, int32(id))
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -365,15 +375,15 @@ 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)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	immunizationList := make([]*model.ImmunizationPlan, 0)
 	var count int64 = 0
 	pref := s.DB.Model(new(model.ImmunizationPlan)).
-		Where("pasture_id = ?", currUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Where("is_show = ?", pasturePb.IsShow_Ok)
 	if req.Name != "" {
 		pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
@@ -405,9 +415,9 @@ func (s *StoreEntry) CreatedOrUpdateImmunization(ctx context.Context, req *pastu
 		systemUser   *model.SystemUser
 	)
 
-	currUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
 	if req.Conditions == pasturePb.ImmunizationConditions_Other_Vaccine_After && req.ImmunizationPlanId <= 0 {
@@ -415,7 +425,7 @@ func (s *StoreEntry) CreatedOrUpdateImmunization(ctx context.Context, req *pastu
 	}
 
 	if req.ImmunizationPlanId > 0 {
-		otherImmunization, err := s.GetImmunizationById(ctx, currUser.PastureId, int64(req.ImmunizationPlanId))
+		otherImmunization, err := s.GetImmunizationById(ctx, userModel.AppPasture.Id, int64(req.ImmunizationPlanId))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
@@ -423,18 +433,19 @@ func (s *StoreEntry) CreatedOrUpdateImmunization(ctx context.Context, req *pastu
 	}
 
 	if req.Id > 0 {
-		immunization, err = s.GetImmunizationById(ctx, currUser.PastureId, int64(req.Id))
+		immunization, err = s.GetImmunizationById(ctx, userModel.AppPasture.Id, int64(req.Id))
 		if err != nil {
 			return xerr.WithStack(err)
 		}
-		systemUser, _ = s.GetSystemUserById(ctx, currUser.PastureId, immunization.OperationId)
+		systemUser, _ = s.GetSystemUserById(ctx, immunization.OperationId)
 	} else {
 		systemUser, _ = s.GetCurrentSystemUser(ctx)
 	}
 
-	immunization = model.NewImmunizationPlan(systemUser, req)
+	immunization = model.NewImmunizationPlan(userModel.AppPasture.Id, systemUser, req)
 	if err = s.DB.Model(&model.ImmunizationPlan{}).Where(map[string]interface{}{
-		"id": req.Id,
+		"id":         req.Id,
+		"pasture_id": userModel.AppPasture.Id,
 	}).Assign(map[string]interface{}{
 		"name":                   immunization.Name,
 		"cow_type":               immunization.CowType,
@@ -453,9 +464,9 @@ func (s *StoreEntry) CreatedOrUpdateImmunization(ctx context.Context, req *pastu
 }
 
 func (s *StoreEntry) ImmunizationIsShow(ctx context.Context, id int64) error {
-	currUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
 	immunizationPlan := &model.ImmunizationPlan{
@@ -463,7 +474,7 @@ func (s *StoreEntry) ImmunizationIsShow(ctx context.Context, id int64) error {
 	}
 	if err = s.DB.Model(new(model.ImmunizationPlan)).
 		Where("id = ?", id).
-		Where("pasture_id = ?", currUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		First(immunizationPlan).Error; err != nil {
 		if errors.Is(err, gorm.ErrRecordNotFound) {
 			return xerr.Custom("该免疫计划不存在")
@@ -482,14 +493,14 @@ func (s *StoreEntry) ImmunizationIsShow(ctx context.Context, id int64) error {
 }
 
 func (s *StoreEntry) SystemBasicList(ctx context.Context) (*pasturePb.SearchBaseDataConfigResponse, error) {
-	currUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return nil, xerr.Custom("当前用户信息错误,请退出重新登录")
+		return nil, xerr.WithStack(err)
 	}
 
 	systemBasicList := make([]*model.SystemBasic, 0)
 	if err = s.DB.Model(new(model.SystemBasic)).
-		Where("pasture_id = ?", currUser.PastureId).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
 		Where("is_show = ?", pasturePb.IsShow_Ok).Find(&systemBasicList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -504,22 +515,22 @@ func (s *StoreEntry) SystemBasicList(ctx context.Context) (*pasturePb.SearchBase
 }
 
 func (s *StoreEntry) SystemBasicEdit(ctx context.Context, req *pasturePb.BaseDataConfigBatch) error {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		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).
+			Where("pasture_id = ?", userModel.AppPasture.Id).
 			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)
+		systemBasic.EditUpdate(userModel.AppPasture.Id, v.MinValue, v.MaxValue, v.WeekValue, userModel.SystemUser)
 		if err = s.DB.Model(systemBasic).
 			Select("min_value", "max_value", "week_value", "operation_id", "operation_name").
 			Updates(systemBasic).Error; err != nil {

+ 59 - 14
module/backend/sql.go

@@ -7,6 +7,9 @@ import (
 	"kpt-pasture/model"
 	"kpt-pasture/store/kptstore"
 
+	"gitee.com/xuyiping_admin/pkg/logger/zaplog"
+	"go.uber.org/zap"
+
 	operationPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/operation"
 
 	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
@@ -14,18 +17,19 @@ import (
 	"gorm.io/gorm"
 )
 
-// GetCurrentUserName 获取当前用户名
-func (s *StoreEntry) GetCurrentUserName(ctx context.Context) (string, error) {
-	userNameInter := ctx.Value(CurrentUserName)
-	if userNameInter == nil {
-		return "", xerr.Customf("cannot userName")
+func (s *StoreEntry) GetUserModel(ctx context.Context) (*model.UserModel, error) {
+	systemUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.WithStack(err)
 	}
-
-	if userName, ok := userNameInter.(string); ok {
-		return userName, nil
-	} else {
-		return "", xerr.Customf("waring userName")
+	appPasture, err := s.GetCurrentFarmInfo(ctx)
+	if err != nil {
+		return nil, xerr.WithStack(err)
 	}
+	return &model.UserModel{
+		SystemUser: systemUser,
+		AppPasture: appPasture,
+	}, nil
 }
 
 func (s *StoreEntry) GetCurrentSystemUser(ctx context.Context) (*model.SystemUser, error) {
@@ -43,12 +47,53 @@ func (s *StoreEntry) GetCurrentSystemUser(ctx context.Context) (*model.SystemUse
 		if errors.Is(err, gorm.ErrRecordNotFound) {
 			return nil, xerr.Custom("当前登录用户数据不存在")
 		}
-		return nil, xerr.WithStack(err)
+		zaplog.Error("GetCurrentSystemUser", zap.Any("err", err), zap.Any("userName", userName))
+		return nil, xerr.Custom("用户登录信息有误,请退出重新登录")
 	}
 	return systemUser, nil
 }
 
-func (s *StoreEntry) GetSystemUserById(ctx context.Context, pastureId, userId int64) (*model.SystemUser, error) {
+func (s *StoreEntry) GetCurrentFarmInfo(ctx context.Context) (*model.AppPastureList, error) {
+	farmId := s.GetFarmId(ctx)
+	if farmId == "" {
+		return nil, xerr.Custom("请选择牧场信息")
+	}
+
+	appPasture, err := s.FindPastureByFarmId(ctx, farmId)
+	if err != nil {
+		return nil, xerr.WithStack(err)
+	}
+	return appPasture, nil
+}
+
+// GetCurrentUserName 获取当前用户名
+func (s *StoreEntry) GetCurrentUserName(ctx context.Context) (string, error) {
+	userNameInter := ctx.Value(CurrentUserName)
+	if userNameInter == nil {
+		return "", xerr.Customf("cannot userName")
+	}
+
+	if userName, ok := userNameInter.(string); ok {
+		return userName, nil
+	} else {
+		return "", xerr.Customf("waring userName")
+	}
+}
+
+// GetFarmId 获取当前牧场Id
+func (s *StoreEntry) GetFarmId(ctx context.Context) string {
+	farmId := ctx.Value(CurrentFarmId)
+	if farmId == nil {
+		return ""
+	}
+
+	if farmIdStr, ok := farmId.(string); ok {
+		return farmIdStr
+	}
+	return ""
+}
+
+func (s *StoreEntry) GetSystemUserById(ctx context.Context, 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) {
@@ -321,9 +366,9 @@ func (s *StoreEntry) FindEventEstrusByCowId(ctx context.Context, pastureId, cowI
 	return newEventEstrus, true, nil
 }
 
-func (s *StoreEntry) GetOutboundById(ctx context.Context, id int64) (*model.Outbound, error) {
+func (s *StoreEntry) GetOutboundById(ctx context.Context, pastureId, id int64) (*model.Outbound, error) {
 	res := &model.Outbound{}
-	if err := s.DB.Model(new(model.Outbound)).
+	if err := s.DB.Model(new(model.Outbound)).Where("pasture_id = ?", pastureId).
 		Where("id = ?", id).First(res).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}

+ 28 - 19
module/backend/system_service.go

@@ -19,7 +19,10 @@ import (
 	"gorm.io/gorm"
 )
 
-const CurrentUserName = "userName"
+const (
+	CurrentUserName = "userName"
+	CurrentFarmId   = "FarmId"
+)
 
 // Login 用户登录
 func (s *StoreEntry) Login(ctx context.Context, req *pasturePb.SearchUserRequest) (*pasturePb.SystemUserResponse, error) {
@@ -57,9 +60,9 @@ func (s *StoreEntry) Login(ctx context.Context, req *pasturePb.SearchUserRequest
 	}
 
 	expires := time.Now().Add(time.Duration(s.Cfg.JwtExpireTime) * time.Second).Format(util.LayoutTime)
-	farmData := s.FindPastureByFarmId(ctx, systemUser.PastureId)
-	if farmData == nil || farmData.FarmId == "" {
-		return nil, xerr.Custom("获取牧场信息错误")
+	farmList, err := s.FindPastureList(ctx, systemUser.PastureIds)
+	if err != nil || len(farmList) == 0 {
+		return nil, xerr.Custom("牧场信息错误")
 	}
 
 	return &pasturePb.SystemUserResponse{
@@ -72,7 +75,7 @@ func (s *StoreEntry) Login(ctx context.Context, req *pasturePb.SearchUserRequest
 			Username:     systemUser.Name,
 			Roles:        []string{systemRole.Name},
 			Avatar:       systemUser.Avatar,
-			FarmId:       farmData.FarmId,
+			FarmId:       farmList[0].FarmId,
 		},
 	}, nil
 }
@@ -271,20 +274,10 @@ func (s *StoreEntry) SystemUserRoleSave(ctx context.Context, req *pasturePb.Syst
 
 // GetSystemUserMenu 返回系统用户相关菜单权限
 func (s *StoreEntry) GetSystemUserMenu(ctx context.Context) (*pasturePb.SystemUserMenuTreeResponse, error) {
-	// 解析token
-	userName, err := s.GetCurrentUserName(ctx)
-	if err != nil {
-		return nil, xerr.WithStack(err)
-	}
 	// 根据用户token获取用户数据
-	systemUser := &model.SystemUser{Name: userName}
-	if err = s.DB.Where("name = ?", userName).
-		Where("is_show = ? and is_delete = ?", pasturePb.IsShow_Ok, pasturePb.IsShow_Ok).
-		First(systemUser).Error; err != nil {
-		if errors.Is(err, gorm.ErrRecordNotFound) {
-			return nil, xerr.Custom("该用户数据不存在")
-		}
-		return nil, xerr.WithStack(err)
+	systemUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.Custom("该用户数据不存在")
 	}
 	if systemUser.RoleId <= 0 {
 		return nil, xerr.Custom("该用户没有角色")
@@ -658,4 +651,20 @@ func (s *StoreEntry) SystemDeptCreateOrUpdate(ctx context.Context, req *pastureP
 	return nil
 }
 
-// SearchSystemDeptListByIds 根据id查询部门列表
+func (s *StoreEntry) SearchUserPastureList(ctx context.Context) (*pasturePb.SystemUserPastureListResponse, error) {
+	currentUser, err := s.GetCurrentSystemUser(ctx)
+	if err != nil {
+		return nil, xerr.WithStack(err)
+	}
+
+	farmList, err := s.FindPastureList(ctx, currentUser.PastureIds)
+	if err != nil {
+		return nil, xerr.WithStack(err)
+	}
+
+	return &pasturePb.SystemUserPastureListResponse{
+		Code: http.StatusOK,
+		Msg:  "ok",
+		Data: model.AppPastureListSlice(farmList).ToPB(),
+	}, err
+}

+ 8 - 8
module/backend/test_service.go

@@ -13,9 +13,9 @@ import (
 )
 
 func (s *StoreEntry) CowNeckRingNumberBound(ctx context.Context, pagination *pasturePb.PaginationModel) error {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
 	lastNeckRing := &model.NeckRing{}
@@ -37,9 +37,9 @@ func (s *StoreEntry) CowNeckRingNumberBound(ctx context.Context, pagination *pas
 	newNeckRingList := make([]*model.NeckRing, 0)
 	newNeckRingBindLogList := make([]*model.NeckRingBindLog, 0)
 	for _, v := range cowList {
-		newNeckRing := model.NewNeckRing(currentUser.PastureId, v.NeckRingNumber, v.Id, currentUser)
+		newNeckRing := model.NewNeckRing(userModel.AppPasture.Id, v.NeckRingNumber, v.Id, userModel.SystemUser)
 		newNeckRingList = append(newNeckRingList, newNeckRing)
-		newNeckRingBindLog := model.NewNeckRingBindLog(v.NeckRingNumber, v.Id, currentUser)
+		newNeckRingBindLog := model.NewNeckRingBindLog(userModel.AppPasture.Id, v.NeckRingNumber, v.Id, userModel.SystemUser)
 		newNeckRingBindLogList = append(newNeckRingBindLogList, newNeckRingBindLog)
 	}
 
@@ -56,9 +56,9 @@ func (s *StoreEntry) CowNeckRingNumberBound(ctx context.Context, pagination *pas
 }
 
 func (s *StoreEntry) CowNeckRingNumberBound2(ctx context.Context, pagination *pasturePb.PaginationModel) error {
-	currentUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
-		return xerr.Custom("当前用户信息错误,请退出重新登录")
+		return xerr.WithStack(err)
 	}
 
 	lastNeckRing := &model.NeckRing{}
@@ -80,9 +80,9 @@ func (s *StoreEntry) CowNeckRingNumberBound2(ctx context.Context, pagination *pa
 	newNeckRingList := make([]*model.NeckRing, 0)
 	newNeckRingBindLogList := make([]*model.NeckRingBindLog, 0)
 	for _, v := range cowList {
-		newNeckRing := model.NewNeckRing(currentUser.PastureId, v.NeckRingNumber, v.Id, currentUser)
+		newNeckRing := model.NewNeckRing(userModel.AppPasture.Id, v.NeckRingNumber, v.Id, userModel.SystemUser)
 		newNeckRingList = append(newNeckRingList, newNeckRing)
-		newNeckRingBindLog := model.NewNeckRingBindLog(v.NeckRingNumber, v.Id, currentUser)
+		newNeckRingBindLog := model.NewNeckRingBindLog(userModel.AppPasture.Id, v.NeckRingNumber, v.Id, userModel.SystemUser)
 		newNeckRingBindLogList = append(newNeckRingBindLogList, newNeckRingBindLog)
 	}
 

+ 10 - 7
module/backend/work.go

@@ -72,10 +72,13 @@ func (s *StoreEntry) OrderList(ctx context.Context, req *pasturePb.SearchWorkOrd
 // 周期性工单【包括每天,每周,每月】一次性生成符合本月日期所有工单
 // 更新工单的时候需要重新维护子工单
 func (s *StoreEntry) OrderCreateOrUpdate(ctx context.Context, req *pasturePb.WorkOrderList) error {
-	currentUser, _ := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
+	if err != nil {
+		return xerr.WithStack(err)
+	}
 	workOrderCategoryMap := s.WorkOrderCategoryMap()
 	systemUserList, _ := s.SystemUserList(ctx)
-	newWorkOrderMaster := model.NewWorkOrderMaster(req, currentUser, systemUserList, workOrderCategoryMap)
+	newWorkOrderMaster := model.NewWorkOrderMaster(userModel.AppPasture.Id, req, userModel.SystemUser, systemUserList, workOrderCategoryMap)
 	if req.Id <= 0 {
 		if err := s.DB.Transaction(func(tx *gorm.DB) error {
 			if err := tx.Create(newWorkOrderMaster).Error; err != nil {
@@ -239,7 +242,7 @@ func (s *StoreEntry) SendAsynqWorkOrder(ctx context.Context, workOrder *model.Wo
 
 // UserWorkOrderList 用户工单列表
 func (s *StoreEntry) UserWorkOrderList(ctx context.Context, workOrderStatus pasturePb.WorkOrderStatus_Kind, pagination *pasturePb.PaginationModel) (*pasturePb.UserWorkOrderResponse, error) {
-	currUser, err := s.GetCurrentSystemUser(ctx)
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -253,9 +256,9 @@ func (s *StoreEntry) UserWorkOrderList(ctx context.Context, workOrderStatus past
 		pref.Where("status = ?", workOrderStatus)
 	}
 
-	if err := pref.Where(
-		s.DB.Where("exec_user_id = ?", currUser.Id).
-			Or("FIND_IN_SET(?, set_user_ids) > 0", currUser.Id),
+	if err = pref.Where(
+		s.DB.Where("exec_user_id = ?", userModel.SystemUser.Id).
+			Or("FIND_IN_SET(?, set_user_ids) > 0", userModel.SystemUser.Id),
 	).
 		Order("id desc").
 		Count(&count).
@@ -267,7 +270,7 @@ func (s *StoreEntry) UserWorkOrderList(ctx context.Context, workOrderStatus past
 
 	mMap := make(map[int64]*model.WorkOrderMaster)
 	workOderMasterList := make([]*model.WorkOrderMaster, 0)
-	if err := s.DB.Model(&model.WorkOrderMaster{}).Find(&workOderMasterList).Error; err != nil {
+	if err = s.DB.Model(&model.WorkOrderMaster{}).Find(&workOderMasterList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}