Files
ocean/category/internal/logic/createcategorylogic.go
2025-05-22 19:39:08 +08:00

119 lines
2.9 KiB
Go

package logic
import (
"context"
"database/sql"
"errors"
"time"
"godemo/category/category"
"godemo/category/internal/model"
"godemo/category/internal/svc"
"github.com/google/uuid"
"github.com/zeromicro/go-zero/core/logx"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type CreateCategoryLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewCreateCategoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCategoryLogic {
return &CreateCategoryLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *CreateCategoryLogic) CreateCategory(in *category.CreateCategoryRequest) (*category.CategoryInfoResponse, error) {
// 参数校验
if in.SystemId == "" || in.Name == "" {
return nil, status.Error(codes.InvalidArgument, "system_id 和 name 不能为空")
}
// 检查唯一性
exists, err := l.checkCategoryExists(in)
if err != nil {
logx.Error("唯一性检查失败: ", err)
return nil, status.Error(codes.Internal, "内部错误")
}
if exists {
return nil, status.Error(codes.AlreadyExists, "分类已存在")
}
// 构建模型
newCategory := &model.Categories{
Id: uuid.New().String(),
SystemId: in.SystemId,
Name: in.Name,
Alias: toNullString(in.Alias),
ParentId: toNullString(in.ParentId),
Description: toNullString(in.Description),
CreatedAt: time.Now(),
UpdatedAt: sql.NullTime{Time: time.Now(), Valid: true},
}
// 插入数据库
if _, err := l.svcCtx.CategoryModel.Insert(l.ctx, newCategory); err != nil {
logx.Error("插入失败: ", err)
return nil, status.Error(codes.Internal, "创建分类失败")
}
// 返回响应
return &category.CategoryInfoResponse{
Category: &category.CategoryInfo{
Id: newCategory.Id,
SystemId: newCategory.SystemId,
Name: newCategory.Name,
Alias: in.Alias,
ParentId: in.ParentId,
Description: in.Description,
CreatedAt: newCategory.CreatedAt.Unix(),
UpdatedAt: newCategory.UpdatedAt.Time.Unix(),
},
}, nil
}
// 空字符串转换为 sql.NullString
func toNullString(s string) sql.NullString {
return sql.NullString{String: s, Valid: s != ""}
}
// 唯一性检查逻辑
func (l *CreateCategoryLogic) checkCategoryExists(in *category.CreateCategoryRequest) (bool, error) {
// 检查名称唯一性
_, err := l.svcCtx.CategoryModel.FindBySystemParentName(
l.ctx,
in.SystemId,
in.ParentId,
in.Name,
)
if err == nil {
return true, nil
} else if !errors.Is(err, model.ErrNotFound) {
return false, err
}
// 检查别名唯一性(如果提供了别名)
if in.Alias != "" {
_, err := l.svcCtx.CategoryModel.FindBySystemParentAlias(
l.ctx,
in.SystemId,
in.ParentId,
in.Alias,
)
if err == nil {
return true, nil
} else if !errors.Is(err, model.ErrNotFound) {
return false, err
}
}
return false, nil
}