feat: add category and group name uniqueness checks with corresponding error handling

This commit is contained in:
BXY 2026-09-23 18:15:26 +08:00
parent 6e7449646c
commit 9c31d0e869
3 changed files with 65 additions and 5 deletions

View File

@ -23,6 +23,8 @@ var ErrProductNotFound = errors.New("product not found")
var ErrCategoryNodeNotFound = errors.New("category or group node not found")
var ErrCategoryVersionConflict = errors.New("category version conflict")
var ErrCategoryTreeConflict = errors.New("category tree conflict")
var ErrCategoryNameExists = errors.New("category name already exists")
var ErrGroupNameExists = errors.New("group name already exists")
var ErrInvalidLeafCategory = errors.New("category must be an existing second-level category")
// ErrInvalidProductGroup is returned when a requested node is not a group in
@ -416,6 +418,19 @@ CREATE INDEX IF NOT EXISTS idx_products_store_id ON product.products (store_id)
CREATE INDEX IF NOT EXISTS idx_product_category_store_id ON product.product_category (store_id);
CREATE INDEX IF NOT EXISTS idx_product_category_campaign_id
ON product.product_category (campaign_id) WHERE campaign_id IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name
ON product.product_category (
store_id,
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
)
WHERE node_type = 2;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_sibling_normalized_name
ON product.product_category (
store_id,
COALESCE(parent_id, 0),
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
)
WHERE node_type = 1;
DROP INDEX IF EXISTS product.uq_product_items_sku_no;
DROP INDEX IF EXISTS product.uq_product_items_sku_no_active;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_store_sku_no_active
@ -819,6 +834,9 @@ RETURNING id, node_type, name, parent_id, level,
update.CampaignID != nil, campaignID,
)
category, err := scanCategory(row)
if nameConflict := categoryNameConflictError(err); nameConflict != nil {
return nil, nameConflict
}
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrCategoryVersionConflict
}
@ -2986,6 +3004,17 @@ func isPostgresConstraintError(err error, code, constraint string) bool {
return pgErr.Code == code && pgErr.ConstraintName == constraint
}
func categoryNameConflictError(err error) error {
switch {
case isPostgresConstraintError(err, "23505", "uq_product_category_group_normalized_name"):
return ErrGroupNameExists
case isPostgresConstraintError(err, "23505", "uq_product_category_sibling_normalized_name"):
return ErrCategoryNameExists
default:
return nil
}
}
func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) (*SKURecord, error) {
attrs, err := normalizeAttributesJSON(sku.AttributesJSON)
if err != nil {
@ -3173,6 +3202,9 @@ RETURNING id,
`, id, scope.TenantID, scope.StoreID, int16(category.NodeType), category.Name, parentID, int16(category.Level), stringSliceOrEmpty(category.ImageIDs), category.SortNum, int16(category.Status), campaignID)
createdCategory, err := scanCategory(row)
if nameConflict := categoryNameConflictError(err); nameConflict != nil {
return nil, nameConflict
}
if err != nil {
return nil, fmt.Errorf("insert category node: %w", err)
}

View File

@ -0,0 +1,16 @@
package server
import "testing"
func TestNormalizeNodeNameCollapsesUnicodeWhitespace(t *testing.T) {
name, err := normalizeNodeName("  Summer\t\n Sale ", "name")
if err != nil {
t.Fatalf("normalizeNodeName: %v", err)
}
if name != "Summer Sale" {
t.Fatalf("normalized name = %q, want %q", name, "Summer Sale")
}
if normalizedNodeNameKey(name) != normalizedNodeNameKey("summer sale") {
t.Fatal("normalized name key must ignore case")
}
}

View File

@ -713,6 +713,9 @@ func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.C
if err != nil {
dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error())
if errors.Is(err, repository.ErrCategoryNameExists) {
return nil, status.Error(codes.AlreadyExists, "category name already exists")
}
s.observer.Logger(ctx).Error("create category tree failed", zap.String("category_name", parent.Name), zap.Error(err))
return nil, status.Errorf(codes.Internal, "create category tree: %v", err)
}
@ -756,6 +759,8 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1.
switch {
case errors.Is(err, repository.ErrCategoryNodeNotFound):
return nil, status.Error(codes.NotFound, "category not found")
case errors.Is(err, repository.ErrCategoryNameExists):
return nil, status.Error(codes.AlreadyExists, "category name already exists")
case errors.Is(err, repository.ErrCategoryVersionConflict):
return nil, status.Error(codes.Aborted, "category version conflict")
case errors.Is(err, repository.ErrCategoryTreeConflict):
@ -856,6 +861,9 @@ func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGr
if err != nil {
dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error())
if errors.Is(err, repository.ErrGroupNameExists) {
return nil, status.Error(codes.AlreadyExists, "group name already exists")
}
s.observer.Logger(ctx).Error("create group failed", zap.String("group_name", group.Name), zap.Error(err))
return nil, status.Errorf(codes.Internal, "create group: %v", err)
}
@ -1192,10 +1200,10 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re
if err != nil {
return repository.CategoryRecord{}, nil, err
}
if _, exists := childNames[childName]; exists {
if _, exists := childNames[normalizedNodeNameKey(childName)]; exists {
return repository.CategoryRecord{}, nil, errors.New("children.name must be unique")
}
childNames[childName] = struct{}{}
childNames[normalizedNodeNameKey(childName)] = struct{}{}
childImageIDs, err := normalizeNodeImageIDs(child.GetImageJson())
if err != nil {
@ -1275,10 +1283,10 @@ func categoryTreeUpdatesFromRequest(req *productv1.UpdateCategoryTreesRequest) (
if err != nil {
return nil, nil, err
}
if _, exists := newChildNames[newChild.Name]; exists {
if _, exists := newChildNames[normalizedNodeNameKey(newChild.Name)]; exists {
return nil, nil, errors.New("new_child_categories.name must be unique")
}
newChildNames[newChild.Name] = struct{}{}
newChildNames[normalizedNodeNameKey(newChild.Name)] = struct{}{}
update.NewChildren = append(update.NewChildren, newChild)
}
if update.Category == nil && len(update.Children) == 0 && len(update.NewChildren) == 0 {
@ -1416,7 +1424,7 @@ func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.Categ
}
func normalizeNodeName(raw, field string) (string, error) {
name := strings.TrimSpace(raw)
name := strings.Join(strings.Fields(raw), " ")
if name == "" {
return "", fmt.Errorf("%s is required", field)
}
@ -1426,6 +1434,10 @@ func normalizeNodeName(raw, field string) (string, error) {
return name, nil
}
func normalizedNodeNameKey(name string) string {
return strings.ToLower(name)
}
func normalizeNodeImageIDs(raw string) ([]string, error) {
raw = strings.TrimSpace(raw)
if raw == "" {