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.
This commit is contained in:
BXY 2026-10-08 14:56:54 +08:00
parent bfb87e771f
commit 6f6887f0d2
4 changed files with 382 additions and 371 deletions

View File

@ -5,6 +5,7 @@ import (
"database/sql" "database/sql"
"errors" "errors"
"fmt" "fmt"
"sort"
"strings" "strings"
"time" "time"
) )
@ -12,18 +13,14 @@ import (
var ( var (
ErrProductCategoryNotFound = errors.New("product category not found") ErrProductCategoryNotFound = errors.New("product category not found")
ErrProductCategoryVersionConflict = errors.New("product category version conflict") ErrProductCategoryVersionConflict = errors.New("product category version conflict")
ErrProductCategoryHasChildren = errors.New("product category has children") ErrDuplicateProductCategory = errors.New("duplicate product category name")
ErrProductCategoryInUse = errors.New("product category is bound to products")
ErrDuplicateProductCategory = errors.New("product category code or sibling name already exists")
) )
// ProductCategoryRecord is the standard product taxonomy node. It is distinct
// from CatalogCategoryRecord (the storefront classification tree).
type ProductCategoryRecord struct { type ProductCategoryRecord struct {
ID, CategoryCode, Name, ParentID, Remark string ID, Name, ParentID, RuleID, Extra, CertStatusMsg string
Level, SortNum, Status, Version int32 Level, Priority, Status, CategoryType, CertStatusCode, Version int32
StatusSet bool ChannelList []int32
IsLeaf bool HasChildren, HasPropRequired, CertStatusPass bool
ProductCount int64 ProductCount int64
CreatedAt, UpdatedAt time.Time CreatedAt, UpdatedAt time.Time
DeletedAt *time.Time DeletedAt *time.Time
@ -31,40 +28,31 @@ type ProductCategoryRecord struct {
} }
type ProductCategoryPatch struct { type ProductCategoryPatch struct {
CategoryCode, Name, ParentID, Remark *string ID string
SortNum, Status *int32
ExpectedVersion int32 ExpectedVersion int32
Name, RuleID, Extra, CertStatusMsg *string
Priority, Status, CategoryType, CertStatusCode *int32
ChannelList *[]int32
HasChildren, HasPropRequired, CertStatusPass *bool
Children []*ProductCategoryPatch
} }
type ProductCategoryListFilter struct { type ProductCategoryDeleteResult struct {
Keyword string CategoryIDs []string
Status *int32 CategoryCount, BindingCount, ProductCount int32
Page, PageSize 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 { func (r *ProductRepository) ValidateProductCategory(ctx context.Context, categoryID string, scope StoreScope) error {
if err := requireWriteScope(scope); err != nil { if err := requireWriteScope(scope); err != nil {
return err return err
} }
parsed, err := parseID(categoryID, "category_id") id, err := parseID(categoryID, "category_id")
if err != nil { if err != nil {
return err return err
} }
var exists bool var exists bool
err = r.db.QueryRowContext(ctx, ` 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 {
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 {
return fmt.Errorf("validate product category: %w", err) return fmt.Errorf("validate product category: %w", err)
} }
if !exists { if !exists {
@ -73,168 +61,119 @@ SELECT EXISTS(
return nil return nil
} }
func (r *ProductRepository) CreateProductCategory(ctx context.Context, root *ProductCategoryRecord, scope StoreScope) (*ProductCategoryRecord, error) { func (r *ProductRepository) CreateProductCategory(ctx context.Context, root *ProductCategoryRecord) (*ProductCategoryRecord, error) {
if root == nil || !scope.Valid() { if root == nil {
return nil, errors.New("product category and store scope are required") return nil, errors.New("product category is required")
} }
tx, err := r.db.BeginTx(ctx, nil) tx, err := r.db.BeginTx(ctx, nil)
if err != nil { if err != nil {
return nil, fmt.Errorf("begin create product category: %w", err) return nil, err
} }
defer tx.Rollback() defer tx.Rollback()
created, err := createProductCategoryNode(ctx, tx, root, root.ParentID, scope) created, err := createProductCategoryNode(ctx, tx, root, root.ParentID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err := tx.Commit(); err != nil { if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit create product category: %w", err) return nil, err
} }
return created, nil return created, nil
} }
func createProductCategoryNode(ctx context.Context, tx *sql.Tx, input *ProductCategoryRecord, parentID string, scope StoreScope) (*ProductCategoryRecord, error) { func createProductCategoryNode(ctx context.Context, tx *sql.Tx, input *ProductCategoryRecord, parentID string) (*ProductCategoryRecord, error) {
if input == nil {
return nil, errors.New("product category is required")
}
level := int32(1) level := int32(1)
parent := sql.NullInt64{} parent := sql.NullInt64{}
if strings.TrimSpace(parentID) != "" { if strings.TrimSpace(parentID) != "" {
parsed, err := parseID(parentID, "parent_id") id, err := parseID(parentID, "parent_id")
if err != nil { if err != nil {
return nil, err return nil, err
} }
var parentLevel int32 var parentLevel int32
var parentStatus int32 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) {
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) {
return nil, ErrProductCategoryNotFound return nil, ErrProductCategoryNotFound
} else if err != nil {
return nil, err
} }
if err != nil { parent = sql.NullInt64{Int64: id, Valid: true}
return nil, fmt.Errorf("load product category parent: %w", err)
}
if parentStatus != 1 {
return nil, errors.New("parent product category must be enabled")
}
level = parentLevel + 1 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") id, err := parseID(input.ID, "product_category_id")
if err != nil { if err != nil {
return nil, err return nil, err
} }
statusValue := input.Status 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)
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)
created, err := scanProductCategory(row) created, err := scanProductCategory(row)
if err != nil { if err != nil {
return nil, mapProductCategoryWriteError(err) return nil, mapProductCategoryWriteError(err)
} }
for _, child := range input.Children { 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 { if err != nil {
return nil, err return nil, err
} }
created.Children = append(created.Children, createdChild) created.Children = append(created.Children, value)
}
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++
} }
return created, nil return created, nil
} }
func (r *ProductRepository) ListProductCategories(ctx context.Context, filter ProductCategoryListFilter, scope StoreScope) ([]*ProductCategoryRecord, int64, error) { func (r *ProductRepository) ListProductCategories(ctx context.Context, id string) ([]*ProductCategoryRecord, error) {
if !scope.Valid() { if id != "" {
return nil, 0, errors.New("store scope is required") node, err := r.GetProductCategory(ctx, id)
}
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...)
if err != nil { if err != nil {
return nil, 0, err return nil, err
}
return []*ProductCategoryRecord{node}, nil
}
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, err
} }
defer rows.Close() defer rows.Close()
rootIDs := []string{} var out []*ProductCategoryRecord
for rows.Next() { for rows.Next() {
var id int64 var raw int64
if err := rows.Scan(&id); err != nil { if err := rows.Scan(&raw); err != nil {
return nil, 0, err return nil, err
} }
rootIDs = append(rootIDs, formatID(id)) node, err := r.GetProductCategory(ctx, formatID(raw))
}
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)
if err != nil { 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) { func (r *ProductRepository) GetProductCategory(ctx context.Context, id string) (*ProductCategoryRecord, error) {
return r.loadProductCategoryTree(ctx, id, scope) 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") parsed, err := parseID(id, "product_category_id")
if err != nil { if err != nil {
return nil, err 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(r.db.QueryRowContext(ctx, `SELECT `+productCategoryColumns+` FROM product.product_category c WHERE c.id=$1 AND c.deleted_at IS NULL`, parsed))
root, err := scanProductCategory(row)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
return nil, ErrProductCategoryNotFound return nil, ErrProductCategoryNotFound
} }
if err != nil { if err != nil {
return nil, err return nil, err
} }
rows, err := r.db.QueryContext(ctx, `WITH RECURSIVE descendants AS ( 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)
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)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close()
byID := map[string]*ProductCategoryRecord{root.ID: root} byID := map[string]*ProductCategoryRecord{root.ID: root}
for rows.Next() { for rows.Next() {
child, err := scanProductCategory(rows) node, e := scanProductCategory(rows)
if err != nil { if e != nil {
return nil, err return nil, e
} }
byID[child.ID] = child byID[node.ID] = node
} }
if err := rows.Err(); err != nil { if err := rows.Err(); err != nil {
return nil, err return nil, err
@ -250,91 +189,67 @@ func (r *ProductRepository) loadProductCategoryTree(ctx context.Context, id stri
return root, nil return root, nil
} }
func (r *ProductRepository) UpdateProductCategory(ctx context.Context, id string, patch ProductCategoryPatch, scope StoreScope) (*ProductCategoryRecord, error) { func (r *ProductRepository) UpdateProductCategory(ctx context.Context, rootID string, patch *ProductCategoryPatch) (*ProductCategoryRecord, error) {
parsed, err := parseID(id, "product_category_id") if patch == nil {
if err != nil { return nil, errors.New("product category patch is required")
return nil, err
} }
tx, err := r.db.BeginTx(ctx, nil) tx, err := r.db.BeginTx(ctx, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer tx.Rollback() defer tx.Rollback()
var oldLevel int32 root, err := parseID(rootID, "product_category_id")
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 err != nil {
if errors.Is(err, sql.ErrNoRows) { return nil, err
}
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
}
if !exists {
return nil, ErrProductCategoryNotFound return nil, ErrProductCategoryNotFound
} }
if err != nil { if err := updateProductCategoryPatch(ctx, tx, root, patch); err != nil {
return nil, err 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")
}
}
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)
}
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 := tx.Commit(); err != nil { if err := tx.Commit(); err != nil {
return nil, err 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") parsed, err := parseID(id, "product_category_id")
if err != nil { if err != nil {
return nil, err return nil, err
@ -344,40 +259,61 @@ func (r *ProductRepository) DeleteProductCategory(ctx context.Context, id string
return nil, err return nil, err
} }
defer tx.Rollback() defer tx.Rollback()
var children, bindings int64 var version int32
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 { 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, 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
}
return nil, ErrProductCategoryNotFound return nil, ErrProductCategoryNotFound
} }
if err != nil { if err != nil {
return nil, err 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 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) { func (r *ProductRepository) BindProductsToProductCategory(ctx context.Context, categoryID string, bindingIDs, productIDs []string, scope StoreScope) (int32, int32, error) {
if len(productIDs) == 0 { if len(productIDs) == 0 {
return 0, 0, errors.New("product_ids is required") 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 { if err != nil {
return 0, 0, err return 0, 0, err
} }
@ -386,95 +322,98 @@ func (r *ProductRepository) BindProductsToProductCategory(ctx context.Context, c
return 0, 0, err return 0, 0, err
} }
defer tx.Rollback() defer tx.Rollback()
var leaf, statusValue int32 var enabled bool
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 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) {
if errors.Is(err, sql.ErrNoRows) {
return 0, 0, ErrProductCategoryNotFound return 0, 0, ErrProductCategoryNotFound
} }
if err != nil { if err != nil {
return 0, 0, err return 0, 0, err
} }
if leaf != 1 || statusValue != 1 { if !enabled {
return 0, 0, errors.New("product category must be an enabled leaf") return 0, 0, errors.New("product category must be enabled and terminal")
} }
var bound, already int32 var bound, already int32
for i, productID := range productIDs { for i, raw := range productIDs {
product, err := parseID(productID, "product_id") product, e := parseID(raw, "product_id")
if err != nil { if e != nil {
return 0, 0, err return 0, 0, e
} }
var exists bool 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 { 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, err return 0, 0, e
} }
if !exists { if !exists {
return 0, 0, ErrProductNotFound return 0, 0, ErrProductNotFound
} }
var active bool 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 { 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, err return 0, 0, e
} }
if active { if active {
already++ already++
continue 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 { 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, err return 0, 0, e
} }
var restored bool 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 { 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, err return 0, 0, e
} }
if !restored { if !restored {
binding, err := parseID(bindingIDs[i], "product_category_binding_id") binding, e := parseID(bindingIDs[i], "product_category_binding_id")
if err != nil { if e != nil {
return 0, 0, err 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 { 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, err return 0, 0, e
} }
} }
bound++ bound++
} }
if err := tx.Commit(); err != nil { if err = tx.Commit(); err != nil {
return 0, 0, err return 0, 0, err
} }
return bound, already, nil return bound, already, nil
} }
func (r *ProductRepository) UnbindProductsFromProductCategory(ctx context.Context, categoryID string, productIDs []string, scope StoreScope) (int32, error) { func (r *ProductRepository) UnbindProductsFromProductCategory(ctx context.Context, categoryID string, productIDs []string, scope StoreScope) (int32, error) {
if err := requireWriteScope(scope); err != nil { if err := requireWriteScope(scope); err != nil {
return 0, err return 0, err
} }
parsed, err := parseID(categoryID, "product_category_id") category, err := parseID(categoryID, "product_category_id")
if err != nil { if err != nil {
return 0, err return 0, err
} }
var exists bool 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 return 0, err
} }
if !exists { if !exists {
return 0, ErrProductCategoryNotFound return 0, ErrProductCategoryNotFound
} }
var count int32 var count int32
for _, productID := range productIDs { for _, raw := range productIDs {
product, err := parseID(productID, "product_id") product, e := parseID(raw, "product_id")
if err != nil { if e != nil {
return 0, err 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) var productExists bool
if err != nil { 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, err return 0, e
} }
affected, _ := result.RowsAffected() if !productExists {
count += int32(affected) 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 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 } type productCategoryScanner interface{ Scan(...any) error }
func scanProductCategory(row productCategoryScanner) (*ProductCategoryRecord, error) { func scanProductCategory(row productCategoryScanner) (*ProductCategoryRecord, error) {
@ -482,7 +421,7 @@ func scanProductCategory(row productCategoryScanner) (*ProductCategoryRecord, er
var parent sql.NullInt64 var parent sql.NullInt64
var deleted sql.NullTime var deleted sql.NullTime
value := &ProductCategoryRecord{} 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 return nil, err
} }
value.ID = formatID(id.Int64) value.ID = formatID(id.Int64)
@ -501,20 +440,27 @@ func sortProductCategoryTree(node *ProductCategoryRecord) {
for _, child := range node.Children { for _, child := range node.Children {
sortProductCategoryTree(child) sortProductCategoryTree(child)
} }
for i := 0; i < len(node.Children); i++ { sort.Slice(node.Children, func(i, j int) bool {
for j := i + 1; j < len(node.Children); j++ { if node.Children[i].Priority == node.Children[j].Priority {
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) { return node.Children[i].ID < node.Children[j].ID
node.Children[i], node.Children[j] = node.Children[j], node.Children[i]
} }
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 { func mapProductCategoryWriteError(err error) error {
if err == nil { if err == nil {
return nil return nil
} }
var text = err.Error() if strings.Contains(err.Error(), "uq_product_category_active_parent_name") {
if strings.Contains(text, "uq_product_category_store_code_active") || strings.Contains(text, "uq_product_category_store_parent_name_active") {
return ErrDuplicateProductCategory return ErrDuplicateProductCategory
} }
return err return err

View File

@ -407,27 +407,29 @@ ALTER TABLE product.catalog_category
CREATE TABLE IF NOT EXISTS product.product_category ( CREATE TABLE IF NOT EXISTS product.product_category (
id BIGINT PRIMARY KEY, 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, parent_id BIGINT REFERENCES product.product_category(id) ON DELETE RESTRICT,
level SMALLINT NOT NULL CHECK (level BETWEEN 1 AND 4), level SMALLINT NOT NULL CHECK (level >= 1),
is_leaf BOOLEAN NOT NULL DEFAULT TRUE, name VARCHAR(100) NOT NULL,
sort_num INTEGER NOT NULL DEFAULT 0, priority INTEGER NOT NULL DEFAULT 0,
rule_id VARCHAR(64) NOT NULL,
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), 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), version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
deleted_at TIMESTAMPTZ deleted_at TIMESTAMPTZ
); );
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_store_code_active CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_active_parent_name
ON product.product_category (store_id, category_code) WHERE deleted_at IS NULL; ON product.product_category (COALESCE(parent_id, 0), lower(btrim(name))) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_store_parent_name_active CREATE INDEX IF NOT EXISTS idx_product_category_active_parent_priority
ON product.product_category (store_id, COALESCE(parent_id, 0), lower(btrim(name))) WHERE deleted_at IS NULL; ON product.product_category (parent_id, priority, id) 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 TABLE IF NOT EXISTS product.product_category_bindings ( CREATE TABLE IF NOT EXISTS product.product_category_bindings (
id BIGINT PRIMARY KEY, id BIGINT PRIMARY KEY,
@ -2850,16 +2852,12 @@ func productListWhere(filter ProductListFilter, scope StoreScope) (string, []any
SELECT c.id SELECT c.id
FROM product.product_category c FROM product.product_category c
WHERE c.id = $%d WHERE c.id = $%d
AND c.tenant_id = p.tenant_id
AND c.store_id = p.store_id
AND c.deleted_at IS NULL AND c.deleted_at IS NULL
UNION UNION
SELECT child.id SELECT child.id
FROM product.product_category child FROM product.product_category child
JOIN category_descendants parent ON child.parent_id = parent.id JOIN category_descendants parent ON child.parent_id = parent.id
WHERE child.tenant_id = p.tenant_id WHERE child.deleted_at IS NULL
AND child.store_id = p.store_id
AND child.deleted_at IS NULL
) )
SELECT 1 SELECT 1
FROM product.product_category_bindings pcb FROM product.product_category_bindings pcb
@ -4311,7 +4309,6 @@ func nullString(raw string) sql.NullString {
return sql.NullString{String: value, Valid: true} return sql.NullString{String: value, Valid: true}
} }
// PromoteDueScheduledSales sets due scheduled products to ON_SALE (status=2). // PromoteDueScheduledSales sets due scheduled products to ON_SALE (status=2).
func (r *ProductRepository) PromoteDueScheduledSales(ctx context.Context, now time.Time) (int64, error) { func (r *ProductRepository) PromoteDueScheduledSales(ctx context.Context, now time.Time) (int64, error) {
res, err := r.db.ExecContext(ctx, ` res, err := r.db.ExecContext(ctx, `

View File

@ -7,19 +7,15 @@ import (
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" "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) { func (s *ProductServer) CreateProductCategory(ctx context.Context, req *productv1.CreateProductCategoryRequest) (*productv1.CreateProductCategoryResponse, error) {
if req == nil || req.GetProductCategory() == nil { if req == nil || req.GetProductCategory() == nil {
return nil, status.Error(codes.InvalidArgument, "product_category is required") return nil, status.Error(codes.InvalidArgument, "product_category is required")
} }
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if s.idgen == nil { if s.idgen == nil {
return nil, status.Error(codes.Internal, "id generator is not configured") 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 { if err := assignProductCategoryIDs(root, s); err != nil {
return nil, err return nil, err
} }
created, err := s.repo.CreateProductCategory(ctx, root, scope) created, err := s.repo.CreateProductCategory(ctx, root)
if err != nil { if err != nil {
return nil, productCategoryGRPCError(err) return nil, productCategoryGRPCError(err)
} }
@ -41,14 +37,10 @@ func (s *ProductServer) GetProductCategory(ctx context.Context, req *productv1.G
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") 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 { if _, err := parsePositiveID(req.GetProductCategoryId(), "product_category_id"); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error()) 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 { if err != nil {
return nil, productCategoryGRPCError(err) return nil, productCategoryGRPCError(err)
} }
@ -59,20 +51,13 @@ func (s *ProductServer) ListProductCategories(ctx context.Context, req *productv
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") return nil, status.Error(codes.InvalidArgument, "request is required")
} }
scope, err := requireStoreScope(req) id := strings.TrimSpace(req.GetProductCategoryId())
if err != nil { if id != "" {
return nil, err if _, err := parsePositiveID(id, "product_category_id"); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
} }
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")
} }
state = &value values, err := s.repo.ListProductCategories(ctx, id)
}
values, total, err := s.repo.ListProductCategories(ctx, repository.ProductCategoryListFilter{Keyword: strings.TrimSpace(req.GetKeyword()), Status: state, Page: page, PageSize: size}, scope)
if err != nil { if err != nil {
return nil, productCategoryGRPCError(err) return nil, productCategoryGRPCError(err)
} }
@ -80,55 +65,21 @@ func (s *ProductServer) ListProductCategories(ctx context.Context, req *productv
for _, value := range values { for _, value := range values {
out = append(out, toProtoProductCategory(value)) 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) { func (s *ProductServer) UpdateProductCategory(ctx context.Context, req *productv1.UpdateProductCategoryRequest) (*productv1.UpdateProductCategoryResponse, error) {
if req == nil { if req == nil || req.GetProductCategory() == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") 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 { if err != nil {
return nil, err
}
if _, err := parsePositiveID(req.GetProductCategoryId(), "product_category_id"); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error()) return nil, status.Error(codes.InvalidArgument, err.Error())
} }
if req.GetExpectedVersion() < 0 { value, err := s.repo.UpdateProductCategory(ctx, req.GetProductCategoryId(), patch)
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)
if err != nil { if err != nil {
return nil, productCategoryGRPCError(err) return nil, productCategoryGRPCError(err)
} }
@ -139,21 +90,23 @@ func (s *ProductServer) DeleteProductCategory(ctx context.Context, req *productv
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") return nil, status.Error(codes.InvalidArgument, "request is required")
} }
scope, err := requireStoreScope(req) if _, err := parsePositiveID(req.GetProductCategoryId(), "product_category_id"); err != nil {
if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error())
return nil, err
} }
deleted, err := s.repo.DeleteProductCategory(ctx, req.GetProductCategoryId(), req.GetExpectedVersion(), scope) result, err := s.repo.DeleteProductCategory(ctx, req.GetProductCategoryId(), req.GetExpectedVersion())
if err != nil { if err != nil {
return nil, productCategoryGRPCError(err) 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) { func (s *ProductServer) BindProductsToProductCategory(ctx context.Context, req *productv1.BindProductsToProductCategoryRequest) (*productv1.BindProductsToProductCategoryResponse, error) {
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") 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) scope, err := requireStoreScope(req)
if err != nil { if err != nil {
return nil, err return nil, err
@ -196,27 +149,26 @@ func (s *ProductServer) productCategoryFromCreate(input *productv1.CreateProduct
if input == nil { if input == nil {
return nil, errors.New("product category is required") return nil, errors.New("product category is required")
} }
code := strings.TrimSpace(input.GetCategoryCode()) name, ruleID := strings.TrimSpace(input.GetName()), strings.TrimSpace(input.GetRuleId())
name := strings.TrimSpace(input.GetName())
if code == "" || len(code) > 64 {
return nil, errors.New("category_code must contain between 1 and 64 characters")
}
if name == "" || len(name) > 100 { if name == "" || len(name) > 100 {
return nil, errors.New("name must contain between 1 and 100 characters") 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 { if !root && input.ParentId != nil {
return nil, errors.New("children must not specify parent_id") 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(input.GetChildren()) > 0 && !input.GetHasChildren() {
if len(value.Remark) > 500 { return nil, errors.New("has_children must be true when children are supplied")
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")
}
} }
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 { if input.ParentId != nil {
value.ParentID = strings.TrimSpace(input.GetParentId()) value.ParentID = strings.TrimSpace(input.GetParentId())
} }
@ -229,9 +181,43 @@ func (s *ProductServer) productCategoryFromCreate(input *productv1.CreateProduct
} }
return value, nil 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 { func assignProductCategoryIDs(node *repository.ProductCategoryRecord, s *ProductServer) error {
if node == nil { if node == nil {
return nil return errors.New("product category is required")
} }
node.ID = s.idgen.NextString() node.ID = s.idgen.NextString()
for _, child := range node.Children { for _, child := range node.Children {
@ -241,11 +227,12 @@ func assignProductCategoryIDs(node *repository.ProductCategoryRecord, s *Product
} }
return nil return nil
} }
func toProtoProductCategory(value *repository.ProductCategoryRecord) *productv1.ProductCategory { func toProtoProductCategory(value *repository.ProductCategoryRecord) *productv1.ProductCategory {
if value == nil { if value == nil {
return 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 != "" { if value.ParentID != "" {
out.ParentId = &value.ParentID out.ParentId = &value.ParentID
} }
@ -258,6 +245,7 @@ func toProtoProductCategory(value *repository.ProductCategoryRecord) *productv1.
} }
return out return out
} }
func productCategoryGRPCError(err error) error { func productCategoryGRPCError(err error) error {
switch { switch {
case errors.Is(err, repository.ErrProductCategoryNotFound): case errors.Is(err, repository.ErrProductCategoryNotFound):
@ -265,9 +253,7 @@ func productCategoryGRPCError(err error) error {
case errors.Is(err, repository.ErrProductCategoryVersionConflict): case errors.Is(err, repository.ErrProductCategoryVersionConflict):
return status.Error(codes.Aborted, "product category version conflict") return status.Error(codes.Aborted, "product category version conflict")
case errors.Is(err, repository.ErrDuplicateProductCategory): case errors.Is(err, repository.ErrDuplicateProductCategory):
return status.Error(codes.AlreadyExists, "product category code or sibling name already exists") return status.Error(codes.AlreadyExists, "duplicate product category name")
case errors.Is(err, repository.ErrProductCategoryHasChildren), errors.Is(err, repository.ErrProductCategoryInUse):
return status.Error(codes.FailedPrecondition, err.Error())
default: default:
return status.Error(codes.InvalidArgument, err.Error()) return status.Error(codes.InvalidArgument, err.Error())
} }

View File

@ -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;