| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434 | package backendimport (	"context"	"fmt"	"kpt-pasture/model"	"net/http"	"strconv"	"strings"	"gitee.com/xuyiping_admin/pkg/logger/zaplog"	"go.uber.org/zap"	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"	"gitee.com/xuyiping_admin/pkg/xerr"	"gorm.io/gorm")func (s *StoreEntry) ParseCowIds(ctx context.Context, pastureId int64, cowIds string) ([]*model.Cow, error) {	if len(cowIds) == 0 {		return nil, xerr.Custom("cow id is required")	}	cowIdStr := strings.Split(cowIds, ",")	var cowIdInts = make([]int64, 0)	for _, v := range cowIdStr {		cowId, err := strconv.ParseInt(v, 10, 64)		if err != nil {			return nil, xerr.Customf("错误的牛号: %s", v)		}		cowIdInts = append(cowIdInts, cowId)	}	cowList, err := s.GetCowInfoByCowIds(ctx, pastureId, cowIdInts)	if err != nil {		return nil, xerr.WithStack(err)	}	return cowList, nil}func (s *StoreEntry) EnterList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchEnterEventResponse, error) {	currentUser, err := s.GetCurrentSystemUser(ctx)	if err != nil || currentUser.Id <= 0 {		return nil, xerr.Customf("当前用户信息错误,请退出重新登录")	}	eventEnterList := make([]*model.EventEnter, 0)	var count int64 = 0	pref := s.DB.Model(new(model.EventEnter)).		Where("pasture_id = ?", currentUser.PastureId)	if len(req.CowId) > 0 {		cowIds := strings.Split(req.CowId, ",")		pref.Where("cow_id IN ?", cowIds)	}	if err = pref.Order("id desc").		Count(&count).Limit(int(pagination.PageSize)).		Offset(int(pagination.PageOffset)).		Find(&eventEnterList).Error; err != nil {		return nil, xerr.WithStack(err)	}	penMap := s.PenMap(ctx, currentUser.PastureId)	breedStatusMap := s.CowBreedStatusMap()	cowSourceMap := s.CowSourceMap()	cowTypeMap := s.CowTypeMap()	cowKindMap := s.CowKindMap()	return &pasturePb.SearchEnterEventResponse{		Code:    http.StatusOK,		Message: "ok",		Data: &pasturePb.SearchEnterEventData{			List:     model.EventEnterSlice(eventEnterList).ToPB(penMap, breedStatusMap, cowSourceMap, cowTypeMap, cowKindMap),			Total:    int32(count),			PageSize: pagination.PageSize,			Page:     pagination.Page,		},	}, nil}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("当前用户信息错误,请退出重新登录")	}	req.MessengerId = int32(currentUser.Id)	req.MessengerName = currentUser.Name	if req.OperationId > 0 {		systemUser, _ := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))		req.OperationName = systemUser.Name	}	newCowData := model.NewCow(req)	newEventEnter := model.NewEventEnter(currentUser.PastureId, newCowData.Id, req)	if err = s.DB.Transaction(func(tx *gorm.DB) error {		if err = tx.Create(newCowData).Error; err != nil {			return xerr.WithStack(err)		}		if err = tx.Create(newEventEnter).Error; err != nil {			return xerr.WithStack(err)		}		return nil	}); err != nil {		return xerr.WithStack(err)	}	return nil}func (s *StoreEntry) GroupTransferList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchTransferGroupEventResponse, error) {	eventGroupTransferList := make([]*pasturePb.EventTransferGroupData, 0)	var count int64 = 0	pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventTransferGroup).TableName())).		Select(`a.id,a.cow_id,a.pen_in_id as transfer_in_pen_id,a.pen_out_id as transfer_out_pen_id,a.lact,a.remarks,a.transfer_reason_id,a.transfer_reason_name,			a.transfer_date,a.created_at,a.operation_id,a.operation_name,b.name as transfer_in_pen_name,c.name as transfer_out_pen_name,			f.lact,f.ear_number`).		Joins(fmt.Sprintf("JOIN %s AS b ON a.pen_in_id = b.id", new(model.Pen).TableName())).		Joins(fmt.Sprintf("JOIN %s AS c on a.pen_out_id = c.id", new(model.Pen).TableName())).		Joins(fmt.Sprintf("JOIN %s AS f ON a.cow_id = f.id", new(model.Cow).TableName()))	if len(req.CowId) > 0 {		cowIds := strings.Split(req.CowId, ",")		pref.Where("a.cow_id IN ?", cowIds)	}	if err := pref.Order("a.id desc").Group("a.id").		Count(&count).Limit(int(pagination.PageSize)).		Offset(int(pagination.PageOffset)).		Find(&eventGroupTransferList).Error; err != nil {		return nil, xerr.WithStack(err)	}	return &pasturePb.SearchTransferGroupEventResponse{		Code:    http.StatusOK,		Message: "ok",		Data: &pasturePb.SearchTransferGroupEventData{			List:     eventGroupTransferList,			Total:    int32(count),			PageSize: pagination.PageSize,			Page:     pagination.Page,		},	}, nil}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("当前用户信息错误,请退出重新登录")	}	newEventTransferGroupModelList := make([]*model.EventTransferGroupModel, 0)	for _, v := range req.Body {		cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(v.CowId))		if err != nil {			return xerr.WithStack(err)		}		// 转去栏舍和当前栏舍相同,则不处理		if cow.PenId == v.TransferInPenId {			continue		}		operationUser, err := s.GetSystemUserById(ctx, cow.PastureId, int64(v.OperationId))		if err != nil {			return xerr.WithStack(err)		}		newEventTransferGroup := model.NewEventTransferGroup(cow, v, currentUser, operationUser)		newEventTransferGroupModelList = append(newEventTransferGroupModelList, &model.EventTransferGroupModel{			Cow:                cow,			EventTransferGroup: newEventTransferGroup,		})	}	if len(newEventTransferGroupModelList) <= 0 {		return nil	}	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)				s.DB.Table(cowLogs.TableName()).Create(cowLogs)			}		}	}()	if err = s.DB.Transaction(func(tx *gorm.DB) error {		for _, v := range newEventTransferGroupModelList {			if err = tx.Create(v.EventTransferGroup).Error; err != nil {				return xerr.WithStack(err)			}			if err = tx.Model(v.Cow).Update("pen_id", v.EventTransferGroup.PenInId).Error; err != nil {				return xerr.WithStack(err)			}		}		return nil	}); err != nil {		return xerr.WithStack(err)	}	return nil}func (s *StoreEntry) BodyScoreList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchBodyScoreEventResponse, error) {	bodyScoreList := make([]*pasturePb.BodyScoreList, 0)	var count int64 = 0	pref := s.DB.Model(new(model.EventBodyScore)).Select("*,score as body_score")	if len(req.CowId) > 0 {		cowIds := strings.Split(req.CowId, ",")		pref.Where("cow_id IN ?", cowIds)	}	if err := pref.Order("id desc").		Count(&count).Limit(int(pagination.PageSize)).		Offset(int(pagination.PageOffset)).		Find(&bodyScoreList).Error; err != nil {		return nil, xerr.WithStack(err)	}	return &pasturePb.SearchBodyScoreEventResponse{		Code:    http.StatusOK,		Message: "ok",		Data: &pasturePb.SearchBodyScoreData{			List:     bodyScoreList,			Total:    int32(count),			PageSize: pagination.PageSize,			Page:     pagination.Page,		},	}, nil}func (s *StoreEntry) CreateBodyScore(ctx context.Context, req *pasturePb.BodyScoreEventRequest) error {	if len(req.CowId) <= 0 {		return xerr.Custom("请选择相关牛只")	}	currentUser, err := s.GetCurrentSystemUser(ctx)	if err != nil {		return xerr.Custom("获取当前用户失败,请退出重新登录")	}	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))	if err != nil {		return xerr.WithStack(err)	}	req.OperationName = operationUser.Name	bodyScourEvent := make([]*model.EventBodyScore, 0)	cowList, err := s.ParseCowIds(ctx, currentUser.PastureId, req.CowId)	if err != nil {		return xerr.WithStack(err)	}	for _, cow := range cowList {		bodyScourEvent = append(bodyScourEvent, model.NewEventBodyScore(cow, currentUser, req))	}	if len(bodyScourEvent) <= 0 {		return nil	}	return s.DB.Create(bodyScourEvent).Error}func (s *StoreEntry) WeightList(ctx context.Context, req *pasturePb.SearchEventRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SearchWeightEventResponse, error) {	weightList := make([]*pasturePb.SearchWeightList, 0)	var count int64 = 0	pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventWeight).TableName())).		Select(`a.id,a.cow_id,a.ear_number,a.weight / 100 as weight,a.lact,a.day_age,a.weight_at,a.remarks,a.created_at,		a.updated_at,a.message_id,a.operation_id,a.message_name,a.operation_name`)	if len(req.CowId) > 0 {		cowIds := strings.Split(req.CowId, ",")		pref.Where("a.cow_id IN ?", cowIds)	}	if err := pref.Order("a.id desc").		Count(&count).Limit(int(pagination.PageSize)).		Offset(int(pagination.PageOffset)).		Find(&weightList).Error; err != nil {		return nil, xerr.WithStack(err)	}	return &pasturePb.SearchWeightEventResponse{		Code:    http.StatusOK,		Message: "ok",		Data: &pasturePb.SearchWeightData{			List:     weightList,			Total:    int32(count),			PageSize: pagination.PageSize,			Page:     pagination.Page,		},	}, nil}func (s *StoreEntry) WeightBatch(ctx context.Context, req *pasturePb.EventWeight) (err error) {	if len(req.WeightItems) <= 0 {		return xerr.Custom("请选择相关牛只")	}	currentUser, err := s.GetCurrentSystemUser(ctx)	if err != nil {		return xerr.Custom("当前登录用户失败,请退出重新登录")	}	operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(req.OperationId))	if err != nil {		return xerr.WithStack(err)	}	req.OperationName = operationUser.Name	defer func() {		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)				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))		if err != nil {			return xerr.WithStack(err)		}		item.WeightAt = req.WeightAt		// 更新牛只信息		cow.EventWeightUpdate(int64(item.Weight), int64(req.WeightAt))		if err = s.DB.Model(new(model.Cow)).			Select("last_second_weight_at", "last_second_weight", "last_weight_at", "current_weight").			Where("id = ?", cow.Id).			Where("admission_status = ?", pasturePb.AdmissionStatus_Admission).			Updates(cow).Error; err != nil {			return xerr.WithStack(err)		}		// 创建牛只的体重记录		eventWeight := model.NewEventWeight(cow, currentUser, int32(item.Weight*1000), item.Height, req)		if err = s.DB.Create(eventWeight).Error; err != nil {			return xerr.WithStack(err)		}	}	return err}func (s *StoreEntry) DepartureBatch(ctx context.Context, req *pasturePb.EventDepartureBatch) (err error) {	if len(req.Item) <= 0 {		return xerr.Custom("请选择相关牛只")	}	currentUser, err := s.GetCurrentSystemUser(ctx)	if err != nil {		return xerr.Custom("当前登录用户失败,请退出重新登录")	}	newEventDepartureModelList := make([]*model.EventDepartureModel, 0)	cow := &model.Cow{}	for _, item := range req.Item {		cow, err = s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(item.CowId))		if err != nil {			zaplog.Error("DepartureBatch", zap.Any("item", item), zap.Any("err", err))			return xerr.Customf("获取牛只信息失败: %d", item.CowId)		}		operationUser, err := s.GetSystemUserById(ctx, currentUser.PastureId, int64(item.OperationId))		if err != nil {			zaplog.Error("DepartureBatch", zap.Any("item", item), zap.Any("err", err))			return xerr.Customf("获取操作人员信息失败: %d", item.OperationId)		}		reasonName := ""		switch item.DepartureType {		case pasturePb.DepartureType_Death:			reasonName = s.DeadReasonMap()[pasturePb.DeadReason_Kind(item.DepartureReasonKind)]		case pasturePb.DepartureType_Out:			reasonName = s.OutReasonMap()[pasturePb.OutReason_Kind(item.DepartureReasonKind)]		default:			return xerr.Custom("未知的离场类型")		}		newEventDeparture := model.NewEventDeparture(currentUser.PastureId, cow, item, reasonName, currentUser, operationUser)		newEventDepartureModelList = append(newEventDepartureModelList, &model.EventDepartureModel{			EventDeparture: newEventDeparture,			Cow:            cow,			DepartureAt:    int64(item.DepartureAt),		})	}	if len(newEventDepartureModelList) <= 0 {		return nil	}	if err = s.DB.Transaction(func(tx *gorm.DB) error {		// 记录事件日志		for _, item := range newEventDepartureModelList {			eventType := pasturePb.EventType_Death			if item.EventDeparture.DepartureType == pasturePb.DepartureType_Out {				eventType = pasturePb.EventType_Out			}			if err = tx.Create(item.EventDeparture).Error; err != nil {				return xerr.WithStack(err)			}			cow.EventDepartureUpdate(item.DepartureAt, item.EventDeparture.DepartureType)			if err = tx.Model(cow).				Select("admission_status", "health_status", "departure_at").				Where("id = ?", cow.Id).				Updates(cow).Error; err != nil {				return xerr.WithStack(err)			}			// 记录事件日志			cowLogs := s.SubmitEventLog(ctx, currentUser, item.Cow, eventType, pasturePb.ExposeEstrusType_Invalid, item)			tx.Table(cowLogs.TableName()).Create(cowLogs)		}		return nil	}); err != nil {		return xerr.WithStack(err)	}	return nil}func (s *StoreEntry) CowEarNumberUpdate(ctx context.Context, req *pasturePb.EventReplaceEarNumber) (err error) {	currentUser, err := s.GetCurrentSystemUser(ctx)	if err != nil {		return xerr.Custom("当前登录用户失败,请退出重新登录")	}	cow, err := s.GetCowInfoByCowId(ctx, currentUser.PastureId, int64(req.CowId))	if err != nil {		return xerr.Custom("未找到该牛只信息")	}	cow.EventEarNumberUpdate(req.EarNumber)	if err = s.DB.Model(cow).		Select("ear_number", "ear_old_number").		Where("id = ?", cow.Id).		Updates(cow).Error; err != nil {		return xerr.WithStack(err)	}	return nil}
 |