package backend import ( "context" "errors" "kpt-tmr-group/model" "kpt-tmr-group/pkg/xerr" operationPb "kpt-tmr-group/proto/go/backend/operation" "gorm.io/gorm" ) const ( FeedCategory = "feed" FeedCategoryDelete = "feed_delete" CowCategory = "cow" CowCategoryDelete = "cow_delete" ) func (s *StoreEntry) CategorySyncData(ctx context.Context, req *operationPb.CategorySyncRequest) error { pastureDetail, err := s.GetGroupPastureListById(ctx, int64(req.PastureId)) if err != nil { return xerr.WithStack(err) } switch req.KeyWord { case FeedCategory: history := &model.ForageCategory{} if err = s.DB.Model(new(model.ForageCategory)). Where("pasture_id = ?", req.PastureId). Where("data_id = ?", req.Id). Where("data_source = ? ", operationPb.DataSource_FROM_PASTURE). First(history).Error; err != nil { if !errors.Is(err, gorm.ErrRecordNotFound) { return xerr.WithStack(err) } } if history.IsShow == operationPb.IsShow_OK && history.Id > 0 { if err = s.DB.Model(new(model.ForageCategory)).Where("id = ?", history.Id).Updates(map[string]interface{}{ "number": req.Number, "is_show": req.IsShow, "parent_id": req.ParentId, "parent_name": req.ParentName, "name": req.Name, }).Error; err != nil { return xerr.WithStack(err) } } newFeedData := model.NewPastureForageCategory(req, pastureDetail) if err = s.DB.Model(new(model.ForageCategory)).Create(newFeedData).Error; err != nil { return xerr.WithStack(err) } case CowCategory: history := &model.CattleCategory{} if err = s.DB.Model(new(model.CattleCategory)). Where("pasture_id = ?", req.PastureId). Where("data_id = ?", req.Id). Where("data_source = ? ", operationPb.DataSource_FROM_PASTURE). First(history).Error; err != nil { if !errors.Is(err, gorm.ErrRecordNotFound) { return xerr.WithStack(err) } } if history.IsShow == operationPb.IsShow_OK && history.Id > 0 { if err = s.DB.Model(new(model.CattleCategory)).Where("id = ?", history.Id).Updates(map[string]interface{}{ "number": req.Number, "is_show": req.IsShow, "parent_id": req.ParentId, "parent_name": req.ParentName, "name": req.Name, }).Error; err != nil { return xerr.WithStack(err) } } newCattleData := model.NewPastureCattleCategory(req, pastureDetail) if err = s.DB.Model(new(model.CattleCategory)).Create(newCattleData).Error; err != nil { return xerr.WithStack(err) } } return nil } func (s *StoreEntry) CategoryDeleteData(ctx context.Context, req *operationPb.CategoryDeleteRequest) error { var modelValue interface{} switch req.KeyWord { case FeedCategoryDelete: modelValue = new(model.ForageCategory) case CowCategoryDelete: modelValue = new(model.CattleCategory) } if modelValue == nil { return nil } if err := s.DB.Model(modelValue).Where("data_id = ?", req.DataId). Where("pasture_id = ?", req.PastureId).Where("data_source = ?", operationPb.DataSource_FROM_PASTURE). Updates(map[string]interface{}{ "is_delete": operationPb.IsShow_OK, }).Error; err != nil { return xerr.WithStack(err) } return nil }