2 Commits c446c5d975 ... ea657d4190

Auteur SHA1 Bericht Datum
  Yi ea657d4190 system: userDepth update 2 maanden geleden
  Yi c446c5d975 system: userDepth update 2 maanden geleden

+ 1 - 1
go.mod

@@ -3,7 +3,7 @@ module kpt-pasture
 go 1.17
 
 require (
-	gitee.com/xuyiping_admin/go_proto v0.0.0-20250530051007-6ce1b83221af
+	gitee.com/xuyiping_admin/go_proto v0.0.0-20250530090709-1e32a1ade71d
 	gitee.com/xuyiping_admin/pkg v0.0.0-20250514071642-f92d2ac9a85d
 	github.com/dgrijalva/jwt-go v3.2.0+incompatible
 	github.com/eclipse/paho.mqtt.golang v1.4.3

+ 2 - 0
go.sum

@@ -131,6 +131,8 @@ gitee.com/xuyiping_admin/go_proto v0.0.0-20250530040106-85ff23fe88f6 h1:UjId/C6d
 gitee.com/xuyiping_admin/go_proto v0.0.0-20250530040106-85ff23fe88f6/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
 gitee.com/xuyiping_admin/go_proto v0.0.0-20250530051007-6ce1b83221af h1:3SBlTKUWyBz4l86klizGDt/xda/7j9PGsRiUyZb+yX8=
 gitee.com/xuyiping_admin/go_proto v0.0.0-20250530051007-6ce1b83221af/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20250530090709-1e32a1ade71d h1:upETgWdn+raGyxXdP1S70Z4gMuGZep9RjcLsWLIWeF0=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20250530090709-1e32a1ade71d/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=
 gitee.com/xuyiping_admin/pkg v0.0.0-20250514071642-f92d2ac9a85d h1:vBXmMRggF7mZVPGRDgavZ87igJgkezwX0a3v1/XtIMQ=

+ 3 - 4
http/handler/config/config.go

@@ -117,13 +117,12 @@ func CowTransferPenReasonOptions(c *gin.Context) {
 }
 
 func SystemUserOptions(c *gin.Context) {
-	depIdStr := c.Query("dept_id")
-	depId, _ := strconv.Atoi(depIdStr)
-	if err := valid.Validate(depId, valid.Required, valid.Min(-1)); err != nil {
+	depName := c.Query("dept_name")
+	if err := valid.Validate(depName, valid.Required); err != nil {
 		apierr.ClassifiedAbort(c, err)
 		return
 	}
-	res, err := middleware.Dependency(c).StoreEventHub.OpsService.SystemUserOptions(c, depId)
+	res, err := middleware.Dependency(c).StoreEventHub.OpsService.SystemUserOptions(c, depName)
 	if err != nil {
 		apierr.ClassifiedAbort(c, err)
 		return

+ 37 - 1
model/system_dept.go

@@ -6,6 +6,11 @@ import (
 	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 )
 
+const (
+	BreedDepthName = "繁育部"
+	VetDepthName   = "兽医部"
+)
+
 type SystemDept struct {
 	Id        int64                 `json:"id"`
 	PastureId int64                 `json:"pastureId"`
@@ -17,6 +22,7 @@ type SystemDept struct {
 	Sort      int32                 `json:"sort"`
 	IsShow    pasturePb.IsShow_Kind `json:"isShow"`
 	IsDelete  pasturePb.IsShow_Kind `json:"isDelete"`
+	IsInit    pasturePb.IsShow_Kind `json:"isInit"`
 	CreatedAt int64                 `json:"createdAt"`
 	UpdatedAt int64                 `json:"updatedAt"`
 }
@@ -44,10 +50,11 @@ func NewSystemDept(pastureId int64, req *pasturePb.SearchDeptRequest) *SystemDep
 		ParentId:  int64(req.ParentId),
 		IsShow:    pasturePb.IsShow_Ok,
 		IsDelete:  pasturePb.IsShow_Ok,
+		IsInit:    pasturePb.IsShow_No,
 	}
 }
 
-func NewSystemDeptInit(pasture *AppPastureList) *SystemDept {
+func NewSystemPastureDeptInit(pasture *AppPastureList) *SystemDept {
 	return &SystemDept{
 		PastureId: pasture.Id,
 		Name:      pasture.Name,
@@ -58,9 +65,38 @@ func NewSystemDeptInit(pasture *AppPastureList) *SystemDept {
 		Sort:      0,
 		IsShow:    pasturePb.IsShow_Ok,
 		IsDelete:  pasturePb.IsShow_Ok,
+		IsInit:    pasturePb.IsShow_Ok,
 	}
 }
 
+func NewSystemDeptInit(pastureId, parentId int64) []*SystemDept {
+	res := make([]*SystemDept, 0)
+	res = append(res, &SystemDept{
+		PastureId: pastureId,
+		Name:      BreedDepthName,
+		Remarks:   BreedDepthName,
+		DeptType:  pasturePb.Depth_Department,
+		LeaderId:  0,
+		ParentId:  parentId,
+		Sort:      1,
+		IsShow:    pasturePb.IsShow_Ok,
+		IsDelete:  pasturePb.IsShow_Ok,
+		IsInit:    pasturePb.IsShow_Ok,
+	}, &SystemDept{
+		PastureId: pastureId,
+		Name:      VetDepthName,
+		Remarks:   VetDepthName,
+		DeptType:  pasturePb.Depth_Department,
+		LeaderId:  0,
+		ParentId:  parentId,
+		Sort:      2,
+		IsShow:    pasturePb.IsShow_Ok,
+		IsDelete:  pasturePb.IsShow_Ok,
+		IsInit:    pasturePb.IsShow_Ok,
+	})
+	return res
+}
+
 type SystemDeptSlice []*SystemDept
 
 func (s SystemDeptSlice) ToPB(systemUserList []*SystemUser) []*pasturePb.SearchDeptRequest {

+ 67 - 46
model/system_user.go

@@ -1,6 +1,7 @@
 package model
 
 import (
+	"encoding/json"
 	"fmt"
 	"strconv"
 	"strings"
@@ -24,6 +25,7 @@ type SystemUser struct {
 	IsShow          pasturePb.IsShow_Kind  `json:"isShow"`
 	IsDelete        pasturePb.IsShow_Kind  `json:"isDelete"`
 	Remarks         string                 `json:"remarks"`
+	Spare           string                 `json:"spare"`
 	CreatedAt       int64                  `json:"created_at"`
 	UpdatedAt       int64                  `json:"updated_at"`
 }
@@ -43,14 +45,19 @@ func (s *SystemUser) UserUpdate(req *pasturePb.SearchUserRequest, deptIds, pastu
 	s.PastureIds = pastureIds
 }
 
-func NewSystemUser(req *pasturePb.SearchUserRequest, deptIds, pastureIds string) *SystemUser {
+func NewSystemUser(req *pasturePb.SearchUserRequest, deptIds, pastureIds string, pastureDepthList []*pasturePb.PastureDepthDetail) *SystemUser {
+	spare := ""
+	if len(pastureDepthList) > 0 {
+		bt, _ := json.Marshal(pastureDepthList)
+		spare = string(bt)
+	}
 	return &SystemUser{
 		Name:            req.Name,
 		NickName:        req.NickName,
 		Gender:          req.Gender,
 		Mobile:          req.Mobile,
 		Password:        req.Password,
-		Avatar:          "",
+		Avatar:          "https://avatars.githubusercontent.com/u/9510375",
 		RoleIds:         "",
 		DeptIds:         deptIds,
 		IndicatorsKinds: fmt.Sprintf("%s,%s,%s,%s,%s,%s", AllCow, OutNumber, InputNumber, SalesVolume, FattenCattleNumber, AdultCow),
@@ -58,16 +65,17 @@ func NewSystemUser(req *pasturePb.SearchUserRequest, deptIds, pastureIds string)
 		IsShow:          pasturePb.IsShow_Ok,
 		IsDelete:        pasturePb.IsShow_Ok,
 		Remarks:         req.Remarks,
+		Spare:           spare,
 	}
 }
 
-func (s *SystemUser) GetPastureIds() []int64 {
-	res := make([]int64, 0)
+func (s *SystemUser) GetPastureIds() []int32 {
+	res := make([]int32, 0)
 	if s.PastureIds != "" {
 		pastureIds := strings.Split(s.PastureIds, ",")
 		for _, idStr := range pastureIds {
 			id, _ := strconv.Atoi(idStr)
-			res = append(res, int64(id))
+			res = append(res, int32(id))
 		}
 	}
 	return res
@@ -85,13 +93,13 @@ func (s *SystemUser) GetRoleIds() []int32 {
 	return res
 }
 
-func (s *SystemUser) GetDepthIds() []int64 {
-	res := make([]int64, 0)
+func (s *SystemUser) GetDepthIds() []int32 {
+	res := make([]int32, 0)
 	if s.DeptIds != "" {
 		depthIds := strings.Split(s.DeptIds, ",")
 		for _, idStr := range depthIds {
 			id, _ := strconv.Atoi(idStr)
-			res = append(res, int64(id))
+			res = append(res, int32(id))
 		}
 	}
 	return res
@@ -104,58 +112,71 @@ type UserModel struct {
 
 type SystemUserSlice []*SystemUser
 
-func (s SystemUserSlice) ToPB(deptList []*SystemDept, roleList []*SystemRole) []*pasturePb.SearchUserRequest {
-	deptMap := make(map[string]*SystemDept)
+func (s SystemUserSlice) ToPB(deptList []*SystemDept, roleList []*SystemRole, appPastureList []*AppPastureList) []*pasturePb.SearchUserRequest {
+	deptMap := make(map[int32]*SystemDept)
 	for _, v := range deptList {
-		deptMap[fmt.Sprintf("%d", v.Id)] = v
+		deptMap[int32(v.Id)] = v
 	}
-	roleMap := make(map[string]*SystemRole)
+	roleMap := make(map[int32]*SystemRole)
 	for _, v := range roleList {
-		roleMap[fmt.Sprintf("%d", v.Id)] = v
+		roleMap[int32(v.Id)] = v
+	}
+
+	appPastureMap := make(map[int32]*AppPastureList)
+	for _, v := range appPastureList {
+		appPastureMap[int32(v.Id)] = v
 	}
 
 	res := make([]*pasturePb.SearchUserRequest, len(s))
 	for i, v := range s {
-		userDeptList := make([]*pasturePb.IdName, 0)
-		if v.DeptIds != "" {
-			deptIds := strings.Split(v.DeptIds, ",")
-			for _, d := range deptIds {
-				if de, ok := deptMap[d]; ok {
-					userDeptList = append(userDeptList, &pasturePb.IdName{
-						Id:   int32(de.Id),
-						Name: de.Name,
-					})
-				}
+		userDepthName := make([]string, 0)
+		deptIds := v.GetDepthIds()
+		for _, d := range deptIds {
+			if de, ok := deptMap[d]; ok {
+				userDepthName = append(userDepthName, de.Name)
+			}
+		}
+
+		userRoleName := make([]string, 0)
+		roleIds := v.GetRoleIds()
+		for _, r := range roleIds {
+			if ro, ok := roleMap[r]; ok {
+				userRoleName = append(userRoleName, ro.Name)
 			}
 		}
 
-		userRoleList := make([]*pasturePb.IdName, 0)
-		if v.RoleIds != "" {
-			roleIds := strings.Split(v.RoleIds, ",")
-			for _, r := range roleIds {
-				if ro, ok := roleMap[r]; ok {
-					userRoleList = append(userRoleList, &pasturePb.IdName{
-						Id:   int32(ro.Id),
-						Name: ro.Name,
-					})
-				}
+		pastureName := make([]string, 0)
+		for _, p := range v.GetPastureIds() {
+			if pa, ok := appPastureMap[p]; ok {
+				pastureName = append(pastureName, pa.Name)
 			}
 		}
 
+		pastureDepthList := make([]*pasturePb.PastureDepthDetail, 0)
+		if len(v.Spare) > 0 {
+			json.Unmarshal([]byte(v.Spare), &pastureDepthList)
+		}
+
 		res[i] = &pasturePb.SearchUserRequest{
-			Id:       int32(v.Id),
-			Name:     v.Name,
-			Mobile:   v.Mobile,
-			NickName: v.NickName,
-			Avatar:   v.Avatar,
-			Gender:   v.Gender,
-			IsShow:   v.IsShow,
-			IsDelete: v.IsDelete,
-			Remarks:  v.Remarks,
-			//PastureDepthList: userDeptList,
-			//RoleList:         userRoleList,
-			CreatedAtFormat: time.Unix(v.CreatedAt, 0).Local().Format(LayoutTime),
-			UpdatedAtFormat: time.Unix(v.UpdatedAt, 0).Local().Format(LayoutTime),
+			Id:               int32(v.Id),
+			Name:             v.Name,
+			NickName:         v.NickName,
+			Mobile:           v.Mobile,
+			Avatar:           v.Avatar,
+			Gender:           v.Gender,
+			IsShow:           v.IsShow,
+			IsDelete:         v.IsDelete,
+			Remarks:          v.Remarks,
+			PastureDepthList: pastureDepthList,
+			DepthId:          deptIds,
+			DeptName:         userDepthName,
+			RoleList:         nil,
+			RoleId:           v.GetRoleIds(),
+			RoleName:         userRoleName,
+			PastureId:        v.GetPastureIds(),
+			PastureName:      pastureName,
+			CreatedAtFormat:  time.Unix(v.CreatedAt, 0).Local().Format(LayoutTime),
+			UpdatedAtFormat:  time.Unix(v.UpdatedAt, 0).Local().Format(LayoutTime),
 		}
 	}
 	return res

+ 12 - 4
module/backend/app_pasture.go

@@ -3,7 +3,6 @@ package backend
 import (
 	"context"
 	"kpt-pasture/model"
-	"strings"
 
 	"gitee.com/xuyiping_admin/pkg/xerr"
 
@@ -21,11 +20,20 @@ func (s *StoreEntry) FindPastureByFarmId(ctx context.Context, farmId string) (*m
 	return res, nil
 }
 
-func (s *StoreEntry) FindPastureList(ctx context.Context, pastureIds string) ([]*model.AppPastureList, error) {
+func (s *StoreEntry) FindPastureListByIds(ctx context.Context, pastureIds []int32) ([]*model.AppPastureList, error) {
+	list := make([]*model.AppPastureList, 0)
+	if err := s.DB.Table(new(model.AppPastureList).TableName()).
+		Where("id IN (?)", pastureIds).
+		Where("is_show = ?", pasturePb.IsShow_Ok).
+		Find(&list).Error; err != nil {
+		return nil, xerr.WithStack(err)
+	}
+	return list, nil
+}
+
+func (s *StoreEntry) FindPastureList(ctx context.Context) ([]*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)

+ 23 - 11
module/backend/enum_options.go

@@ -146,26 +146,38 @@ func (s *StoreEntry) CowTransferPenReasonOptions(ctx context.Context) (*pastureP
 	}, nil
 }
 
-// SystemUserOptions 系统用户下拉框  todo 待优化
-func (s *StoreEntry) SystemUserOptions(ctx context.Context, depId int) (*pasturePb.ConfigOptionsListResponse, error) {
-	_, err := s.GetUserModel(ctx)
+// SystemUserOptions 系统用户下拉框
+func (s *StoreEntry) SystemUserOptions(ctx context.Context, depName string) (*pasturePb.ConfigOptionsListResponse, error) {
+	userModel, err := s.GetUserModel(ctx)
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
 
+	systemDepth := &model.SystemDept{}
+	if err = s.DB.Model(new(model.SystemDept)).
+		Where("name = ?", depName).
+		Where("pasture_id = ?", userModel.AppPasture.Id).
+		First(systemDepth).Error; err != nil {
+		return nil, xerr.WithStack(err)
+	}
+
+	if systemDepth.IsDelete == pasturePb.IsShow_No {
+		return nil, xerr.Custom("部门已经删除")
+	}
+
+	if systemDepth.IsShow == pasturePb.IsShow_No {
+		return nil, xerr.Custom("部门已经禁用")
+	}
+
 	systemUserList := make([]*model.SystemUser, 0)
-	pref := s.DB.Table(new(model.SystemUser).TableName()).
-		//Where("FIND_IN_SET('?',pasture_ids) > 0", userModel.AppPasture.Id).
+	if err = s.DB.Table(new(model.SystemUser).TableName()).
+		Where("FIND_IN_SET('?',dept_ids) > 0", systemDepth.Id).
 		Where("is_delete = ?", pasturePb.IsShow_Ok).
 		Where("is_show = ? ", pasturePb.IsShow_Ok).
-		Where("dept_ids = ? ", depId)
-	/*if depId != -1 && depId > 0 {
-		pref = pref.Where("FIND_IN_SET('?',dept_ids) > 0", depId)
-	}*/
-
-	if err = pref.Find(&systemUserList).Error; err != nil {
+		Find(&systemUserList).Error; err != nil {
 		return nil, xerr.WithStack(err)
 	}
+
 	return &pasturePb.ConfigOptionsListResponse{
 		Code: http.StatusOK,
 		Msg:  "ok",

+ 1 - 1
module/backend/interface.go

@@ -152,7 +152,7 @@ type ConfigDataService interface {
 	CowSourceOptions(ctx context.Context) (*pasturePb.ConfigOptionsListResponse, error)
 	CowTypeOptions(ctx context.Context, optionName, isAll string) (*pasturePb.ConfigOptionsListResponse, error)
 	CowTransferPenReasonOptions(ctx context.Context) (*pasturePb.ConfigOptionsListResponse, error)
-	SystemUserOptions(ctx context.Context, depId int) (*pasturePb.ConfigOptionsListResponse, error)
+	SystemUserOptions(ctx context.Context, depName string) (*pasturePb.ConfigOptionsListResponse, error)
 	BullOptions(ctx context.Context) (*pasturePb.BullOptionsListResponse, error)
 	SystemBaseConfigOptions(ctx context.Context, optionName, isAll string) (*pasturePb.ConfigOptionsListResponse, error)
 	DiseaseTypeOptions(ctx context.Context, isChildren string) (*pasturePb.ConfigOptionsListResponse, error)

+ 2 - 169
module/backend/sql.go

@@ -386,9 +386,10 @@ func (s *StoreEntry) GetEventCowSameTimeByCowId(ctx context.Context, pastureId,
 	return eventCowSameTime, nil
 }
 
-func (s *StoreEntry) SearchSystemDeptListByIds(ctx context.Context, ids []int64) ([]*model.SystemDept, error) {
+func (s *StoreEntry) SearchSystemDeptListByIds(ctx context.Context, pastureId int64, ids []int64) ([]*model.SystemDept, error) {
 	systemDeptList := make([]*model.SystemDept, 0)
 	if err := s.DB.Model(new(model.SystemDept)).
+		Where("pasture_id = ?", pastureId).
 		Where("is_show = ?", operationPb.IsShow_OK).
 		Find(&systemDeptList, ids).Error; err != nil {
 		return nil, xerr.WithStack(err)
@@ -414,171 +415,3 @@ func (s *StoreEntry) GetSystemBasicByName(ctx context.Context, pastureId int64,
 	}
 	return systemBasic, nil
 }
-
-// FindLastEventMatingByCowId 根据cowId获取最近一次配种表信息
-func (s *StoreEntry) FindLastEventMatingByCowId(ctx context.Context, pastureId, cowId int64) (*model.EventMating, error) {
-	newEventMating := &model.EventMating{}
-	if err := s.DB.Model(new(model.EventMating)).
-		Where("cow_id = ?", cowId).
-		Where("pasture_id = ?", pastureId).
-		Order("id desc").
-		First(newEventMating).Error; err != nil {
-		return nil, xerr.WithStack(err)
-	}
-	return newEventMating, nil
-}
-
-func (s *StoreEntry) FindEventEstrusByCowId(pastureId, cowId int64, startTime, endTime int64) bool {
-	var count int64
-	if err := s.DB.Model(new(model.EventEstrus)).
-		Where("cow_id = ?", cowId).
-		Where("pasture_id = ?", pastureId).
-		Where("reality_day BETWEEN ? AND ?", startTime, endTime).
-		Where("is_show = ? ", pasturePb.IsShow_Ok).
-		Count(&count).Error; err != nil {
-		return false
-	}
-	return count > 0
-}
-
-func (s *StoreEntry) FindEventMatingByCowId(pastureId, cowId int64) bool {
-	var count int64
-	if err := s.DB.Model(new(model.EventMating)).
-		Where("cow_id = ?", cowId).
-		Where("pasture_id = ?", pastureId).
-		Where("is_show = ? ", pasturePb.IsShow_Ok).
-		Count(&count).Error; err != nil {
-		return false
-	}
-	return count > 0
-}
-
-func (s *StoreEntry) GetOutboundById(ctx context.Context, pastureId, id int64) (*model.Outbound, error) {
-	res := &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)
-	}
-	return res, nil
-}
-
-func (s *StoreEntry) GetOutboundDetailByOutboundId(ctx context.Context, id int64) ([]*model.OutboundDetail, error) {
-	list := make([]*model.OutboundDetail, 0)
-	if err := s.DB.Model(new(model.OutboundDetail)).
-		Where("outbound_id = ?", id).
-		Where("is_delete = ?", pasturePb.IsShow_Ok).
-		Find(&list).Error; err != nil {
-		return nil, xerr.WithStack(err)
-	}
-	return list, nil
-}
-
-func (s *StoreEntry) FindEventPregnantCheckIsExIstByCowId(ctx context.Context, cow *model.Cow) (*model.EventPregnantCheck, error) {
-	newEventPregnantCheck := &model.EventPregnantCheck{}
-	if err := s.DB.Model(new(model.EventPregnantCheck)).
-		Where("cow_id = ?", cow.Id).
-		Where("lact = ?", cow.Lact).
-		Where("status = ?", pasturePb.IsShow_No).
-		Order("id desc").
-		First(newEventPregnantCheck).Error; err != nil {
-		if errors.Is(err, gorm.ErrRecordNotFound) {
-			return nil, xerr.Customf("该牛只: %d 孕检数据未找到", cow.Id)
-		} else {
-			return nil, xerr.WithStack(err)
-		}
-	}
-	return newEventPregnantCheck, nil
-}
-
-func (s *StoreEntry) DiseaseMaps(ctx context.Context) (map[int64]*model.Disease, error) {
-	res := make(map[int64]*model.Disease)
-	list := make([]*model.Disease, 0)
-	if err := s.DB.Model(new(model.Disease)).Where("is_show = ?", pasturePb.IsShow_Ok).Find(&list).Error; err != nil {
-		return nil, xerr.WithStack(err)
-	}
-	for _, v := range list {
-		res[v.Id] = v
-	}
-	return res, nil
-}
-
-// NeckRingIsExist 根据neckRingNumber判断该耳环是否存在
-func (s *StoreEntry) NeckRingIsExist(pastureId int64, number string) (*model.NeckRing, bool) {
-	neckRing := &model.NeckRing{}
-	if err := s.DB.Model(new(model.NeckRing)).
-		Where("neck_ring_number = ?", number).
-		Where("pasture_id = ?", pastureId).
-		First(neckRing).Error; err != nil {
-		if errors.Is(err, gorm.ErrRecordNotFound) {
-			return nil, false
-		} else {
-			return nil, false
-		}
-	}
-	return neckRing, true
-}
-
-func (s *StoreEntry) GetEventLogList(
-	cowId int64, lact int32,
-	eventCategoryId pasturePb.EventCategory_Kind,
-	paginationModel *pasturePb.PaginationModel,
-) ([]*model.EventCowLog, error) {
-	eventLogList := make([]*model.EventCowLog, 0)
-	newEventCowLog := &model.EventCowLog{CowId: cowId}
-	pref := s.DB.Table(newEventCowLog.TableName()).
-		Where("cow_id = ?", cowId)
-	if lact >= 0 {
-		pref.Where("lact = ?", lact)
-	}
-
-	if eventCategoryId > 0 {
-		pref.Where("event_category_id = ?", eventCategoryId)
-	}
-
-	if err := pref.Order("id desc").
-		Offset(int(paginationModel.PageOffset)).
-		Limit(int(paginationModel.PageSize)).
-		Find(&eventLogList).Error; err != nil {
-		return nil, xerr.WithStack(err)
-	}
-	return eventLogList, nil
-}
-
-func (s *StoreEntry) FindIndicatorsDetailsList(ctx context.Context) ([]*model.IndicatorsDetails, error) {
-	list := make([]*model.IndicatorsDetails, 0)
-	if err := s.DB.Model(new(model.IndicatorsDetails)).Find(&list).Error; err != nil {
-		return nil, xerr.WithStack(err)
-	}
-	return list, nil
-}
-
-func (s *StoreEntry) GetCowLastEvent(pastureId, cowId int64, eventCategoryId pasturePb.EventCategory_Kind) *model.EventCowLog {
-	newEventCowLog := &model.EventCowLog{CowId: cowId}
-	pref := s.DB.Table(newEventCowLog.TableName()).
-		Where("cow_id = ?", cowId).Where("pasture_id = ?", pastureId)
-	if eventCategoryId > 0 {
-		pref.Where("event_category_kind = ?", eventCategoryId)
-	}
-
-	if err := pref.Order("id desc").
-		First(newEventCowLog); err != nil {
-		return nil
-	}
-	return newEventCowLog
-}
-
-// IsExistCalvingCalf 根据cowId查询犊牛信息
-func (s *StoreEntry) IsExistCalvingCalf(pastureId, cowId int64) (*model.CalvingCalf, bool) {
-	calvingCalf := &model.CalvingCalf{}
-	if err := s.DB.Model(new(model.CalvingCalf)).
-		Where("cow_id = ?", cowId).
-		Where("pasture_id = ?", pastureId).
-		First(calvingCalf).Error; err != nil {
-		if errors.Is(err, gorm.ErrRecordNotFound) {
-			return nil, false
-		} else {
-			return nil, false
-		}
-	}
-	return calvingCalf, true
-}

+ 202 - 0
module/backend/sql_more.go

@@ -0,0 +1,202 @@
+package backend
+
+import (
+	"context"
+	"errors"
+	"kpt-pasture/model"
+
+	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
+	"gitee.com/xuyiping_admin/pkg/xerr"
+	"gorm.io/gorm"
+)
+
+// FindLastEventMatingByCowId 根据cowId获取最近一次配种表信息
+func (s *StoreEntry) FindLastEventMatingByCowId(ctx context.Context, pastureId, cowId int64) (*model.EventMating, error) {
+	newEventMating := &model.EventMating{}
+	if err := s.DB.Model(new(model.EventMating)).
+		Where("cow_id = ?", cowId).
+		Where("pasture_id = ?", pastureId).
+		Order("id desc").
+		First(newEventMating).Error; err != nil {
+		return nil, xerr.WithStack(err)
+	}
+	return newEventMating, nil
+}
+
+func (s *StoreEntry) FindEventEstrusByCowId(pastureId, cowId int64, startTime, endTime int64) bool {
+	var count int64
+	if err := s.DB.Model(new(model.EventEstrus)).
+		Where("cow_id = ?", cowId).
+		Where("pasture_id = ?", pastureId).
+		Where("reality_day BETWEEN ? AND ?", startTime, endTime).
+		Where("is_show = ? ", pasturePb.IsShow_Ok).
+		Count(&count).Error; err != nil {
+		return false
+	}
+	return count > 0
+}
+
+func (s *StoreEntry) FindEventMatingByCowId(pastureId, cowId int64) bool {
+	var count int64
+	if err := s.DB.Model(new(model.EventMating)).
+		Where("cow_id = ?", cowId).
+		Where("pasture_id = ?", pastureId).
+		Where("is_show = ? ", pasturePb.IsShow_Ok).
+		Count(&count).Error; err != nil {
+		return false
+	}
+	return count > 0
+}
+
+func (s *StoreEntry) GetOutboundById(ctx context.Context, pastureId, id int64) (*model.Outbound, error) {
+	res := &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)
+	}
+	return res, nil
+}
+
+func (s *StoreEntry) GetOutboundDetailByOutboundId(ctx context.Context, id int64) ([]*model.OutboundDetail, error) {
+	list := make([]*model.OutboundDetail, 0)
+	if err := s.DB.Model(new(model.OutboundDetail)).
+		Where("outbound_id = ?", id).
+		Where("is_delete = ?", pasturePb.IsShow_Ok).
+		Find(&list).Error; err != nil {
+		return nil, xerr.WithStack(err)
+	}
+	return list, nil
+}
+
+func (s *StoreEntry) FindEventPregnantCheckIsExIstByCowId(ctx context.Context, cow *model.Cow) (*model.EventPregnantCheck, error) {
+	newEventPregnantCheck := &model.EventPregnantCheck{}
+	if err := s.DB.Model(new(model.EventPregnantCheck)).
+		Where("cow_id = ?", cow.Id).
+		Where("lact = ?", cow.Lact).
+		Where("status = ?", pasturePb.IsShow_No).
+		Order("id desc").
+		First(newEventPregnantCheck).Error; err != nil {
+		if errors.Is(err, gorm.ErrRecordNotFound) {
+			return nil, xerr.Customf("该牛只: %d 孕检数据未找到", cow.Id)
+		} else {
+			return nil, xerr.WithStack(err)
+		}
+	}
+	return newEventPregnantCheck, nil
+}
+
+func (s *StoreEntry) DiseaseMaps(ctx context.Context) (map[int64]*model.Disease, error) {
+	res := make(map[int64]*model.Disease)
+	list := make([]*model.Disease, 0)
+	if err := s.DB.Model(new(model.Disease)).Where("is_show = ?", pasturePb.IsShow_Ok).Find(&list).Error; err != nil {
+		return nil, xerr.WithStack(err)
+	}
+	for _, v := range list {
+		res[v.Id] = v
+	}
+	return res, nil
+}
+
+// NeckRingIsExist 根据neckRingNumber判断该耳环是否存在
+func (s *StoreEntry) NeckRingIsExist(pastureId int64, number string) (*model.NeckRing, bool) {
+	neckRing := &model.NeckRing{}
+	if err := s.DB.Model(new(model.NeckRing)).
+		Where("neck_ring_number = ?", number).
+		Where("pasture_id = ?", pastureId).
+		First(neckRing).Error; err != nil {
+		if errors.Is(err, gorm.ErrRecordNotFound) {
+			return nil, false
+		} else {
+			return nil, false
+		}
+	}
+	return neckRing, true
+}
+
+func (s *StoreEntry) GetEventLogList(
+	cowId int64, lact int32,
+	eventCategoryId pasturePb.EventCategory_Kind,
+	paginationModel *pasturePb.PaginationModel,
+) ([]*model.EventCowLog, error) {
+	eventLogList := make([]*model.EventCowLog, 0)
+	newEventCowLog := &model.EventCowLog{CowId: cowId}
+	pref := s.DB.Table(newEventCowLog.TableName()).
+		Where("cow_id = ?", cowId)
+	if lact >= 0 {
+		pref.Where("lact = ?", lact)
+	}
+
+	if eventCategoryId > 0 {
+		pref.Where("event_category_id = ?", eventCategoryId)
+	}
+
+	if err := pref.Order("id desc").
+		Offset(int(paginationModel.PageOffset)).
+		Limit(int(paginationModel.PageSize)).
+		Find(&eventLogList).Error; err != nil {
+		return nil, xerr.WithStack(err)
+	}
+	return eventLogList, nil
+}
+
+func (s *StoreEntry) FindIndicatorsDetailsList(ctx context.Context) ([]*model.IndicatorsDetails, error) {
+	list := make([]*model.IndicatorsDetails, 0)
+	if err := s.DB.Model(new(model.IndicatorsDetails)).Find(&list).Error; err != nil {
+		return nil, xerr.WithStack(err)
+	}
+	return list, nil
+}
+
+func (s *StoreEntry) GetCowLastEvent(pastureId, cowId int64, eventCategoryId pasturePb.EventCategory_Kind) *model.EventCowLog {
+	newEventCowLog := &model.EventCowLog{CowId: cowId}
+	pref := s.DB.Table(newEventCowLog.TableName()).
+		Where("cow_id = ?", cowId).Where("pasture_id = ?", pastureId)
+	if eventCategoryId > 0 {
+		pref.Where("event_category_kind = ?", eventCategoryId)
+	}
+
+	if err := pref.Order("id desc").
+		First(newEventCowLog); err != nil {
+		return nil
+	}
+	return newEventCowLog
+}
+
+// IsExistCalvingCalf 根据cowId查询犊牛信息
+func (s *StoreEntry) IsExistCalvingCalf(pastureId, cowId int64) (*model.CalvingCalf, bool) {
+	calvingCalf := &model.CalvingCalf{}
+	if err := s.DB.Model(new(model.CalvingCalf)).
+		Where("cow_id = ?", cowId).
+		Where("pasture_id = ?", pastureId).
+		First(calvingCalf).Error; err != nil {
+		if errors.Is(err, gorm.ErrRecordNotFound) {
+			return nil, false
+		} else {
+			return nil, false
+		}
+	}
+	return calvingCalf, true
+}
+
+func (s *StoreEntry) GetAppPastureListByFarmId(ctx context.Context, farmId string) (*model.AppPastureList, error) {
+	res := &model.AppPastureList{}
+	if err := s.DB.Model(new(model.AppPastureList)).
+		Where("farm_id = ?", farmId).
+		First(res).Error; err != nil {
+		if errors.Is(err, gorm.ErrRecordNotFound) {
+			return nil, xerr.Custom("请选择牧场信息")
+		} else {
+			return nil, xerr.WithStack(err)
+		}
+	}
+
+	if res.Id == 0 {
+		return nil, xerr.Custom("请选择牧场信息")
+	}
+
+	if res.IsShow != pasturePb.IsShow_Ok {
+		return nil, xerr.Custom("改牧场已禁用")
+	}
+
+	return res, nil
+}

+ 24 - 7
module/backend/system_service.go

@@ -72,7 +72,7 @@ func (s *StoreEntry) Login(ctx context.Context, req *pasturePb.SearchUserRequest
 	}
 
 	expires := time.Now().Local().Add(time.Duration(s.Cfg.JwtExpireTime) * time.Second).Format(util.LayoutTime)
-	farmList, err := s.FindPastureList(ctx, systemUser.PastureIds)
+	farmList, err := s.FindPastureListByIds(ctx, systemUser.GetPastureIds())
 	if err != nil || len(farmList) == 0 {
 		return nil, xerr.Custom("牧场信息错误")
 	}
@@ -133,12 +133,17 @@ func (s *StoreEntry) SearchSystemUserList(ctx context.Context, req *pasturePb.Se
 		return nil, xerr.WithStack(err)
 	}
 
-	roleList, err := s.SearchSystemRoleListByIds(ctx, []int64{})
+	roleList, err := s.SearchSystemRoleListByIds(ctx, userModel.AppPasture.Id, []int64{})
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
 
-	deptList, err := s.SearchSystemDeptListByIds(ctx, []int64{})
+	deptList, err := s.SearchSystemDeptListByIds(ctx, userModel.AppPasture.Id, []int64{})
+	if err != nil {
+		return nil, xerr.WithStack(err)
+	}
+
+	appPastureList, err := s.FindPastureList(ctx)
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -147,7 +152,7 @@ func (s *StoreEntry) SearchSystemUserList(ctx context.Context, req *pasturePb.Se
 		Code: http.StatusOK,
 		Msg:  "ok",
 		Data: &pasturePb.SearchUserData{
-			List:     model.SystemUserSlice(systemUserList).ToPB(deptList, roleList),
+			List:     model.SystemUserSlice(systemUserList).ToPB(deptList, roleList, appPastureList),
 			Total:    int32(count),
 			PageSize: pagination.PageSize,
 			Page:     pagination.Page,
@@ -209,12 +214,23 @@ func (s *StoreEntry) IsShowSystemUser(ctx context.Context, userId int64) error {
 func (s *StoreEntry) SystemUserCreateOrUpdate(ctx context.Context, req *pasturePb.SearchUserRequest) error {
 	deptIds, pastureIds := "", ""
 	for _, pasture := range req.PastureDepthList {
-		pastureIds += fmt.Sprintf("%d,", pasture.PastureId)
+		appPasture, err := s.GetAppPastureListByFarmId(ctx, pasture.FarmId)
+		if err != nil {
+			return xerr.WithStack(err)
+		}
+		pastureIds += fmt.Sprintf("%d,", appPasture.Id)
 		if len(pasture.DepthList) > 0 {
 			for _, dept := range pasture.DepthList {
 				deptIds += fmt.Sprintf("%d,", dept.Id)
 			}
 		}
+		if len(pastureIds) > 0 {
+			pastureIds = strings.TrimSuffix(pastureIds, ",")
+		}
+
+		if len(deptIds) > 0 {
+			deptIds = strings.TrimSuffix(deptIds, ",")
+		}
 	}
 
 	systemUser := &model.SystemUser{}
@@ -247,7 +263,7 @@ func (s *StoreEntry) SystemUserCreateOrUpdate(ctx context.Context, req *pastureP
 			return xerr.Customf("系统中该用户名称已经存在: %s_%s", req.Name, req.Mobile)
 		}
 
-		newSystemUser := model.NewSystemUser(req, deptIds, pastureIds)
+		newSystemUser := model.NewSystemUser(req, deptIds, pastureIds, req.PastureDepthList)
 		if err := s.DB.Model(new(model.SystemUser)).
 			Create(newSystemUser).Error; err != nil {
 			return xerr.WithStack(err)
@@ -521,9 +537,10 @@ func (s *StoreEntry) SearchSystemRoleList(ctx context.Context, req *pasturePb.Se
 }
 
 // SearchSystemRoleListByIds 根据id查询角色列表
-func (s *StoreEntry) SearchSystemRoleListByIds(ctx context.Context, ids []int64) ([]*model.SystemRole, error) {
+func (s *StoreEntry) SearchSystemRoleListByIds(ctx context.Context, pastureId int64, ids []int64) ([]*model.SystemRole, error) {
 	systemRoleList := make([]*model.SystemRole, 0)
 	if err := s.DB.Model(new(model.SystemRole)).
+		Where("pasture_id = ?", pastureId).
 		Where("is_show = ?", operationPb.IsShow_OK).
 		Find(&systemRoleList, ids).Error; err != nil {
 		return nil, xerr.WithStack(err)

+ 7 - 2
module/backend/system_service_more.go

@@ -192,10 +192,15 @@ func (s *StoreEntry) SystemDepDelete(ctx context.Context, id int64) error {
 		return xerr.WithStack(err)
 	}
 
+	if dept.IsInit == pasturePb.IsShow_Ok {
+		return xerr.Custom("该部门不可删除")
+	}
+
 	if dept.IsShow == pasturePb.IsShow_No {
 		return nil
 	}
 	if err = s.DB.Model(new(model.SystemDept)).
+		Where("id = ?", id).
 		Update("is_delete", operationPb.IsShow_NO).
 		Error; err != nil {
 		return xerr.WithStack(err)
@@ -245,7 +250,7 @@ func (s *StoreEntry) SearchUserPastureList(ctx context.Context) (*pasturePb.Syst
 		return nil, xerr.WithStack(err)
 	}
 
-	farmList, err := s.FindPastureList(ctx, currentUser.PastureIds)
+	farmList, err := s.FindPastureListByIds(ctx, currentUser.GetPastureIds())
 	if err != nil {
 		return nil, xerr.WithStack(err)
 	}
@@ -331,7 +336,7 @@ func (s *StoreEntry) SearchDepthPastureList(ctx context.Context) []*model.System
 }
 
 // findAllParentDepths 递归查找所有上级部门
-func (s *StoreEntry) findAllParentDepths(ctx context.Context, depths []*model.SystemDept, pastureIds []int64) ([]*model.SystemDept, error) {
+func (s *StoreEntry) findAllParentDepths(ctx context.Context, depths []*model.SystemDept, pastureIds []int32) ([]*model.SystemDept, error) {
 	var allDepths []*model.SystemDept
 	var parentIDs []int64
 	foundDepths := make(map[int64]bool)

+ 8 - 2
module/backend/test_service.go

@@ -171,8 +171,14 @@ func (s *StoreEntry) PastureInit(ctx context.Context, pastureId int64) error {
 			zaplog.Error("PastureInit-NeckRingConfigure", zap.Any("error", err))
 		}
 
-		// 初始化牧场部门数据
-		newSystemDept := model.NewSystemDeptInit(pasture)
+		// 初始化牧场和部门数据
+		newSystemPastureDept := model.NewSystemPastureDeptInit(pasture)
+		if err := tx.Model(new(model.SystemDept)).
+			Create(newSystemPastureDept).Error; err != nil {
+			zaplog.Error("PastureInit-SystemDept", zap.Any("error", err))
+		}
+
+		newSystemDept := model.NewSystemDeptInit(pasture.Id, newSystemPastureDept.Id)
 		if err := tx.Model(new(model.SystemDept)).
 			Create(newSystemDept).Error; err != nil {
 			zaplog.Error("PastureInit-SystemDept", zap.Any("error", err))

+ 0 - 6
util/util_test.go

@@ -535,11 +535,5 @@ type WeeklyActiveModel struct {
 }
 
 func Test_demo(t *testing.T) {
-	for _, frameId := range FrameIdSlice {
-		if frameId%10 == 8 {
-			continue
-		}
-		fmt.Println(GenerateRandomNumber(int(frameId)))
-	}
 
 }