mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
feat: implement multi-level catalog category tree with nested children support
This commit is contained in:
parent
c8e9db4300
commit
feb1364be6
@ -30,7 +30,7 @@ var ErrCategoryVersionConflict = errors.New("category version conflict")
|
|||||||
var ErrCategoryTreeConflict = errors.New("category tree conflict")
|
var ErrCategoryTreeConflict = errors.New("category tree conflict")
|
||||||
var ErrCategoryNameExists = errors.New("category name already exists")
|
var ErrCategoryNameExists = errors.New("category name already exists")
|
||||||
var ErrGroupNameExists = errors.New("group name already exists")
|
var ErrGroupNameExists = errors.New("group name already exists")
|
||||||
var ErrInvalidLeafCategory = errors.New("category must be an existing second-level category")
|
var ErrInvalidLeafCategory = errors.New("category must be an existing terminal catalog category")
|
||||||
|
|
||||||
// ErrInvalidProductGroup is returned when a requested node is not a group in
|
// ErrInvalidProductGroup is returned when a requested node is not a group in
|
||||||
// the current store.
|
// the current store.
|
||||||
@ -317,6 +317,67 @@ type CategoryRecord struct {
|
|||||||
Version int32
|
Version int32
|
||||||
// ProductCount is populated when listing product groups.
|
// ProductCount is populated when listing product groups.
|
||||||
ProductCount int64
|
ProductCount int64
|
||||||
|
// Children is populated for catalog-category tree operations.
|
||||||
|
Children []CategoryRecord
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateCatalogCategoryTree inserts a catalog-category subtree of arbitrary
|
||||||
|
// depth. The request root may be attached to an existing catalog category.
|
||||||
|
func (r *ProductRepository) CreateCatalogCategoryTree(ctx context.Context, root CategoryRecord, children []CategoryRecord, scope StoreScope) (*CategoryRecord, []*CategoryRecord, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
tx, err := r.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("begin create catalog category tree: %w", err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
root.Children = children
|
||||||
|
created, err := r.createCatalogCategoryNode(ctx, tx, root, root.ParentID, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("commit create catalog category tree: %w", err)
|
||||||
|
}
|
||||||
|
return created, categoryRecordPointers(created.Children), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func categoryRecordPointers(values []CategoryRecord) []*CategoryRecord {
|
||||||
|
result := make([]*CategoryRecord, 0, len(values))
|
||||||
|
for index := range values {
|
||||||
|
result = append(result, &values[index])
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) createCatalogCategoryNode(ctx context.Context, tx *sql.Tx, input CategoryRecord, parentID string, scope StoreScope) (*CategoryRecord, error) {
|
||||||
|
input.NodeType = 1
|
||||||
|
input.ParentID = strings.TrimSpace(parentID)
|
||||||
|
if input.ParentID == "" {
|
||||||
|
input.Level = 1
|
||||||
|
} else {
|
||||||
|
parent, err := loadCategoryForUpdate(ctx, tx, input.ParentID, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if parent.NodeType != 1 {
|
||||||
|
return nil, ErrCategoryTreeConflict
|
||||||
|
}
|
||||||
|
input.Level = parent.Level + 1
|
||||||
|
}
|
||||||
|
created, err := insertCategoryNode(ctx, tx, input, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, child := range input.Children {
|
||||||
|
value, err := r.createCatalogCategoryNode(ctx, tx, child, created.ID, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
created.Children = append(created.Children, *value)
|
||||||
|
}
|
||||||
|
return created, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GroupListFilter contains optional product-group list constraints.
|
// GroupListFilter contains optional product-group list constraints.
|
||||||
@ -550,6 +611,10 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_products_store_spu_no
|
|||||||
WHERE deleted_at IS NULL AND spu_no <> '';
|
WHERE deleted_at IS NULL AND spu_no <> '';
|
||||||
CREATE INDEX IF NOT EXISTS idx_products_store_id ON product.products (store_id) WHERE deleted_at IS NULL;
|
CREATE INDEX IF NOT EXISTS idx_products_store_id ON product.products (store_id) WHERE deleted_at IS NULL;
|
||||||
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_id ON product.catalog_category (store_id);
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_id ON product.catalog_category (store_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_parent_status_sort
|
||||||
|
ON product.catalog_category (store_id, node_type, parent_id, status, sort_num, id);
|
||||||
|
COMMENT ON COLUMN product.catalog_category.level IS
|
||||||
|
'Server-maintained hierarchy level: root is 1 and each child is parent level plus 1.';
|
||||||
CREATE INDEX IF NOT EXISTS idx_product_category_campaign_id
|
CREATE INDEX IF NOT EXISTS idx_product_category_campaign_id
|
||||||
ON product.catalog_category (campaign_id) WHERE campaign_id IS NOT NULL;
|
ON product.catalog_category (campaign_id) WHERE campaign_id IS NOT NULL;
|
||||||
DROP INDEX IF EXISTS product.uq_product_category_group_normalized_name;
|
DROP INDEX IF EXISTS product.uq_product_category_group_normalized_name;
|
||||||
@ -916,55 +981,46 @@ func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID strin
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if target.NodeType != 1 || (target.Level != 1 && target.Level != 2) {
|
if target.NodeType != 1 {
|
||||||
return nil, ErrCategoryTreeConflict
|
return nil, ErrCategoryTreeConflict
|
||||||
}
|
}
|
||||||
if target.Version != expectedVersion {
|
if target.Version != expectedVersion {
|
||||||
return nil, ErrCategoryVersionConflict
|
return nil, ErrCategoryVersionConflict
|
||||||
}
|
}
|
||||||
|
|
||||||
categoryIDs := []int64{}
|
|
||||||
targetID, err := parseID(target.ID, "category_id")
|
targetID, err := parseID(target.ID, "category_id")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if target.Level == 1 {
|
rows, err := tx.QueryContext(ctx, `
|
||||||
rows, err := tx.QueryContext(ctx, `
|
WITH RECURSIVE descendants(id, path) AS (
|
||||||
SELECT id, node_type, name, parent_id, level,
|
SELECT id, ARRAY[id] FROM product.catalog_category WHERE id = $1 AND store_id = $2 AND node_type = 1
|
||||||
COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, campaign_id, version
|
UNION ALL
|
||||||
FROM product.catalog_category
|
SELECT child.id, parent.path || child.id
|
||||||
WHERE parent_id = $1 AND store_id = $2
|
FROM product.catalog_category child JOIN descendants parent ON child.parent_id = parent.id
|
||||||
FOR UPDATE
|
WHERE child.store_id = $2 AND child.node_type = 1 AND NOT child.id = ANY(parent.path)
|
||||||
|
)
|
||||||
|
SELECT id FROM descendants
|
||||||
`, targetID, scope.StoreID)
|
`, targetID, scope.StoreID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("load category children for delete: %w", err)
|
return nil, fmt.Errorf("load category descendants for delete: %w", err)
|
||||||
}
|
}
|
||||||
for rows.Next() {
|
categoryIDs := make([]int64, 0)
|
||||||
child, err := scanCategory(rows)
|
for rows.Next() {
|
||||||
if err != nil {
|
var id int64
|
||||||
rows.Close()
|
if err := rows.Scan(&id); err != nil {
|
||||||
return nil, err
|
rows.Close()
|
||||||
}
|
return nil, err
|
||||||
if child.NodeType != 1 || child.Level != 2 || child.ParentID != target.ID {
|
}
|
||||||
rows.Close()
|
categoryIDs = append(categoryIDs, id)
|
||||||
return nil, ErrCategoryTreeConflict
|
}
|
||||||
}
|
if err := rows.Err(); err != nil {
|
||||||
childID, err := parseID(child.ID, "category_id")
|
rows.Close()
|
||||||
if err != nil {
|
return nil, fmt.Errorf("iterate category descendants for delete: %w", err)
|
||||||
rows.Close()
|
}
|
||||||
return nil, err
|
if err := rows.Close(); err != nil {
|
||||||
}
|
return nil, fmt.Errorf("close category descendants for delete: %w", err)
|
||||||
categoryIDs = append(categoryIDs, childID)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
rows.Close()
|
|
||||||
return nil, fmt.Errorf("iterate category children for delete: %w", err)
|
|
||||||
}
|
|
||||||
if err := rows.Close(); err != nil {
|
|
||||||
return nil, fmt.Errorf("close category children for delete: %w", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
categoryIDs = append(categoryIDs, targetID)
|
|
||||||
placeholders := make([]string, len(categoryIDs))
|
placeholders := make([]string, len(categoryIDs))
|
||||||
args := make([]any, len(categoryIDs))
|
args := make([]any, len(categoryIDs))
|
||||||
for index, id := range categoryIDs {
|
for index, id := range categoryIDs {
|
||||||
@ -991,13 +1047,8 @@ WHERE category_id IN (%s)
|
|||||||
`, whereIDs), args...); err != nil {
|
`, whereIDs), args...); err != nil {
|
||||||
return nil, fmt.Errorf("delete category bindings: %w", err)
|
return nil, fmt.Errorf("delete category bindings: %w", err)
|
||||||
}
|
}
|
||||||
if target.Level == 1 {
|
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM product.catalog_category WHERE id IN (%s) AND store_id = $%d`, whereIDs, len(args)+1), append(args, scope.StoreID)...); err != nil {
|
||||||
if _, err := tx.ExecContext(ctx, `DELETE FROM product.catalog_category WHERE parent_id = $1 AND store_id = $2`, targetID, scope.StoreID); err != nil {
|
return nil, fmt.Errorf("delete category tree: %w", err)
|
||||||
return nil, fmt.Errorf("delete child categories: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if _, err := tx.ExecContext(ctx, `DELETE FROM product.catalog_category WHERE id = $1 AND store_id = $2`, targetID, scope.StoreID); err != nil {
|
|
||||||
return nil, fmt.Errorf("delete category: %w", err)
|
|
||||||
}
|
}
|
||||||
if err := tx.Commit(); err != nil {
|
if err := tx.Commit(); err != nil {
|
||||||
return nil, fmt.Errorf("commit delete category: %w", err)
|
return nil, fmt.Errorf("commit delete category: %w", err)
|
||||||
@ -1257,10 +1308,10 @@ func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID stri
|
|||||||
return r.addProductsToCategoryNode(ctx, groupID, bindingIDs, productIDs, 2, 0, "group", scope)
|
return r.addProductsToCategoryNode(ctx, groupID, bindingIDs, productIDs, 2, 0, "group", scope)
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddProductsToCategory binds every product to a second-level category in one
|
// AddProductsToCategory binds every product to a terminal catalog category at
|
||||||
// transaction. Existing bindings are retained and duplicate bindings are ignored.
|
// any level. Existing bindings are retained and duplicate bindings are ignored.
|
||||||
func (r *ProductRepository) AddProductsToCategory(ctx context.Context, categoryID string, bindingIDs, productIDs []string, scope StoreScope) error {
|
func (r *ProductRepository) AddProductsToCategory(ctx context.Context, categoryID string, bindingIDs, productIDs []string, scope StoreScope) error {
|
||||||
return r.addProductsToCategoryNode(ctx, categoryID, bindingIDs, productIDs, 1, 2, "category", scope)
|
return r.addProductsToCategoryNode(ctx, categoryID, bindingIDs, productIDs, 1, -1, "category", scope)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *ProductRepository) addProductsToCategoryNode(ctx context.Context, nodeID string, bindingIDs, productIDs []string, nodeType, level int32, nodeLabel string, scope StoreScope) error {
|
func (r *ProductRepository) addProductsToCategoryNode(ctx context.Context, nodeID string, bindingIDs, productIDs []string, nodeType, level int32, nodeLabel string, scope StoreScope) error {
|
||||||
@ -1298,12 +1349,17 @@ func (r *ProductRepository) addProductsToCategoryNode(ctx context.Context, nodeI
|
|||||||
defer tx.Rollback()
|
defer tx.Rollback()
|
||||||
|
|
||||||
err = tx.QueryRowContext(ctx, `
|
err = tx.QueryRowContext(ctx, `
|
||||||
SELECT id
|
SELECT c.id
|
||||||
FROM product.catalog_category
|
FROM product.catalog_category c
|
||||||
WHERE id = $1
|
WHERE c.id = $1
|
||||||
AND node_type = $2
|
AND c.node_type = $2
|
||||||
AND store_id = $3
|
AND c.store_id = $3
|
||||||
AND ($4 = 0 OR level = $4)
|
AND ($4 = 0 OR ($4 > 0 AND c.level = $4) OR ($4 = -1 AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM product.catalog_category child
|
||||||
|
WHERE child.parent_id = c.id
|
||||||
|
AND child.store_id = $3
|
||||||
|
AND child.node_type = 1
|
||||||
|
)))
|
||||||
`, parsedNodeID, nodeType, scope.StoreID, level).Scan(&parsedNodeID)
|
`, parsedNodeID, nodeType, scope.StoreID, level).Scan(&parsedNodeID)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, nodeID)
|
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, nodeID)
|
||||||
@ -1649,12 +1705,17 @@ func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, product
|
|||||||
args[index] = categoryID
|
args[index] = categoryID
|
||||||
}
|
}
|
||||||
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
|
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
|
||||||
SELECT id
|
SELECT c.id
|
||||||
FROM product.catalog_category
|
FROM product.catalog_category c
|
||||||
WHERE node_type = 1
|
WHERE c.node_type = 1
|
||||||
AND level = 2
|
AND c.store_id = $%d
|
||||||
AND store_id = $%d
|
AND c.id IN (%s)
|
||||||
AND id IN (%s)
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM product.catalog_category child
|
||||||
|
WHERE child.parent_id = c.id
|
||||||
|
AND child.store_id = c.store_id
|
||||||
|
AND child.node_type = 1
|
||||||
|
)
|
||||||
FOR KEY SHARE
|
FOR KEY SHARE
|
||||||
`, len(args)+1, strings.Join(placeholders, ", ")), append(args, scope.StoreID)...)
|
`, len(args)+1, strings.Join(placeholders, ", ")), append(args, scope.StoreID)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -1687,7 +1748,6 @@ USING product.catalog_category AS c
|
|||||||
WHERE b.product_id = $1
|
WHERE b.product_id = $1
|
||||||
AND b.category_id = c.id
|
AND b.category_id = c.id
|
||||||
AND c.node_type = 1
|
AND c.node_type = 1
|
||||||
AND c.level = 2
|
|
||||||
AND c.store_id = $2
|
AND c.store_id = $2
|
||||||
`, parsedProductID, scope.StoreID); err != nil {
|
`, parsedProductID, scope.StoreID); err != nil {
|
||||||
return fmt.Errorf("delete product leaf category bindings: %w", err)
|
return fmt.Errorf("delete product leaf category bindings: %w", err)
|
||||||
@ -2940,8 +3000,13 @@ FROM product.product_catalog_bindings AS b
|
|||||||
JOIN product.catalog_category AS c ON c.id = b.category_id
|
JOIN product.catalog_category AS c ON c.id = b.category_id
|
||||||
WHERE b.product_id = $1
|
WHERE b.product_id = $1
|
||||||
AND c.node_type = 1
|
AND c.node_type = 1
|
||||||
AND c.level = 2
|
|
||||||
AND c.store_id = $2
|
AND c.store_id = $2
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM product.catalog_category child
|
||||||
|
WHERE child.parent_id = c.id
|
||||||
|
AND child.store_id = c.store_id
|
||||||
|
AND child.node_type = 1
|
||||||
|
)
|
||||||
ORDER BY c.sort_num, c.id
|
ORDER BY c.sort_num, c.id
|
||||||
`, parsedProductID, scope.StoreID)
|
`, parsedProductID, scope.StoreID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -3290,7 +3355,7 @@ func (r *ProductRepository) SearchProducts(ctx context.Context, keyword string,
|
|||||||
|
|
||||||
var total int64
|
var total int64
|
||||||
if err := r.db.QueryRowContext(ctx, `
|
if err := r.db.QueryRowContext(ctx, `
|
||||||
SELECT COUNT(*)
|
SELECT COUNT(DISTINCT p.id)
|
||||||
FROM product.products p
|
FROM product.products p
|
||||||
WHERE p.deleted_at IS NULL
|
WHERE p.deleted_at IS NULL
|
||||||
AND p.store_id = $4
|
AND p.store_id = $4
|
||||||
@ -3438,7 +3503,14 @@ SELECT COUNT(*)
|
|||||||
FROM product.products p
|
FROM product.products p
|
||||||
JOIN product.product_catalog_bindings b ON b.product_id = p.id
|
JOIN product.product_catalog_bindings b ON b.product_id = p.id
|
||||||
JOIN product.catalog_category c ON c.id = b.category_id
|
JOIN product.catalog_category c ON c.id = b.category_id
|
||||||
WHERE b.category_id = $1
|
WHERE ($6 = 2 OR b.category_id IN (
|
||||||
|
WITH RECURSIVE descendants(id) AS (
|
||||||
|
SELECT id FROM product.catalog_category WHERE id = $1 AND store_id = $5 AND node_type = 1
|
||||||
|
UNION ALL
|
||||||
|
SELECT child.id FROM product.catalog_category child JOIN descendants parent ON child.parent_id = parent.id
|
||||||
|
WHERE child.store_id = $5 AND child.node_type = 1
|
||||||
|
) SELECT id FROM descendants
|
||||||
|
))
|
||||||
AND p.deleted_at IS NULL
|
AND p.deleted_at IS NULL
|
||||||
AND p.store_id = $5
|
AND p.store_id = $5
|
||||||
AND c.store_id = $5
|
AND c.store_id = $5
|
||||||
@ -3464,7 +3536,14 @@ SELECT p.id
|
|||||||
FROM product.products p
|
FROM product.products p
|
||||||
JOIN product.product_catalog_bindings b ON b.product_id = p.id
|
JOIN product.product_catalog_bindings b ON b.product_id = p.id
|
||||||
JOIN product.catalog_category c ON c.id = b.category_id
|
JOIN product.catalog_category c ON c.id = b.category_id
|
||||||
WHERE b.category_id = $1
|
WHERE ($6 = 2 OR b.category_id IN (
|
||||||
|
WITH RECURSIVE descendants(id) AS (
|
||||||
|
SELECT id FROM product.catalog_category WHERE id = $1 AND store_id = $5 AND node_type = 1
|
||||||
|
UNION ALL
|
||||||
|
SELECT child.id FROM product.catalog_category child JOIN descendants parent ON child.parent_id = parent.id
|
||||||
|
WHERE child.store_id = $5 AND child.node_type = 1
|
||||||
|
) SELECT id FROM descendants
|
||||||
|
))
|
||||||
AND p.deleted_at IS NULL
|
AND p.deleted_at IS NULL
|
||||||
AND p.store_id = $5
|
AND p.store_id = $5
|
||||||
AND c.store_id = $5
|
AND c.store_id = $5
|
||||||
@ -3478,7 +3557,8 @@ WHERE b.category_id = $1
|
|||||||
AND pi.is_archived = FALSE
|
AND pi.is_archived = FALSE
|
||||||
AND pi.status = 1
|
AND pi.status = 1
|
||||||
))
|
))
|
||||||
ORDER BY p.created_at DESC, p.id DESC
|
GROUP BY p.id
|
||||||
|
ORDER BY MAX(p.created_at) DESC, p.id DESC
|
||||||
`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID, targetNodeType)
|
`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID, targetNodeType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, 0, fmt.Errorf("query category product ids: %w", err)
|
return nil, nil, 0, fmt.Errorf("query category product ids: %w", err)
|
||||||
@ -3498,7 +3578,7 @@ ORDER BY p.created_at DESC, p.id DESC
|
|||||||
|
|
||||||
offset := int64(page-1) * int64(pageSize)
|
offset := int64(page-1) * int64(pageSize)
|
||||||
rows, err := r.db.QueryContext(ctx, `
|
rows, err := r.db.QueryContext(ctx, `
|
||||||
SELECT p.updated_at,
|
SELECT DISTINCT p.updated_at,
|
||||||
p.created_at,
|
p.created_at,
|
||||||
p.title,
|
p.title,
|
||||||
p.id,
|
p.id,
|
||||||
@ -3525,7 +3605,14 @@ LEFT JOIN LATERAL (
|
|||||||
AND pi.is_archived = FALSE
|
AND pi.is_archived = FALSE
|
||||||
AND ($2 = FALSE OR pi.status = 1)
|
AND ($2 = FALSE OR pi.status = 1)
|
||||||
) sku_summary ON TRUE
|
) sku_summary ON TRUE
|
||||||
WHERE b.category_id = $1
|
WHERE ($8 = 2 OR b.category_id IN (
|
||||||
|
WITH RECURSIVE descendants(id) AS (
|
||||||
|
SELECT id FROM product.catalog_category WHERE id = $1 AND store_id = $7 AND node_type = 1
|
||||||
|
UNION ALL
|
||||||
|
SELECT child.id FROM product.catalog_category child JOIN descendants parent ON child.parent_id = parent.id
|
||||||
|
WHERE child.store_id = $7 AND child.node_type = 1
|
||||||
|
) SELECT id FROM descendants
|
||||||
|
))
|
||||||
AND p.deleted_at IS NULL
|
AND p.deleted_at IS NULL
|
||||||
AND p.store_id = $7
|
AND p.store_id = $7
|
||||||
AND c.store_id = $7
|
AND c.store_id = $7
|
||||||
@ -3605,11 +3692,29 @@ SELECT EXISTS (SELECT 1 FROM ancestry WHERE parent_id IS NULL)
|
|||||||
return visible, nil
|
return visible, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListCategoryTreeNodes loads product category nodes for storefront category trees.
|
// ListCategoryTreeNodes loads a complete catalog tree (maxDepth=0) or a
|
||||||
func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool, scope StoreScope) ([]*CategoryRecord, error) {
|
// lazily-loaded slice beginning at rootID. maxDepth counts edges below a root.
|
||||||
|
func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool, rootID string, maxDepth int32, scope StoreScope) ([]*CategoryRecord, error) {
|
||||||
if err := requireWriteScope(scope); err != nil {
|
if err := requireWriteScope(scope); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
var root any
|
||||||
|
if strings.TrimSpace(rootID) != "" {
|
||||||
|
parsed, err := parseID(rootID, "category_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if onlyVisible {
|
||||||
|
visible, err := r.isStorefrontCategoryVisible(ctx, parsed, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !visible {
|
||||||
|
return nil, ErrStorefrontCategoryNotFound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
root = parsed
|
||||||
|
}
|
||||||
rows, err := r.db.QueryContext(ctx, `
|
rows, err := r.db.QueryContext(ctx, `
|
||||||
SELECT id,
|
SELECT id,
|
||||||
node_type,
|
node_type,
|
||||||
@ -3623,26 +3728,28 @@ SELECT id,
|
|||||||
version
|
version
|
||||||
FROM (
|
FROM (
|
||||||
WITH RECURSIVE category_tree AS (
|
WITH RECURSIVE category_tree AS (
|
||||||
SELECT id, node_type, name, parent_id, level, image_ids, sort_num, status, campaign_id, version
|
SELECT id, node_type, name, parent_id, level, image_ids, sort_num, status, campaign_id, version, 0 AS depth, ARRAY[id] AS path
|
||||||
FROM product.catalog_category
|
FROM product.catalog_category
|
||||||
WHERE node_type = 1
|
WHERE node_type = 1
|
||||||
AND store_id = $2
|
AND store_id = $2
|
||||||
AND parent_id IS NULL
|
AND (($3::BIGINT IS NULL AND parent_id IS NULL) OR id = $3)
|
||||||
AND ($1 = FALSE OR status = 1)
|
AND ($1 = FALSE OR status = 1)
|
||||||
|
|
||||||
UNION ALL
|
UNION ALL
|
||||||
|
|
||||||
SELECT child.id, child.node_type, child.name, child.parent_id, child.level, child.image_ids, child.sort_num, child.status, child.campaign_id, child.version
|
SELECT child.id, child.node_type, child.name, child.parent_id, child.level, child.image_ids, child.sort_num, child.status, child.campaign_id, child.version, parent.depth + 1, parent.path || child.id
|
||||||
FROM product.catalog_category child
|
FROM product.catalog_category child
|
||||||
JOIN category_tree parent ON child.parent_id = parent.id
|
JOIN category_tree parent ON child.parent_id = parent.id
|
||||||
WHERE child.node_type = 1
|
WHERE child.node_type = 1
|
||||||
AND child.store_id = $2
|
AND child.store_id = $2
|
||||||
AND ($1 = FALSE OR child.status = 1)
|
AND ($1 = FALSE OR child.status = 1)
|
||||||
|
AND ($4 = 0 OR parent.depth < $4)
|
||||||
|
AND NOT child.id = ANY(parent.path)
|
||||||
)
|
)
|
||||||
SELECT * FROM category_tree
|
SELECT * FROM category_tree
|
||||||
) category_tree
|
) category_tree
|
||||||
ORDER BY level ASC, sort_num ASC, id ASC
|
ORDER BY level ASC, sort_num ASC, id ASC
|
||||||
`, onlyVisible, scope.StoreID)
|
`, onlyVisible, scope.StoreID, root, maxDepth)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("query category tree nodes: %w", err)
|
return nil, fmt.Errorf("query category tree nodes: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -37,3 +37,22 @@ func TestGroupTreeFromCreateRequestAcceptsChildren(t *testing.T) {
|
|||||||
t.Fatal("expected duplicate child names to fail")
|
t.Fatal("expected duplicate child names to fail")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCategoryTreeFromCreateRequestAcceptsNestedChildren(t *testing.T) {
|
||||||
|
root, children, err := categoryTreeFromCreateRequest(&productv1.CreateCategoryTreeRequest{
|
||||||
|
Name: "服饰",
|
||||||
|
Children: []*productv1.CreateChildCategory{{
|
||||||
|
Name: "女装",
|
||||||
|
Children: []*productv1.CreateChildCategory{{
|
||||||
|
Name: "连衣裙",
|
||||||
|
Children: []*productv1.CreateChildCategory{{Name: "长裙"}},
|
||||||
|
}},
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("categoryTreeFromCreateRequest: %v", err)
|
||||||
|
}
|
||||||
|
if root.Level != 1 || len(children) != 1 || len(children[0].Children) != 1 || len(children[0].Children[0].Children) != 1 {
|
||||||
|
t.Fatalf("nested category tree was not preserved: root=%#v children=%#v", root, children)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -997,7 +997,21 @@ func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.Lis
|
|||||||
))
|
))
|
||||||
defer dbSpan.End()
|
defer dbSpan.End()
|
||||||
|
|
||||||
categories, err := s.repo.ListCategoryTreeNodes(dbCtx, onlyVisible, scope)
|
categoryID := ""
|
||||||
|
maxDepth := int32(0)
|
||||||
|
if req != nil {
|
||||||
|
categoryID = strings.TrimSpace(req.GetCategoryId())
|
||||||
|
maxDepth = req.GetMaxDepth()
|
||||||
|
}
|
||||||
|
if maxDepth < 0 {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "max_depth must be non-negative")
|
||||||
|
}
|
||||||
|
if categoryID != "" {
|
||||||
|
if _, err := normalizeCategoryID(categoryID, "category_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
categories, err := s.repo.ListCategoryTreeNodes(dbCtx, onlyVisible, categoryID, maxDepth, scope)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
dbSpan.RecordError(err)
|
dbSpan.RecordError(err)
|
||||||
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||||
@ -1019,7 +1033,7 @@ func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.Lis
|
|||||||
return resp, nil
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateCategoryTree creates a top-level category and optional second-level categories.
|
// CreateCategoryTree creates a catalog-category subtree at any depth.
|
||||||
func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.CreateCategoryTreeRequest) (*productv1.CreateCategoryTreeResponse, error) {
|
func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.CreateCategoryTreeRequest) (*productv1.CreateCategoryTreeResponse, 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")
|
||||||
@ -1036,10 +1050,7 @@ func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.C
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
}
|
}
|
||||||
parent.ID = s.idgen.NextString()
|
assignCatalogCategoryIDs(&parent, s)
|
||||||
for i := range children {
|
|
||||||
children[i].ID = s.idgen.NextString()
|
|
||||||
}
|
|
||||||
|
|
||||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_category_tree", trace.WithAttributes(
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_category_tree", trace.WithAttributes(
|
||||||
attribute.String("category.name", parent.Name),
|
attribute.String("category.name", parent.Name),
|
||||||
@ -1047,7 +1058,7 @@ func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.C
|
|||||||
))
|
))
|
||||||
defer dbSpan.End()
|
defer dbSpan.End()
|
||||||
|
|
||||||
createdParent, createdChildren, err := s.repo.CreateCategoryTree(dbCtx, parent, children, scope)
|
createdParent, _, err := s.repo.CreateCatalogCategoryTree(dbCtx, parent, children, scope)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
dbSpan.RecordError(err)
|
dbSpan.RecordError(err)
|
||||||
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||||
@ -1059,9 +1070,6 @@ func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.C
|
|||||||
}
|
}
|
||||||
|
|
||||||
category := toProtoCategoryNode(createdParent)
|
category := toProtoCategoryNode(createdParent)
|
||||||
for _, child := range createdChildren {
|
|
||||||
category.Children = append(category.Children, toProtoCategoryNode(child))
|
|
||||||
}
|
|
||||||
|
|
||||||
return &productv1.CreateCategoryTreeResponse{
|
return &productv1.CreateCategoryTreeResponse{
|
||||||
Category: category,
|
Category: category,
|
||||||
@ -1108,7 +1116,7 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1.
|
|||||||
return nil, status.Error(codes.Internal, "update category trees")
|
return nil, status.Error(codes.Internal, "update category trees")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
all, err := s.repo.ListCategoryTreeNodes(dbCtx, false, scope)
|
all, err := s.repo.ListCategoryTreeNodes(dbCtx, false, "", 0, scope)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, status.Error(codes.Internal, "load updated category trees")
|
return nil, status.Error(codes.Internal, "load updated category trees")
|
||||||
}
|
}
|
||||||
@ -1127,8 +1135,7 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1.
|
|||||||
return &productv1.UpdateCategoryTreesResponse{Categories: categories}, nil
|
return &productv1.UpdateCategoryTreesResponse{Categories: categories}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteCategory removes a single second-level category or a full top-level
|
// DeleteCategory removes a category subtree. It never deletes products themselves.
|
||||||
// category tree. It never deletes products themselves.
|
|
||||||
func (s *ProductServer) DeleteCategory(ctx context.Context, req *productv1.DeleteCategoryRequest) (*productv1.DeleteCategoryResponse, error) {
|
func (s *ProductServer) DeleteCategory(ctx context.Context, req *productv1.DeleteCategoryRequest) (*productv1.DeleteCategoryResponse, 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")
|
||||||
@ -1659,6 +1666,12 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re
|
|||||||
Status: statusValue,
|
Status: statusValue,
|
||||||
CampaignID: req.GetCampaignId(),
|
CampaignID: req.GetCampaignId(),
|
||||||
}
|
}
|
||||||
|
if req.ParentId != nil {
|
||||||
|
parent.ParentID, err = normalizeCategoryID(req.GetParentId(), "parent_id")
|
||||||
|
if err != nil {
|
||||||
|
return repository.CategoryRecord{}, nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
children := make([]repository.CategoryRecord, 0, len(req.GetChildren()))
|
children := make([]repository.CategoryRecord, 0, len(req.GetChildren()))
|
||||||
childNames := make(map[string]struct{}, len(req.GetChildren()))
|
childNames := make(map[string]struct{}, len(req.GetChildren()))
|
||||||
@ -1684,20 +1697,58 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re
|
|||||||
return repository.CategoryRecord{}, nil, err
|
return repository.CategoryRecord{}, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
children = append(children, repository.CategoryRecord{
|
grandchildren, err := categoryChildrenFromCreateRequest(child.GetChildren(), "children.children")
|
||||||
NodeType: categoryNodeType,
|
if err != nil {
|
||||||
Name: childName,
|
return repository.CategoryRecord{}, nil, err
|
||||||
Level: 2,
|
}
|
||||||
ImageIDs: childImageIDs,
|
children = append(children, repository.CategoryRecord{NodeType: categoryNodeType, Name: childName, ImageIDs: childImageIDs, SortNum: child.GetSortNum(), Status: childStatus, CampaignID: child.GetCampaignId(), Children: grandchildren})
|
||||||
SortNum: child.GetSortNum(),
|
|
||||||
Status: childStatus,
|
|
||||||
CampaignID: child.GetCampaignId(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return parent, children, nil
|
return parent, children, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func categoryChildrenFromCreateRequest(inputs []*productv1.CreateChildCategory, field string) ([]repository.CategoryRecord, error) {
|
||||||
|
children := make([]repository.CategoryRecord, 0, len(inputs))
|
||||||
|
seen := make(map[string]struct{}, len(inputs))
|
||||||
|
for _, child := range inputs {
|
||||||
|
if child == nil {
|
||||||
|
return nil, errors.New(field + " item is required")
|
||||||
|
}
|
||||||
|
name, err := normalizeNodeName(child.GetName(), field+".name")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if _, exists := seen[normalizedNodeNameKey(name)]; exists {
|
||||||
|
return nil, errors.New(field + ".name must be unique")
|
||||||
|
}
|
||||||
|
seen[normalizedNodeNameKey(name)] = struct{}{}
|
||||||
|
images, err := normalizeNodeImageIDs(child.GetImageJson())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
statusValue, err := normalizeNodeStatus(child.Status)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
grandchildren, err := categoryChildrenFromCreateRequest(child.GetChildren(), field+".children")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
children = append(children, repository.CategoryRecord{NodeType: categoryNodeType, Name: name, ImageIDs: images, SortNum: child.GetSortNum(), Status: statusValue, CampaignID: child.GetCampaignId(), Children: grandchildren})
|
||||||
|
}
|
||||||
|
return children, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func assignCatalogCategoryIDs(node *repository.CategoryRecord, s *ProductServer) {
|
||||||
|
if node == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
node.ID = s.idgen.NextString()
|
||||||
|
for index := range node.Children {
|
||||||
|
assignCatalogCategoryIDs(&node.Children[index], s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func categoryTreeUpdatesFromRequest(req *productv1.UpdateCategoryTreesRequest) ([]repository.CategoryTreeUpdate, []string, error) {
|
func categoryTreeUpdatesFromRequest(req *productv1.UpdateCategoryTreesRequest) ([]repository.CategoryTreeUpdate, []string, error) {
|
||||||
if len(req.GetCategoryTrees()) == 0 {
|
if len(req.GetCategoryTrees()) == 0 {
|
||||||
return nil, nil, errors.New("category_trees is required")
|
return nil, nil, errors.New("category_trees is required")
|
||||||
@ -2851,7 +2902,7 @@ func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.Categor
|
|||||||
if category == nil {
|
if category == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return &productv1.CategoryNode{
|
out := &productv1.CategoryNode{
|
||||||
CategoryId: category.ID,
|
CategoryId: category.ID,
|
||||||
NodeType: category.NodeType,
|
NodeType: category.NodeType,
|
||||||
Name: category.Name,
|
Name: category.Name,
|
||||||
@ -2864,6 +2915,10 @@ func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.Categor
|
|||||||
Version: category.Version,
|
Version: category.Version,
|
||||||
Children: []*productv1.CategoryNode{},
|
Children: []*productv1.CategoryNode{},
|
||||||
}
|
}
|
||||||
|
for index := range category.Children {
|
||||||
|
out.Children = append(out.Children, toProtoCategoryNode(&category.Children[index]))
|
||||||
|
}
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode {
|
func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode {
|
||||||
|
|||||||
11
scripts/sql/007_catalog_category_multilevel_tree.sql
Normal file
11
scripts/sql/007_catalog_category_multilevel_tree.sql
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
-- Enables efficient lazy administration and full storefront traversal for the
|
||||||
|
-- existing multi-level capable catalog_category adjacency list. Existing
|
||||||
|
-- two-level records require no data migration. The product service executes
|
||||||
|
-- the same idempotent statements during EnsureSchema on every startup; retain
|
||||||
|
-- this file for release pipelines or standalone database operations.
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_parent_status_sort
|
||||||
|
ON product.catalog_category (store_id, node_type, parent_id, status, sort_num, id);
|
||||||
|
|
||||||
|
COMMENT ON COLUMN product.catalog_category.level IS
|
||||||
|
'Server-maintained hierarchy level: root is 1 and each child is parent level plus 1.';
|
||||||
Loading…
Reference in New Issue
Block a user