From 6f6887f0d25b4638dca64707c13bd9ffa8de273d Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:56:54 +0800 Subject: [PATCH] Refactor product category schema and server logic - Updated the product_category table schema to remove tenant_id and store_id, and added new fields: priority, rule_id, category_type, channel_list, has_children, has_prop_required, extra, cert_status_code, cert_status_pass, and cert_status_msg. - Modified SQL scripts to drop and recreate product_category and product_category_bindings tables with the new schema. - Refactored the ProductServer methods to remove store scope requirements and adjust to the new product category structure. - Updated error handling and validation in Create, Update, and Delete product category methods. - Added new patch handling for product categories to accommodate the updated schema. - Introduced a new SQL script to rebuild the standard product category tree, ensuring a clean migration to the new structure. --- .../repository/product_category_repository.go | 468 ++++++++---------- internal/repository/product_repository.go | 39 +- internal/server/product_category_server.go | 164 +++--- ...rebuild_standard_product_category_tree.sql | 82 +++ 4 files changed, 382 insertions(+), 371 deletions(-) create mode 100644 scripts/sql/006_rebuild_standard_product_category_tree.sql diff --git a/internal/repository/product_category_repository.go b/internal/repository/product_category_repository.go index 3b75371..7a58aa9 100644 --- a/internal/repository/product_category_repository.go +++ b/internal/repository/product_category_repository.go @@ -5,6 +5,7 @@ import ( "database/sql" "errors" "fmt" + "sort" "strings" "time" ) @@ -12,59 +13,46 @@ import ( var ( ErrProductCategoryNotFound = errors.New("product category not found") ErrProductCategoryVersionConflict = errors.New("product category version conflict") - ErrProductCategoryHasChildren = errors.New("product category has children") - ErrProductCategoryInUse = errors.New("product category is bound to products") - ErrDuplicateProductCategory = errors.New("product category code or sibling name already exists") + ErrDuplicateProductCategory = errors.New("duplicate product category name") ) -// ProductCategoryRecord is the standard product taxonomy node. It is distinct -// from CatalogCategoryRecord (the storefront classification tree). type ProductCategoryRecord struct { - ID, CategoryCode, Name, ParentID, Remark string - Level, SortNum, Status, Version int32 - StatusSet bool - IsLeaf bool - ProductCount int64 - CreatedAt, UpdatedAt time.Time - DeletedAt *time.Time - Children []*ProductCategoryRecord + ID, Name, ParentID, RuleID, Extra, CertStatusMsg string + Level, Priority, Status, CategoryType, CertStatusCode, Version int32 + ChannelList []int32 + HasChildren, HasPropRequired, CertStatusPass bool + ProductCount int64 + CreatedAt, UpdatedAt time.Time + DeletedAt *time.Time + Children []*ProductCategoryRecord } type ProductCategoryPatch struct { - CategoryCode, Name, ParentID, Remark *string - SortNum, Status *int32 - ExpectedVersion int32 + ID string + ExpectedVersion int32 + Name, RuleID, Extra, CertStatusMsg *string + Priority, Status, CategoryType, CertStatusCode *int32 + ChannelList *[]int32 + HasChildren, HasPropRequired, CertStatusPass *bool + Children []*ProductCategoryPatch } -type ProductCategoryListFilter struct { - Keyword string - Status *int32 - Page, PageSize int32 +type ProductCategoryDeleteResult struct { + CategoryIDs []string + CategoryCount, BindingCount, ProductCount int32 + DeletedAt time.Time } -// ValidateProductCategory verifies that categoryID identifies a non-deleted -// standard product category in the active tenant and store. The category may -// be disabled: admin product-list filtering must still support historical -// products under disabled categories. func (r *ProductRepository) ValidateProductCategory(ctx context.Context, categoryID string, scope StoreScope) error { if err := requireWriteScope(scope); err != nil { return err } - parsed, err := parseID(categoryID, "category_id") + id, err := parseID(categoryID, "category_id") if err != nil { return err } var exists bool - err = r.db.QueryRowContext(ctx, ` -SELECT EXISTS( - SELECT 1 - FROM product.product_category - WHERE id = $1 - AND tenant_id = $2 - AND store_id = $3 - AND deleted_at IS NULL -)`, parsed, scope.TenantID, scope.StoreID).Scan(&exists) - if err != nil { + if err := r.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category WHERE id=$1 AND deleted_at IS NULL)`, id).Scan(&exists); err != nil { return fmt.Errorf("validate product category: %w", err) } if !exists { @@ -73,168 +61,119 @@ SELECT EXISTS( return nil } -func (r *ProductRepository) CreateProductCategory(ctx context.Context, root *ProductCategoryRecord, scope StoreScope) (*ProductCategoryRecord, error) { - if root == nil || !scope.Valid() { - return nil, errors.New("product category and store scope are required") +func (r *ProductRepository) CreateProductCategory(ctx context.Context, root *ProductCategoryRecord) (*ProductCategoryRecord, error) { + if root == nil { + return nil, errors.New("product category is required") } tx, err := r.db.BeginTx(ctx, nil) if err != nil { - return nil, fmt.Errorf("begin create product category: %w", err) + return nil, err } defer tx.Rollback() - created, err := createProductCategoryNode(ctx, tx, root, root.ParentID, scope) + created, err := createProductCategoryNode(ctx, tx, root, root.ParentID) if err != nil { return nil, err } if err := tx.Commit(); err != nil { - return nil, fmt.Errorf("commit create product category: %w", err) + return nil, err } return created, nil } -func createProductCategoryNode(ctx context.Context, tx *sql.Tx, input *ProductCategoryRecord, parentID string, scope StoreScope) (*ProductCategoryRecord, error) { - if input == nil { - return nil, errors.New("product category is required") - } +func createProductCategoryNode(ctx context.Context, tx *sql.Tx, input *ProductCategoryRecord, parentID string) (*ProductCategoryRecord, error) { level := int32(1) parent := sql.NullInt64{} if strings.TrimSpace(parentID) != "" { - parsed, err := parseID(parentID, "parent_id") + id, err := parseID(parentID, "parent_id") if err != nil { return nil, err } var parentLevel int32 - var parentStatus int32 - err = tx.QueryRowContext(ctx, `SELECT level,status FROM product.product_category WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL FOR UPDATE`, parsed, scope.TenantID, scope.StoreID).Scan(&parentLevel, &parentStatus) - if errors.Is(err, sql.ErrNoRows) { + if err = tx.QueryRowContext(ctx, `SELECT level FROM product.product_category WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, id).Scan(&parentLevel); errors.Is(err, sql.ErrNoRows) { return nil, ErrProductCategoryNotFound + } else if err != nil { + return nil, err } - if err != nil { - return nil, fmt.Errorf("load product category parent: %w", err) - } - if parentStatus != 1 { - return nil, errors.New("parent product category must be enabled") - } + parent = sql.NullInt64{Int64: id, Valid: true} level = parentLevel + 1 - parent = sql.NullInt64{Int64: parsed, Valid: true} - } - if level > 4 { - return nil, errors.New("product category depth cannot exceed 4") } id, err := parseID(input.ID, "product_category_id") if err != nil { return nil, err } - statusValue := input.Status - if !input.StatusSet { - statusValue = 1 - } - row := tx.QueryRowContext(ctx, `INSERT INTO product.product_category - (id,tenant_id,store_id,category_code,name,parent_id,level,is_leaf,sort_num,status,remark) - VALUES ($1,$2,$3,$4,$5,$6,$7,true,$8,$9,$10) - RETURNING id,category_code,name,parent_id,level,is_leaf,sort_num,status,remark,version,created_at,updated_at,deleted_at`, - id, scope.TenantID, scope.StoreID, input.CategoryCode, input.Name, parent, level, input.SortNum, statusValue, input.Remark) + row := tx.QueryRowContext(ctx, `INSERT INTO product.product_category (id,parent_id,level,name,priority,rule_id,status,category_type,channel_list,has_children,has_prop_required,extra,cert_status_code,cert_status_pass,cert_status_msg) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15) RETURNING id,parent_id,level,name,priority,rule_id,status,category_type,channel_list,has_children,has_prop_required,extra,cert_status_code,cert_status_pass,cert_status_msg,version,created_at,updated_at,deleted_at,0::bigint`, id, parent, level, input.Name, input.Priority, input.RuleID, input.Status, input.CategoryType, input.ChannelList, input.HasChildren, input.HasPropRequired, input.Extra, input.CertStatusCode, input.CertStatusPass, input.CertStatusMsg) created, err := scanProductCategory(row) if err != nil { return nil, mapProductCategoryWriteError(err) } for _, child := range input.Children { - createdChild, err := createProductCategoryNode(ctx, tx, child, created.ID, scope) + value, err := createProductCategoryNode(ctx, tx, child, created.ID) if err != nil { return nil, err } - created.Children = append(created.Children, createdChild) - } - if len(created.Children) > 0 { - if _, err := tx.ExecContext(ctx, `UPDATE product.product_category SET is_leaf=false,updated_at=NOW(),version=version+1 WHERE id=$1`, id); err != nil { - return nil, err - } - created.IsLeaf = false - created.Version++ + created.Children = append(created.Children, value) } return created, nil } -func (r *ProductRepository) ListProductCategories(ctx context.Context, filter ProductCategoryListFilter, scope StoreScope) ([]*ProductCategoryRecord, int64, error) { - if !scope.Valid() { - return nil, 0, errors.New("store scope is required") +func (r *ProductRepository) ListProductCategories(ctx context.Context, id string) ([]*ProductCategoryRecord, error) { + if id != "" { + node, err := r.GetProductCategory(ctx, id) + if err != nil { + return nil, err + } + return []*ProductCategoryRecord{node}, nil } - where := `tenant_id=$1 AND store_id=$2 AND deleted_at IS NULL AND parent_id IS NULL` - args := []any{scope.TenantID, scope.StoreID} - if strings.TrimSpace(filter.Keyword) != "" { - args = append(args, "%"+strings.TrimSpace(filter.Keyword)+"%") - where += fmt.Sprintf(" AND (category_code ILIKE $%d OR name ILIKE $%d)", len(args), len(args)) - } - if filter.Status != nil { - args = append(args, *filter.Status) - where += fmt.Sprintf(" AND status=$%d", len(args)) - } - var total int64 - if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.product_category WHERE `+where, args...).Scan(&total); err != nil { - return nil, 0, err - } - args = append(args, filter.PageSize, (filter.Page-1)*filter.PageSize) - rows, err := r.db.QueryContext(ctx, fmt.Sprintf(`SELECT id FROM product.product_category WHERE %s ORDER BY sort_num,id LIMIT $%d OFFSET $%d`, where, len(args)-1, len(args)), args...) + rows, err := r.db.QueryContext(ctx, `SELECT id FROM product.product_category WHERE parent_id IS NULL AND deleted_at IS NULL ORDER BY priority,id`) if err != nil { - return nil, 0, err + return nil, err } defer rows.Close() - rootIDs := []string{} + var out []*ProductCategoryRecord for rows.Next() { - var id int64 - if err := rows.Scan(&id); err != nil { - return nil, 0, err + var raw int64 + if err := rows.Scan(&raw); err != nil { + return nil, err } - rootIDs = append(rootIDs, formatID(id)) - } - if err := rows.Err(); err != nil { - return nil, 0, err - } - roots := make([]*ProductCategoryRecord, 0, len(rootIDs)) - for _, id := range rootIDs { - root, err := r.loadProductCategoryTree(ctx, id, scope) + node, err := r.GetProductCategory(ctx, formatID(raw)) if err != nil { - return nil, 0, err + return nil, err } - roots = append(roots, root) + out = append(out, node) } - return roots, total, nil + return out, rows.Err() } -func (r *ProductRepository) GetProductCategory(ctx context.Context, id string, scope StoreScope) (*ProductCategoryRecord, error) { - return r.loadProductCategoryTree(ctx, id, scope) +func (r *ProductRepository) GetProductCategory(ctx context.Context, id string) (*ProductCategoryRecord, error) { + return r.loadProductCategoryTree(ctx, id) } -func (r *ProductRepository) loadProductCategoryTree(ctx context.Context, id string, scope StoreScope) (*ProductCategoryRecord, error) { +const productCategoryColumns = `id,parent_id,level,name,priority,rule_id,status,category_type,channel_list,has_children,has_prop_required,extra,cert_status_code,cert_status_pass,cert_status_msg,version,created_at,updated_at,deleted_at,(SELECT COUNT(*) FROM product.product_category_bindings b WHERE b.product_category_id=c.id AND b.deleted_at IS NULL)` + +func (r *ProductRepository) loadProductCategoryTree(ctx context.Context, id string) (*ProductCategoryRecord, error) { parsed, err := parseID(id, "product_category_id") if err != nil { return nil, err } - row := r.db.QueryRowContext(ctx, productCategorySelect+` WHERE c.id=$1 AND c.tenant_id=$2 AND c.store_id=$3 AND c.deleted_at IS NULL`, parsed, scope.TenantID, scope.StoreID) - root, err := scanProductCategory(row) + root, err := scanProductCategory(r.db.QueryRowContext(ctx, `SELECT `+productCategoryColumns+` FROM product.product_category c WHERE c.id=$1 AND c.deleted_at IS NULL`, parsed)) if errors.Is(err, sql.ErrNoRows) { return nil, ErrProductCategoryNotFound } if err != nil { return nil, err } - rows, err := r.db.QueryContext(ctx, `WITH RECURSIVE descendants AS ( - SELECT id FROM product.product_category WHERE parent_id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL - UNION ALL SELECT c.id FROM product.product_category c JOIN descendants d ON c.parent_id=d.id WHERE c.tenant_id=$2 AND c.store_id=$3 AND c.deleted_at IS NULL - ) SELECT c.id,c.category_code,c.name,c.parent_id,c.level,c.is_leaf,c.sort_num,c.status,c.remark,c.version,c.created_at,c.updated_at,c.deleted_at, - (SELECT COUNT(*) FROM product.product_category_bindings b WHERE b.product_category_id=c.id AND b.deleted_at IS NULL) - FROM product.product_category c JOIN descendants d ON d.id=c.id ORDER BY c.level,c.sort_num,c.id`, parsed, scope.TenantID, scope.StoreID) + rows, err := r.db.QueryContext(ctx, `WITH RECURSIVE d AS (SELECT id FROM product.product_category WHERE parent_id=$1 AND deleted_at IS NULL UNION ALL SELECT c.id FROM product.product_category c JOIN d ON c.parent_id=d.id WHERE c.deleted_at IS NULL) SELECT `+productCategoryColumns+` FROM product.product_category c JOIN d ON d.id=c.id ORDER BY c.level,c.priority,c.id`, parsed) if err != nil { return nil, err } defer rows.Close() byID := map[string]*ProductCategoryRecord{root.ID: root} for rows.Next() { - child, err := scanProductCategory(rows) - if err != nil { - return nil, err + node, e := scanProductCategory(rows) + if e != nil { + return nil, e } - byID[child.ID] = child + byID[node.ID] = node } if err := rows.Err(); err != nil { return nil, err @@ -250,91 +189,67 @@ func (r *ProductRepository) loadProductCategoryTree(ctx context.Context, id stri return root, nil } -func (r *ProductRepository) UpdateProductCategory(ctx context.Context, id string, patch ProductCategoryPatch, scope StoreScope) (*ProductCategoryRecord, error) { - parsed, err := parseID(id, "product_category_id") - if err != nil { - return nil, err +func (r *ProductRepository) UpdateProductCategory(ctx context.Context, rootID string, patch *ProductCategoryPatch) (*ProductCategoryRecord, error) { + if patch == nil { + return nil, errors.New("product category patch is required") } tx, err := r.db.BeginTx(ctx, nil) if err != nil { return nil, err } defer tx.Rollback() - var oldLevel int32 - err = tx.QueryRowContext(ctx, `SELECT level FROM product.product_category WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL FOR UPDATE`, parsed, scope.TenantID, scope.StoreID).Scan(&oldLevel) - if errors.Is(err, sql.ErrNoRows) { - return nil, ErrProductCategoryNotFound - } + root, err := parseID(rootID, "product_category_id") if err != nil { return nil, err } - parent := sql.NullInt64{} - newLevel := oldLevel - if patch.ParentID != nil { - if strings.TrimSpace(*patch.ParentID) != "" { - parentID, err := parseID(*patch.ParentID, "parent_id") - if err != nil { - return nil, err - } - if parentID == parsed { - return nil, errors.New("parent_id cannot be self") - } - var parentLevel, parentStatus int32 - err = tx.QueryRowContext(ctx, `SELECT level,status FROM product.product_category WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL FOR UPDATE`, parentID, scope.TenantID, scope.StoreID).Scan(&parentLevel, &parentStatus) - if errors.Is(err, sql.ErrNoRows) { - return nil, ErrProductCategoryNotFound - } - if err != nil { - return nil, err - } - if parentStatus != 1 { - return nil, errors.New("parent product category must be enabled") - } - var cycle bool - if err := tx.QueryRowContext(ctx, `WITH RECURSIVE d AS (SELECT id FROM product.product_category WHERE parent_id=$1 AND deleted_at IS NULL UNION ALL SELECT c.id FROM product.product_category c JOIN d ON c.parent_id=d.id WHERE c.deleted_at IS NULL) SELECT EXISTS(SELECT 1 FROM d WHERE id=$2)`, parsed, parentID).Scan(&cycle); err != nil { - return nil, err - } - if cycle { - return nil, errors.New("parent_id cannot be a descendant") - } - parent = sql.NullInt64{Int64: parentID, Valid: true} - newLevel = parentLevel + 1 - } - if newLevel > 4 { - return nil, errors.New("product category depth cannot exceed 4") - } - var maxDescendantLevel int32 - if err := tx.QueryRowContext(ctx, `WITH RECURSIVE d AS (SELECT id,level FROM product.product_category WHERE id=$1 UNION ALL SELECT c.id,c.level FROM product.product_category c JOIN d ON c.parent_id=d.id WHERE c.deleted_at IS NULL) SELECT COALESCE(MAX(level),$2) FROM d`, parsed, oldLevel).Scan(&maxDescendantLevel); err != nil { - return nil, err - } - if newLevel+(maxDescendantLevel-oldLevel) > 4 { - return nil, errors.New("moving this category exceeds maximum depth") - } + var exists bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category WHERE id=$1 AND deleted_at IS NULL)`, root).Scan(&exists); err != nil { + return nil, err } - result, err := tx.ExecContext(ctx, `UPDATE product.product_category SET - category_code=COALESCE($1,category_code),name=COALESCE($2,name),parent_id=CASE WHEN $3 THEN $4 ELSE parent_id END, - sort_num=COALESCE($5,sort_num),status=COALESCE($6,status),remark=COALESCE($7,remark),level=$8,version=version+1,updated_at=NOW() - WHERE id=$9 AND tenant_id=$10 AND store_id=$11 AND version=$12 AND deleted_at IS NULL`, patch.CategoryCode, patch.Name, patch.ParentID != nil, parent, patch.SortNum, patch.Status, patch.Remark, newLevel, parsed, scope.TenantID, scope.StoreID, patch.ExpectedVersion) - if err != nil { - return nil, mapProductCategoryWriteError(err) + if !exists { + return nil, ErrProductCategoryNotFound } - changed, _ := result.RowsAffected() - if changed == 0 { - return nil, ErrProductCategoryVersionConflict - } - if newLevel != oldLevel { - delta := newLevel - oldLevel - if _, err := tx.ExecContext(ctx, `WITH RECURSIVE d AS (SELECT id FROM product.product_category WHERE parent_id=$1 AND deleted_at IS NULL UNION ALL SELECT c.id FROM product.product_category c JOIN d ON c.parent_id=d.id WHERE c.deleted_at IS NULL) UPDATE product.product_category SET level=level+$2,version=version+1,updated_at=NOW() WHERE id IN (SELECT id FROM d)`, parsed, delta); err != nil { - return nil, err - } + if err := updateProductCategoryPatch(ctx, tx, root, patch); err != nil { + return nil, err } if err := tx.Commit(); err != nil { return nil, err } - return r.GetProductCategory(ctx, id, scope) + return r.GetProductCategory(ctx, rootID) +} +func updateProductCategoryPatch(ctx context.Context, tx *sql.Tx, root int64, patch *ProductCategoryPatch) error { + id, err := parseID(patch.ID, "product_category_id") + if err != nil { + return err + } + var allowed bool + if err = tx.QueryRowContext(ctx, `WITH RECURSIVE d AS (SELECT id FROM product.product_category WHERE id=$1 AND deleted_at IS NULL UNION ALL SELECT c.id FROM product.product_category c JOIN d ON c.parent_id=d.id WHERE c.deleted_at IS NULL) SELECT EXISTS(SELECT 1 FROM d WHERE id=$2)`, root, id).Scan(&allowed); err != nil { + return err + } + if !allowed { + return errors.New("updated category must be a descendant of the request root") + } + var channelList any + if patch.ChannelList != nil { + channelList = *patch.ChannelList + } + result, err := tx.ExecContext(ctx, `UPDATE product.product_category SET name=COALESCE($1,name),priority=COALESCE($2,priority),rule_id=COALESCE($3,rule_id),status=COALESCE($4,status),category_type=COALESCE($5,category_type),channel_list=CASE WHEN $6 THEN $7 ELSE channel_list END,has_children=COALESCE($8,has_children),has_prop_required=COALESCE($9,has_prop_required),extra=COALESCE($10,extra),cert_status_code=COALESCE($11,cert_status_code),cert_status_pass=COALESCE($12,cert_status_pass),cert_status_msg=COALESCE($13,cert_status_msg),version=version+1,updated_at=NOW() WHERE id=$14 AND version=$15 AND deleted_at IS NULL`, patch.Name, patch.Priority, patch.RuleID, patch.Status, patch.CategoryType, patch.ChannelList != nil, channelList, patch.HasChildren, patch.HasPropRequired, patch.Extra, patch.CertStatusCode, patch.CertStatusPass, patch.CertStatusMsg, id, patch.ExpectedVersion) + if err != nil { + return mapProductCategoryWriteError(err) + } + n, _ := result.RowsAffected() + if n == 0 { + return ErrProductCategoryVersionConflict + } + for _, child := range patch.Children { + if err := updateProductCategoryPatch(ctx, tx, root, child); err != nil { + return err + } + } + return nil } -func (r *ProductRepository) DeleteProductCategory(ctx context.Context, id string, expectedVersion int32, scope StoreScope) (*time.Time, error) { +func (r *ProductRepository) DeleteProductCategory(ctx context.Context, id string, expected int32) (*ProductCategoryDeleteResult, error) { parsed, err := parseID(id, "product_category_id") if err != nil { return nil, err @@ -344,40 +259,61 @@ func (r *ProductRepository) DeleteProductCategory(ctx context.Context, id string return nil, err } defer tx.Rollback() - var children, bindings int64 - if err := tx.QueryRowContext(ctx, `SELECT (SELECT COUNT(*) FROM product.product_category WHERE parent_id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL),(SELECT COUNT(*) FROM product.product_category_bindings WHERE product_category_id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, parsed, scope.TenantID, scope.StoreID).Scan(&children, &bindings); err != nil { - return nil, err - } - if children > 0 { - return nil, ErrProductCategoryHasChildren - } - if bindings > 0 { - return nil, ErrProductCategoryInUse - } - var deleted time.Time - err = tx.QueryRowContext(ctx, `UPDATE product.product_category SET deleted_at=NOW(),updated_at=NOW(),version=version+1 WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND version=$4 AND deleted_at IS NULL RETURNING deleted_at`, parsed, scope.TenantID, scope.StoreID, expectedVersion).Scan(&deleted) - if errors.Is(err, sql.ErrNoRows) { - var exists bool - _ = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, parsed, scope.TenantID, scope.StoreID).Scan(&exists) - if exists { - return nil, ErrProductCategoryVersionConflict - } + var version int32 + if err = tx.QueryRowContext(ctx, `SELECT version FROM product.product_category WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, parsed).Scan(&version); errors.Is(err, sql.ErrNoRows) { return nil, ErrProductCategoryNotFound } if err != nil { return nil, err } - if err := tx.Commit(); err != nil { + if version != expected { + return nil, ErrProductCategoryVersionConflict + } + rows, err := tx.QueryContext(ctx, `WITH RECURSIVE d AS (SELECT id FROM product.product_category WHERE id=$1 AND deleted_at IS NULL UNION ALL SELECT c.id FROM product.product_category c JOIN d ON c.parent_id=d.id WHERE c.deleted_at IS NULL) SELECT id FROM d ORDER BY id`, parsed) + if err != nil { return nil, err } - return &deleted, nil + var ids []int64 + for rows.Next() { + var v int64 + if err = rows.Scan(&v); err != nil { + rows.Close() + return nil, err + } + ids = append(ids, v) + } + rows.Close() + if err = rows.Err(); err != nil { + return nil, err + } + q, args := int64In("product_category_id", ids, 1) + var bindings, products int32 + if err = tx.QueryRowContext(ctx, `SELECT COUNT(*),COUNT(DISTINCT product_id) FROM product.product_category_bindings WHERE `+q+` AND deleted_at IS NULL`, args...).Scan(&bindings, &products); err != nil { + return nil, err + } + if _, err = tx.ExecContext(ctx, `UPDATE product.product_category_bindings SET deleted_at=NOW(),updated_at=NOW() WHERE `+q+` AND deleted_at IS NULL`, args...); err != nil { + return nil, err + } + q, args = int64In("id", ids, 1) + var deleted time.Time + if err = tx.QueryRowContext(ctx, `UPDATE product.product_category SET deleted_at=NOW(),updated_at=NOW(),version=version+1 WHERE `+q+` RETURNING deleted_at`, args...).Scan(&deleted); err != nil { + return nil, err + } + if err = tx.Commit(); err != nil { + return nil, err + } + out := make([]string, len(ids)) + for i, v := range ids { + out[i] = formatID(v) + } + return &ProductCategoryDeleteResult{CategoryIDs: out, CategoryCount: int32(len(ids)), BindingCount: bindings, ProductCount: products, DeletedAt: deleted}, nil } func (r *ProductRepository) BindProductsToProductCategory(ctx context.Context, categoryID string, bindingIDs, productIDs []string, scope StoreScope) (int32, int32, error) { if len(productIDs) == 0 { return 0, 0, errors.New("product_ids is required") } - parsedCategory, err := parseID(categoryID, "product_category_id") + category, err := parseID(categoryID, "product_category_id") if err != nil { return 0, 0, err } @@ -386,95 +322,98 @@ func (r *ProductRepository) BindProductsToProductCategory(ctx context.Context, c return 0, 0, err } defer tx.Rollback() - var leaf, statusValue int32 - err = tx.QueryRowContext(ctx, `SELECT CASE WHEN is_leaf THEN 1 ELSE 0 END,status FROM product.product_category WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL FOR UPDATE`, parsedCategory, scope.TenantID, scope.StoreID).Scan(&leaf, &statusValue) - if errors.Is(err, sql.ErrNoRows) { + var enabled bool + if err = tx.QueryRowContext(ctx, `SELECT status=1 AND NOT EXISTS(SELECT 1 FROM product.product_category child WHERE child.parent_id=c.id AND child.deleted_at IS NULL) FROM product.product_category c WHERE c.id=$1 AND c.deleted_at IS NULL FOR UPDATE`, category).Scan(&enabled); errors.Is(err, sql.ErrNoRows) { return 0, 0, ErrProductCategoryNotFound } if err != nil { return 0, 0, err } - if leaf != 1 || statusValue != 1 { - return 0, 0, errors.New("product category must be an enabled leaf") + if !enabled { + return 0, 0, errors.New("product category must be enabled and terminal") } var bound, already int32 - for i, productID := range productIDs { - product, err := parseID(productID, "product_id") - if err != nil { - return 0, 0, err + for i, raw := range productIDs { + product, e := parseID(raw, "product_id") + if e != nil { + return 0, 0, e } var exists bool - if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.products WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, product, scope.TenantID, scope.StoreID).Scan(&exists); err != nil { - return 0, 0, err + if e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.products WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, product, scope.TenantID, scope.StoreID).Scan(&exists); e != nil { + return 0, 0, e } if !exists { return 0, 0, ErrProductNotFound } var active bool - if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category_bindings WHERE product_id=$1 AND product_category_id=$2 AND deleted_at IS NULL)`, product, parsedCategory).Scan(&active); err != nil { - return 0, 0, err + if e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category_bindings WHERE product_id=$1 AND product_category_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, product, category, scope.StoreID).Scan(&active); e != nil { + return 0, 0, e } if active { already++ continue } - if _, err := tx.ExecContext(ctx, `UPDATE product.product_category_bindings SET deleted_at=NULL,updated_at=NOW() WHERE product_id=$1 AND product_category_id=$2 AND deleted_at IS NOT NULL`, product, parsedCategory); err != nil { - return 0, 0, err + if _, e = tx.ExecContext(ctx, `UPDATE product.product_category_bindings SET deleted_at=NULL,updated_at=NOW() WHERE product_id=$1 AND product_category_id=$2 AND store_id=$3 AND deleted_at IS NOT NULL`, product, category, scope.StoreID); e != nil { + return 0, 0, e } var restored bool - if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category_bindings WHERE product_id=$1 AND product_category_id=$2 AND deleted_at IS NULL)`, product, parsedCategory).Scan(&restored); err != nil { - return 0, 0, err + if e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category_bindings WHERE product_id=$1 AND product_category_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, product, category, scope.StoreID).Scan(&restored); e != nil { + return 0, 0, e } if !restored { - binding, err := parseID(bindingIDs[i], "product_category_binding_id") - if err != nil { - return 0, 0, err + binding, e := parseID(bindingIDs[i], "product_category_binding_id") + if e != nil { + return 0, 0, e } - if _, err := tx.ExecContext(ctx, `INSERT INTO product.product_category_bindings (id,tenant_id,store_id,product_id,product_category_id) VALUES ($1,$2,$3,$4,$5)`, binding, scope.TenantID, scope.StoreID, product, parsedCategory); err != nil { - return 0, 0, err + if _, e = tx.ExecContext(ctx, `INSERT INTO product.product_category_bindings(id,tenant_id,store_id,product_id,product_category_id) VALUES($1,$2,$3,$4,$5)`, binding, scope.TenantID, scope.StoreID, product, category); e != nil { + return 0, 0, e } } bound++ } - if err := tx.Commit(); err != nil { + if err = tx.Commit(); err != nil { return 0, 0, err } return bound, already, nil } - func (r *ProductRepository) UnbindProductsFromProductCategory(ctx context.Context, categoryID string, productIDs []string, scope StoreScope) (int32, error) { if err := requireWriteScope(scope); err != nil { return 0, err } - parsed, err := parseID(categoryID, "product_category_id") + category, err := parseID(categoryID, "product_category_id") if err != nil { return 0, err } var exists bool - if err := r.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, parsed, scope.TenantID, scope.StoreID).Scan(&exists); err != nil { + if err = r.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category WHERE id=$1 AND deleted_at IS NULL)`, category).Scan(&exists); err != nil { return 0, err } if !exists { return 0, ErrProductCategoryNotFound } var count int32 - for _, productID := range productIDs { - product, err := parseID(productID, "product_id") - if err != nil { - return 0, err + for _, raw := range productIDs { + product, e := parseID(raw, "product_id") + if e != nil { + return 0, e } - result, err := r.db.ExecContext(ctx, `UPDATE product.product_category_bindings SET deleted_at=NOW(),updated_at=NOW() WHERE product_id=$1 AND product_category_id=$2 AND tenant_id=$3 AND store_id=$4 AND deleted_at IS NULL`, product, parsed, scope.TenantID, scope.StoreID) - if err != nil { - return 0, err + var productExists bool + if e = r.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.products WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, product, scope.TenantID, scope.StoreID).Scan(&productExists); e != nil { + return 0, e } - affected, _ := result.RowsAffected() - count += int32(affected) + if !productExists { + return 0, ErrProductNotFound + } + result, e := r.db.ExecContext(ctx, `UPDATE product.product_category_bindings SET deleted_at=NOW(),updated_at=NOW() WHERE product_id=$1 AND product_category_id=$2 AND tenant_id=$3 AND store_id=$4 AND deleted_at IS NULL`, product, category, scope.TenantID, scope.StoreID) + if e != nil { + return 0, e + } + n, _ := result.RowsAffected() + count += int32(n) } return count, nil } -const productCategorySelect = `SELECT c.id,c.category_code,c.name,c.parent_id,c.level,c.is_leaf,c.sort_num,c.status,c.remark,c.version,c.created_at,c.updated_at,c.deleted_at,(SELECT COUNT(*) FROM product.product_category_bindings b WHERE b.product_category_id=c.id AND b.deleted_at IS NULL) FROM product.product_category c` - type productCategoryScanner interface{ Scan(...any) error } func scanProductCategory(row productCategoryScanner) (*ProductCategoryRecord, error) { @@ -482,7 +421,7 @@ func scanProductCategory(row productCategoryScanner) (*ProductCategoryRecord, er var parent sql.NullInt64 var deleted sql.NullTime value := &ProductCategoryRecord{} - if err := row.Scan(&id, &value.CategoryCode, &value.Name, &parent, &value.Level, &value.IsLeaf, &value.SortNum, &value.Status, &value.Remark, &value.Version, &value.CreatedAt, &value.UpdatedAt, &deleted, &value.ProductCount); err != nil { + if err := row.Scan(&id, &parent, &value.Level, &value.Name, &value.Priority, &value.RuleID, &value.Status, &value.CategoryType, &value.ChannelList, &value.HasChildren, &value.HasPropRequired, &value.Extra, &value.CertStatusCode, &value.CertStatusPass, &value.CertStatusMsg, &value.Version, &value.CreatedAt, &value.UpdatedAt, &deleted, &value.ProductCount); err != nil { return nil, err } value.ID = formatID(id.Int64) @@ -501,20 +440,27 @@ func sortProductCategoryTree(node *ProductCategoryRecord) { for _, child := range node.Children { sortProductCategoryTree(child) } - for i := 0; i < len(node.Children); i++ { - for j := i + 1; j < len(node.Children); j++ { - if node.Children[j].SortNum < node.Children[i].SortNum || (node.Children[j].SortNum == node.Children[i].SortNum && node.Children[j].ID < node.Children[i].ID) { - node.Children[i], node.Children[j] = node.Children[j], node.Children[i] - } + sort.Slice(node.Children, func(i, j int) bool { + if node.Children[i].Priority == node.Children[j].Priority { + return node.Children[i].ID < node.Children[j].ID } + return node.Children[i].Priority < node.Children[j].Priority + }) +} +func int64In(column string, values []int64, start int) (string, []any) { + parts := make([]string, len(values)) + args := make([]any, len(values)) + for i, value := range values { + parts[i] = fmt.Sprintf("$%d", start+i) + args[i] = value } + return column + " IN (" + strings.Join(parts, ",") + ")", args } func mapProductCategoryWriteError(err error) error { if err == nil { return nil } - var text = err.Error() - if strings.Contains(text, "uq_product_category_store_code_active") || strings.Contains(text, "uq_product_category_store_parent_name_active") { + if strings.Contains(err.Error(), "uq_product_category_active_parent_name") { return ErrDuplicateProductCategory } return err diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index fdbbe9b..f3675ee 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -407,27 +407,29 @@ ALTER TABLE product.catalog_category CREATE TABLE IF NOT EXISTS product.product_category ( id BIGINT PRIMARY KEY, - tenant_id BIGINT NOT NULL, - store_id BIGINT NOT NULL, - category_code VARCHAR(64) NOT NULL, - name VARCHAR(100) NOT NULL, parent_id BIGINT REFERENCES product.product_category(id) ON DELETE RESTRICT, - level SMALLINT NOT NULL CHECK (level BETWEEN 1 AND 4), - is_leaf BOOLEAN NOT NULL DEFAULT TRUE, - sort_num INTEGER NOT NULL DEFAULT 0, + level SMALLINT NOT NULL CHECK (level >= 1), + name VARCHAR(100) NOT NULL, + priority INTEGER NOT NULL DEFAULT 0, + rule_id VARCHAR(64) NOT NULL, status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), - remark VARCHAR(500) NOT NULL DEFAULT '', + category_type SMALLINT NOT NULL, + channel_list INTEGER[] NOT NULL DEFAULT '{}'::INTEGER[], + has_children BOOLEAN NOT NULL DEFAULT FALSE, + has_prop_required BOOLEAN NOT NULL DEFAULT FALSE, + extra TEXT NOT NULL DEFAULT '', + cert_status_code INTEGER NOT NULL, + cert_status_pass BOOLEAN NOT NULL DEFAULT FALSE, + cert_status_msg VARCHAR(500) NOT NULL DEFAULT '', version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), deleted_at TIMESTAMPTZ ); -CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_store_code_active - ON product.product_category (store_id, category_code) WHERE deleted_at IS NULL; -CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_store_parent_name_active - ON product.product_category (store_id, COALESCE(parent_id, 0), lower(btrim(name))) WHERE deleted_at IS NULL; -CREATE INDEX IF NOT EXISTS idx_product_category_store_parent_sort - ON product.product_category (store_id, parent_id, sort_num, id) WHERE deleted_at IS NULL; +CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_active_parent_name + ON product.product_category (COALESCE(parent_id, 0), lower(btrim(name))) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_product_category_active_parent_priority + ON product.product_category (parent_id, priority, id) WHERE deleted_at IS NULL; CREATE TABLE IF NOT EXISTS product.product_category_bindings ( id BIGINT PRIMARY KEY, @@ -1445,7 +1447,7 @@ func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, product return err } if _, duplicate := seenCategoryIDs[parsedLeafCategoryIDs[index]]; duplicate { - return errors.New("leaf_catalog_category_ids must not contain duplicates") + return errors.New("leaf_catalog_category_ids must not contain duplicates") } seenCategoryIDs[parsedLeafCategoryIDs[index]] = struct{}{} if _, err := parseID(bindingIDs[index], "category binding id"); err != nil { @@ -2850,16 +2852,12 @@ func productListWhere(filter ProductListFilter, scope StoreScope) (string, []any SELECT c.id FROM product.product_category c WHERE c.id = $%d - AND c.tenant_id = p.tenant_id - AND c.store_id = p.store_id AND c.deleted_at IS NULL UNION SELECT child.id FROM product.product_category child JOIN category_descendants parent ON child.parent_id = parent.id - WHERE child.tenant_id = p.tenant_id - AND child.store_id = p.store_id - AND child.deleted_at IS NULL + WHERE child.deleted_at IS NULL ) SELECT 1 FROM product.product_category_bindings pcb @@ -4311,7 +4309,6 @@ func nullString(raw string) sql.NullString { return sql.NullString{String: value, Valid: true} } - // PromoteDueScheduledSales sets due scheduled products to ON_SALE (status=2). func (r *ProductRepository) PromoteDueScheduledSales(ctx context.Context, now time.Time) (int64, error) { res, err := r.db.ExecContext(ctx, ` diff --git a/internal/server/product_category_server.go b/internal/server/product_category_server.go index 60ce373..d29cced 100644 --- a/internal/server/product_category_server.go +++ b/internal/server/product_category_server.go @@ -7,19 +7,15 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" ) +// Taxonomy nodes are global. StoreContext is used only when binding products. func (s *ProductServer) CreateProductCategory(ctx context.Context, req *productv1.CreateProductCategoryRequest) (*productv1.CreateProductCategoryResponse, error) { if req == nil || req.GetProductCategory() == nil { return nil, status.Error(codes.InvalidArgument, "product_category is required") } - scope, err := requireStoreScope(req) - if err != nil { - return nil, err - } if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") } @@ -30,7 +26,7 @@ func (s *ProductServer) CreateProductCategory(ctx context.Context, req *productv if err := assignProductCategoryIDs(root, s); err != nil { return nil, err } - created, err := s.repo.CreateProductCategory(ctx, root, scope) + created, err := s.repo.CreateProductCategory(ctx, root) if err != nil { return nil, productCategoryGRPCError(err) } @@ -41,14 +37,10 @@ func (s *ProductServer) GetProductCategory(ctx context.Context, req *productv1.G if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } - scope, err := requireStoreScope(req) - if err != nil { - return nil, err - } if _, err := parsePositiveID(req.GetProductCategoryId(), "product_category_id"); err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } - value, err := s.repo.GetProductCategory(ctx, req.GetProductCategoryId(), scope) + value, err := s.repo.GetProductCategory(ctx, req.GetProductCategoryId()) if err != nil { return nil, productCategoryGRPCError(err) } @@ -59,20 +51,13 @@ func (s *ProductServer) ListProductCategories(ctx context.Context, req *productv if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } - scope, err := requireStoreScope(req) - if err != nil { - return nil, err - } - page, size := normalizedPage(req.GetPage(), req.GetPageSize()) - var state *int32 - if req.Status != nil { - value := req.GetStatus() - if value != 0 && value != 1 { - return nil, status.Error(codes.InvalidArgument, "status must be 0 or 1") + id := strings.TrimSpace(req.GetProductCategoryId()) + if id != "" { + if _, err := parsePositiveID(id, "product_category_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) } - state = &value } - values, total, err := s.repo.ListProductCategories(ctx, repository.ProductCategoryListFilter{Keyword: strings.TrimSpace(req.GetKeyword()), Status: state, Page: page, PageSize: size}, scope) + values, err := s.repo.ListProductCategories(ctx, id) if err != nil { return nil, productCategoryGRPCError(err) } @@ -80,55 +65,21 @@ func (s *ProductServer) ListProductCategories(ctx context.Context, req *productv for _, value := range values { out = append(out, toProtoProductCategory(value)) } - return &productv1.ListProductCategoriesResponse{ProductCategories: out, Page: page, PageSize: size, Total: total, TotalPages: totalPages(total, size)}, nil + return &productv1.ListProductCategoriesResponse{ProductCategories: out}, nil } func (s *ProductServer) UpdateProductCategory(ctx context.Context, req *productv1.UpdateProductCategoryRequest) (*productv1.UpdateProductCategoryResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "request is required") + if req == nil || req.GetProductCategory() == nil { + return nil, status.Error(codes.InvalidArgument, "product_category is required") } - scope, err := requireStoreScope(req) + if req.GetProductCategoryId() != req.GetProductCategory().GetProductCategoryId() { + return nil, status.Error(codes.InvalidArgument, "product_category_id must equal the path ID") + } + patch, err := productCategoryPatchFromProto(req.GetProductCategory()) if err != nil { - return nil, err - } - if _, err := parsePositiveID(req.GetProductCategoryId(), "product_category_id"); err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } - if req.GetExpectedVersion() < 0 { - return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative") - } - patch := repository.ProductCategoryPatch{ExpectedVersion: req.GetExpectedVersion()} - if req.CategoryCode != nil { - value := strings.TrimSpace(req.GetCategoryCode()) - patch.CategoryCode = &value - } - if req.Name != nil { - value := strings.TrimSpace(req.GetName()) - patch.Name = &value - } - if req.ParentId != nil { - value := strings.TrimSpace(req.GetParentId()) - patch.ParentID = &value - } - if req.SortNum != nil { - value := req.GetSortNum() - patch.SortNum = &value - } - if req.Status != nil { - value := req.GetStatus() - if value != 0 && value != 1 { - return nil, status.Error(codes.InvalidArgument, "status must be 0 or 1") - } - patch.Status = &value - } - if req.Remark != nil { - value := strings.TrimSpace(req.GetRemark()) - patch.Remark = &value - } - if patch.CategoryCode == nil && patch.Name == nil && patch.ParentID == nil && patch.SortNum == nil && patch.Status == nil && patch.Remark == nil { - return nil, status.Error(codes.InvalidArgument, "at least one mutable field is required") - } - value, err := s.repo.UpdateProductCategory(ctx, req.GetProductCategoryId(), patch, scope) + value, err := s.repo.UpdateProductCategory(ctx, req.GetProductCategoryId(), patch) if err != nil { return nil, productCategoryGRPCError(err) } @@ -139,21 +90,23 @@ func (s *ProductServer) DeleteProductCategory(ctx context.Context, req *productv if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } - scope, err := requireStoreScope(req) - if err != nil { - return nil, err + if _, err := parsePositiveID(req.GetProductCategoryId(), "product_category_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) } - deleted, err := s.repo.DeleteProductCategory(ctx, req.GetProductCategoryId(), req.GetExpectedVersion(), scope) + result, err := s.repo.DeleteProductCategory(ctx, req.GetProductCategoryId(), req.GetExpectedVersion()) if err != nil { return nil, productCategoryGRPCError(err) } - return &productv1.DeleteProductCategoryResponse{DeletedProductCategoryId: req.GetProductCategoryId(), DeletedAt: deleted.Format("2006-01-02T15:04:05Z07:00")}, nil + return &productv1.DeleteProductCategoryResponse{DeletedProductCategoryIds: result.CategoryIDs, DeletedCategoryCount: result.CategoryCount, UnboundBindingCount: result.BindingCount, UnboundProductCount: result.ProductCount, DeletedAt: result.DeletedAt.Format("2006-01-02T15:04:05Z07:00")}, nil } func (s *ProductServer) BindProductsToProductCategory(ctx context.Context, req *productv1.BindProductsToProductCategoryRequest) (*productv1.BindProductsToProductCategoryResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } scope, err := requireStoreScope(req) if err != nil { return nil, err @@ -196,27 +149,26 @@ func (s *ProductServer) productCategoryFromCreate(input *productv1.CreateProduct if input == nil { return nil, errors.New("product category is required") } - code := strings.TrimSpace(input.GetCategoryCode()) - name := strings.TrimSpace(input.GetName()) - if code == "" || len(code) > 64 { - return nil, errors.New("category_code must contain between 1 and 64 characters") - } + name, ruleID := strings.TrimSpace(input.GetName()), strings.TrimSpace(input.GetRuleId()) if name == "" || len(name) > 100 { return nil, errors.New("name must contain between 1 and 100 characters") } + if ruleID == "" || len(ruleID) > 64 { + return nil, errors.New("rule_id must contain between 1 and 64 characters") + } + if input.GetStatus() != 0 && input.GetStatus() != 1 { + return nil, errors.New("status must be 0 or 1") + } + if len(input.GetCertStatusMsg()) > 500 { + return nil, errors.New("cert_status_msg must contain at most 500 characters") + } if !root && input.ParentId != nil { return nil, errors.New("children must not specify parent_id") } - value := &repository.ProductCategoryRecord{CategoryCode: code, Name: name, SortNum: input.GetSortNum(), Status: 1, StatusSet: true, Remark: strings.TrimSpace(input.GetRemark())} - if len(value.Remark) > 500 { - return nil, errors.New("remark must contain at most 500 characters") - } - if input.Status != nil { - value.Status = input.GetStatus() - if value.Status != 0 && value.Status != 1 { - return nil, errors.New("status must be 0 or 1") - } + if len(input.GetChildren()) > 0 && !input.GetHasChildren() { + return nil, errors.New("has_children must be true when children are supplied") } + value := &repository.ProductCategoryRecord{Name: name, RuleID: ruleID, Priority: input.GetPriority(), Status: input.GetStatus(), CategoryType: input.GetCategoryType(), ChannelList: input.GetChannelList(), HasChildren: input.GetHasChildren(), HasPropRequired: input.GetHasPropRequired(), Extra: input.GetExtra(), CertStatusCode: input.GetCertStatusCode(), CertStatusPass: input.GetCertStatusPass(), CertStatusMsg: input.GetCertStatusMsg()} if input.ParentId != nil { value.ParentID = strings.TrimSpace(input.GetParentId()) } @@ -229,9 +181,43 @@ func (s *ProductServer) productCategoryFromCreate(input *productv1.CreateProduct } return value, nil } + +func productCategoryPatchFromProto(input *productv1.ProductCategoryPatch) (*repository.ProductCategoryPatch, error) { + if input == nil || strings.TrimSpace(input.GetProductCategoryId()) == "" { + return nil, errors.New("product_category_id is required") + } + if input.GetExpectedVersion() < 0 { + return nil, errors.New("expected_version must be non-negative") + } + if input.Name != nil && (strings.TrimSpace(input.GetName()) == "" || len(strings.TrimSpace(input.GetName())) > 100) { + return nil, errors.New("name must contain between 1 and 100 characters") + } + if input.RuleId != nil && (strings.TrimSpace(input.GetRuleId()) == "" || len(strings.TrimSpace(input.GetRuleId())) > 64) { + return nil, errors.New("rule_id must contain between 1 and 64 characters") + } + if input.Status != nil && input.GetStatus() != 0 && input.GetStatus() != 1 { + return nil, errors.New("status must be 0 or 1") + } + if input.CertStatusMsg != nil && len(input.GetCertStatusMsg()) > 500 { + return nil, errors.New("cert_status_msg must contain at most 500 characters") + } + patch := &repository.ProductCategoryPatch{ID: strings.TrimSpace(input.GetProductCategoryId()), ExpectedVersion: input.GetExpectedVersion(), Name: input.Name, Priority: input.Priority, RuleID: input.RuleId, Status: input.Status, CategoryType: input.CategoryType, HasChildren: input.HasChildren, HasPropRequired: input.HasPropRequired, Extra: input.Extra, CertStatusCode: input.CertStatusCode, CertStatusPass: input.CertStatusPass, CertStatusMsg: input.CertStatusMsg} + if input.ChannelList != nil { + patch.ChannelList = &input.ChannelList + } + for _, child := range input.GetChildren() { + item, err := productCategoryPatchFromProto(child) + if err != nil { + return nil, err + } + patch.Children = append(patch.Children, item) + } + return patch, nil +} + func assignProductCategoryIDs(node *repository.ProductCategoryRecord, s *ProductServer) error { if node == nil { - return nil + return errors.New("product category is required") } node.ID = s.idgen.NextString() for _, child := range node.Children { @@ -241,11 +227,12 @@ func assignProductCategoryIDs(node *repository.ProductCategoryRecord, s *Product } return nil } + func toProtoProductCategory(value *repository.ProductCategoryRecord) *productv1.ProductCategory { if value == nil { return nil } - out := &productv1.ProductCategory{ProductCategoryId: value.ID, CategoryCode: value.CategoryCode, Name: value.Name, Level: value.Level, IsLeaf: value.IsLeaf, SortNum: value.SortNum, Status: value.Status, Remark: value.Remark, Version: value.Version, CreatedAt: value.CreatedAt.Format("2006-01-02T15:04:05Z07:00"), UpdatedAt: value.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"), ProductCount: value.ProductCount} + out := &productv1.ProductCategory{ProductCategoryId: value.ID, Name: value.Name, Level: value.Level, Priority: value.Priority, RuleId: value.RuleID, Status: value.Status, CategoryType: value.CategoryType, ChannelList: value.ChannelList, HasChildren: value.HasChildren, HasPropRequired: value.HasPropRequired, Extra: value.Extra, CertStatusCode: value.CertStatusCode, CertStatusPass: value.CertStatusPass, CertStatusMsg: value.CertStatusMsg, Version: value.Version, CreatedAt: value.CreatedAt.Format("2006-01-02T15:04:05Z07:00"), UpdatedAt: value.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"), ProductCount: value.ProductCount} if value.ParentID != "" { out.ParentId = &value.ParentID } @@ -258,6 +245,7 @@ func toProtoProductCategory(value *repository.ProductCategoryRecord) *productv1. } return out } + func productCategoryGRPCError(err error) error { switch { case errors.Is(err, repository.ErrProductCategoryNotFound): @@ -265,9 +253,7 @@ func productCategoryGRPCError(err error) error { case errors.Is(err, repository.ErrProductCategoryVersionConflict): return status.Error(codes.Aborted, "product category version conflict") case errors.Is(err, repository.ErrDuplicateProductCategory): - return status.Error(codes.AlreadyExists, "product category code or sibling name already exists") - case errors.Is(err, repository.ErrProductCategoryHasChildren), errors.Is(err, repository.ErrProductCategoryInUse): - return status.Error(codes.FailedPrecondition, err.Error()) + return status.Error(codes.AlreadyExists, "duplicate product category name") default: return status.Error(codes.InvalidArgument, err.Error()) } diff --git a/scripts/sql/006_rebuild_standard_product_category_tree.sql b/scripts/sql/006_rebuild_standard_product_category_tree.sql new file mode 100644 index 0000000..68f2976 --- /dev/null +++ b/scripts/sql/006_rebuild_standard_product_category_tree.sql @@ -0,0 +1,82 @@ +-- Rebuild product.product_category as the global standard product taxonomy. +-- +-- DESTRUCTIVE: this script permanently removes every legacy store-scoped +-- product category and every product-category binding. Product, SKU, catalog +-- category, and product-group data are not removed. Run during a maintenance +-- window, after taking a database backup, and before importing the new tree. + +BEGIN; + +DROP TABLE IF EXISTS product.product_category_bindings; +DROP TABLE IF EXISTS product.product_category; + +CREATE TABLE product.product_category ( + id BIGINT PRIMARY KEY, + parent_id BIGINT REFERENCES product.product_category(id) ON DELETE RESTRICT, + level SMALLINT NOT NULL CHECK (level >= 1), + name VARCHAR(100) NOT NULL, + priority INTEGER NOT NULL DEFAULT 0, + rule_id VARCHAR(64) NOT NULL, + status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), + category_type SMALLINT NOT NULL, + channel_list INTEGER[] NOT NULL DEFAULT '{}'::INTEGER[], + has_children BOOLEAN NOT NULL DEFAULT FALSE, + has_prop_required BOOLEAN NOT NULL DEFAULT FALSE, + extra TEXT NOT NULL DEFAULT '', + cert_status_code INTEGER NOT NULL, + cert_status_pass BOOLEAN NOT NULL DEFAULT FALSE, + cert_status_msg VARCHAR(500) NOT NULL DEFAULT '', + version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ, + CONSTRAINT chk_product_category_hierarchy CHECK ( + (parent_id IS NULL AND level = 1) + OR (parent_id IS NOT NULL AND level > 1) + ) +); + +CREATE INDEX idx_product_category_active_parent_priority + ON product.product_category (parent_id, priority, id) + WHERE deleted_at IS NULL; +CREATE INDEX idx_product_category_active_status_parent_priority + ON product.product_category (status, parent_id, priority, id) + WHERE deleted_at IS NULL; +CREATE INDEX idx_product_category_rule_id + ON product.product_category (rule_id) + WHERE deleted_at IS NULL; +CREATE INDEX idx_product_category_channel_list + ON product.product_category USING GIN (channel_list); + +CREATE TABLE product.product_category_bindings ( + id BIGINT PRIMARY KEY, + tenant_id BIGINT NOT NULL, + store_id BIGINT NOT NULL, + product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, + product_category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE RESTRICT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); + +CREATE UNIQUE INDEX uq_product_category_bindings_active + ON product.product_category_bindings (product_id, product_category_id) + WHERE deleted_at IS NULL; +CREATE INDEX idx_product_category_bindings_category + ON product.product_category_bindings (store_id, product_category_id) + WHERE deleted_at IS NULL; +CREATE INDEX idx_product_category_bindings_product + ON product.product_category_bindings (store_id, product_id) + WHERE deleted_at IS NULL; + +DROP TRIGGER IF EXISTS set_product_category_updated_at ON product.product_category; +CREATE TRIGGER set_product_category_updated_at + BEFORE UPDATE ON product.product_category + FOR EACH ROW EXECUTE FUNCTION public.set_updated_at(); + +DROP TRIGGER IF EXISTS set_product_category_bindings_updated_at ON product.product_category_bindings; +CREATE TRIGGER set_product_category_bindings_updated_at + BEFORE UPDATE ON product.product_category_bindings + FOR EACH ROW EXECUTE FUNCTION public.set_updated_at(); + +COMMIT;