feat: implement product category path handling and enhance product category retrieval

This commit is contained in:
BXY 2026-10-26 14:22:21 +08:00
parent 0a58b5e332
commit 099d6eeab0
5 changed files with 263 additions and 16 deletions

View File

@ -28,6 +28,15 @@ type ProductCategoryRecord struct {
CreatedAt, UpdatedAt time.Time
DeletedAt *time.Time
Children []*ProductCategoryRecord
Path []ProductCategoryPathNodeRecord
}
// ProductCategoryListFilter narrows a standard-category list query. The
// fields are combined when more than one selector is supplied.
type ProductCategoryListFilter struct {
ProductCategoryID string
PlatformCategoryID *int64
Name string
}
type ProductCategoryPatch struct {
@ -123,14 +132,25 @@ func createProductCategoryNode(ctx context.Context, tx *sql.Tx, input *ProductCa
return created, nil
}
func (r *ProductRepository) ListProductCategories(ctx context.Context, id string) ([]*ProductCategoryRecord, error) {
if id != "" {
func (r *ProductRepository) ListProductCategories(ctx context.Context, filter ProductCategoryListFilter) ([]*ProductCategoryRecord, error) {
id := strings.TrimSpace(filter.ProductCategoryID)
name := strings.TrimSpace(filter.Name)
if id != "" && filter.PlatformCategoryID == nil && name == "" {
node, err := r.loadProductCategoryOneLevel(ctx, id)
if err != nil {
return nil, err
}
return []*ProductCategoryRecord{node}, nil
out := []*ProductCategoryRecord{node}
return out, r.populateProductCategoryPaths(ctx, flattenProductCategoryNodes(out))
}
if id != "" || filter.PlatformCategoryID != nil || name != "" {
out, err := r.searchProductCategories(ctx, filter)
if err != nil {
return nil, err
}
return out, r.populateProductCategoryPaths(ctx, out)
}
rows, err := r.db.QueryContext(ctx, `SELECT `+productCategoryColumns+` FROM product.product_category c WHERE c.parent_id IS NULL AND c.deleted_at IS NULL ORDER BY c.priority,c.id`)
if err != nil {
return nil, err
@ -170,9 +190,135 @@ func (r *ProductRepository) ListProductCategories(ctx context.Context, id string
if err := children.Err(); err != nil {
return nil, err
}
return out, r.populateProductCategoryPaths(ctx, flattenProductCategoryNodes(out))
}
func (r *ProductRepository) searchProductCategories(ctx context.Context, filter ProductCategoryListFilter) ([]*ProductCategoryRecord, error) {
clauses := []string{"c.deleted_at IS NULL"}
args := make([]any, 0, 3)
if id := strings.TrimSpace(filter.ProductCategoryID); id != "" {
parsed, err := parseID(id, "product_category_id")
if err != nil {
return nil, err
}
args = append(args, parsed)
clauses = append(clauses, fmt.Sprintf("c.id=$%d", len(args)))
}
if filter.PlatformCategoryID != nil {
args = append(args, *filter.PlatformCategoryID)
clauses = append(clauses, fmt.Sprintf("c.platform_category_id=$%d", len(args)))
}
if name := strings.TrimSpace(filter.Name); name != "" {
args = append(args, "%"+escapeLikeLiteral(name)+"%")
clauses = append(clauses, fmt.Sprintf("lower(c.name) LIKE lower($%d) ESCAPE '\\'", len(args)))
}
rows, err := r.db.QueryContext(ctx, `SELECT `+productCategoryColumns+` FROM product.product_category c WHERE `+strings.Join(clauses, " AND ")+` ORDER BY c.level,c.priority,c.id`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
out := make([]*ProductCategoryRecord, 0)
for rows.Next() {
node, err := scanProductCategory(rows)
if err != nil {
return nil, err
}
out = append(out, node)
}
if err := rows.Err(); err != nil {
return nil, err
}
return out, nil
}
func flattenProductCategoryNodes(roots []*ProductCategoryRecord) []*ProductCategoryRecord {
out := make([]*ProductCategoryRecord, 0, len(roots))
for _, root := range roots {
if root == nil {
continue
}
out = append(out, root)
out = append(out, root.Children...)
}
return out
}
// populateProductCategoryPaths loads each supplied node's active ancestors in
// one recursive query. The returned path is always ordered from root to node.
func (r *ProductRepository) populateProductCategoryPaths(ctx context.Context, categories []*ProductCategoryRecord) error {
if len(categories) == 0 {
return nil
}
ids := make([]int64, 0, len(categories))
byID := make(map[string]*ProductCategoryRecord, len(categories))
for _, category := range categories {
if category == nil {
continue
}
parsed, err := parseID(category.ID, "product_category_id")
if err != nil {
return err
}
ids = append(ids, parsed)
byID[category.ID] = category
category.Path = []ProductCategoryPathNodeRecord{}
}
if len(ids) == 0 {
return nil
}
placeholders, args := productIDPlaceholders(ids, 1)
rows, err := r.db.QueryContext(ctx, `
WITH RECURSIVE category_paths AS (
SELECT c.id AS target_category_id,
c.id,
c.parent_id,
c.name,
c.level,
0 AS depth,
ARRAY[c.id] AS visited_category_ids
FROM product.product_category c
WHERE c.id IN (`+placeholders+`)
AND c.deleted_at IS NULL
UNION ALL
SELECT cp.target_category_id,
parent.id,
parent.parent_id,
parent.name,
parent.level,
cp.depth + 1,
cp.visited_category_ids || parent.id
FROM category_paths cp
JOIN product.product_category parent ON parent.id = cp.parent_id
WHERE parent.deleted_at IS NULL
AND NOT parent.id = ANY(cp.visited_category_ids)
)
SELECT target_category_id, id, parent_id, name, level
FROM category_paths
ORDER BY target_category_id, depth DESC`, args...)
if err != nil {
return fmt.Errorf("list product category paths: %w", err)
}
defer rows.Close()
for rows.Next() {
var targetID, categoryID int64
var parentID sql.NullInt64
var name string
var level int32
if err := rows.Scan(&targetID, &categoryID, &parentID, &name, &level); err != nil {
return fmt.Errorf("scan product category path: %w", err)
}
if target := byID[formatID(targetID)]; target != nil {
target.Path = append(target.Path, ProductCategoryPathNodeRecord{
ID: formatID(categoryID), Name: name, Level: level, ParentID: nullableFormattedID(parentID),
})
}
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterate product category paths: %w", err)
}
return nil
}
func (r *ProductRepository) loadProductCategoryOneLevel(ctx context.Context, id string) (*ProductCategoryRecord, error) {
parsed, err := parseID(id, "product_category_id")
if err != nil {

View File

@ -111,6 +111,7 @@ type ProductRecord struct {
GroupBindingIDs []string
ProductCategoryIDs []string
ProductCategoryBindingIDs []string
ProductCategories []ProductCategorySummaryRecord
Version int32
DeletedAt *time.Time
CreatedAt time.Time
@ -2964,6 +2965,15 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string, sc
return nil, nil, err
}
product.ProductCategoryIDs = productCategoryIDs
parsedProductID, err := parseID(productID, "product_id")
if err != nil {
return nil, nil, err
}
productCategorySummaries, err := r.loadProductCategorySummaries(ctx, []int64{parsedProductID}, scope)
if err != nil {
return nil, nil, err
}
product.ProductCategories = productCategorySummaries[productID]
return product, skus[productID], nil
}
@ -3485,6 +3495,26 @@ func nullableFormattedID(value sql.NullInt64) *string {
}
func (r *ProductRepository) populateProductCategorySummaries(ctx context.Context, productIDs []int64, products map[string]*CategoryProductRecord, scope StoreScope) error {
summaries, err := r.loadProductCategorySummaries(ctx, productIDs, scope)
if err != nil {
return err
}
for productID, product := range products {
if product != nil {
product.ProductCategories = append(product.ProductCategories, summaries[productID]...)
}
}
return nil
}
// loadProductCategorySummaries returns every direct standard-category binding
// for the supplied products together with its complete active ancestor path.
// It is shared by product lists and the product-detail read path.
func (r *ProductRepository) loadProductCategorySummaries(ctx context.Context, productIDs []int64, scope StoreScope) (map[string][]ProductCategorySummaryRecord, error) {
result := make(map[string][]ProductCategorySummaryRecord, len(productIDs))
if len(productIDs) == 0 {
return result, nil
}
placeholders, idArgs := productIDPlaceholders(productIDs, 3)
args := append([]any{scope.TenantID, scope.StoreID}, idArgs...)
rows, err := r.db.QueryContext(ctx, `
@ -3522,7 +3552,7 @@ SELECT product_id, bound_category_id, id, parent_id, name, level, depth
FROM category_paths
ORDER BY product_id, bound_category_id, depth DESC`, args...)
if err != nil {
return fmt.Errorf("list product category summaries: %w", err)
return nil, fmt.Errorf("list product category summaries: %w", err)
}
defer rows.Close()
@ -3533,7 +3563,7 @@ ORDER BY product_id, bound_category_id, depth DESC`, args...)
var name string
var level, depth int32
if err := rows.Scan(&productID, &boundCategoryID, &categoryID, &parentID, &name, &level, &depth); err != nil {
return fmt.Errorf("scan product category summary: %w", err)
return nil, fmt.Errorf("scan product category summary: %w", err)
}
productKey, boundKey := formatID(productID), formatID(boundCategoryID)
categoryByProduct := byProductCategory[productKey]
@ -3556,13 +3586,10 @@ ORDER BY product_id, bound_category_id, depth DESC`, args...)
})
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterate product category summaries: %w", err)
return nil, fmt.Errorf("iterate product category summaries: %w", err)
}
for productID, categories := range byProductCategory {
product := products[productID]
if product == nil {
continue
}
productCategories := make([]ProductCategorySummaryRecord, 0, len(categories))
for _, category := range categories {
if category.ParentID != nil {
for _, node := range category.Path {
@ -3572,17 +3599,18 @@ ORDER BY product_id, bound_category_id, depth DESC`, args...)
}
}
}
product.ProductCategories = append(product.ProductCategories, *category)
productCategories = append(productCategories, *category)
}
sort.Slice(product.ProductCategories, func(i, j int) bool {
left, right := product.ProductCategories[i], product.ProductCategories[j]
sort.Slice(productCategories, func(i, j int) bool {
left, right := productCategories[i], productCategories[j]
if left.Level != right.Level {
return left.Level < right.Level
}
return left.ID < right.ID
})
result[productID] = productCategories
}
return nil
return result, nil
}
func (r *ProductRepository) populateProductGroupSummaries(ctx context.Context, productIDs []int64, products map[string]*CategoryProductRecord, scope StoreScope) error {

View File

@ -4,6 +4,7 @@ import (
"testing"
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
)
func TestProductCategoryFromCreateKeepsPlatformIdentifiers(t *testing.T) {
@ -34,6 +35,43 @@ func TestProductCategoryFromCreateKeepsPlatformIdentifiers(t *testing.T) {
}
}
func TestToProtoProductCategoryIncludesRootPath(t *testing.T) {
rootID := "1001"
value := &repository.ProductCategoryRecord{
ID: "3003", Name: "连衣裙", Level: 3, ParentID: "2002",
Path: []repository.ProductCategoryPathNodeRecord{{
ID: "1001", Name: "服饰", Level: 1,
}, {
ID: "2002", Name: "女装", Level: 2, ParentID: &rootID,
}, {
ID: "3003", Name: "连衣裙", Level: 3, ParentID: stringPtr("2002"),
}},
}
response := toProtoProductCategory(value)
if len(response.GetPath()) != 3 || response.GetPath()[0].GetParentCategoryId() != "" || response.GetPath()[2].GetProductCategoryId() != "3003" {
t.Fatalf("category path = %#v", response.GetPath())
}
}
func TestToProtoProductIncludesStandardCategoryPath(t *testing.T) {
product := toProtoProduct(&repository.ProductRecord{
ID: "9001",
ProductCategories: []repository.ProductCategorySummaryRecord{{
ID: "3003", Name: "连衣裙", Level: 3, ParentID: stringPtr("2002"), ParentName: "女装",
Path: []repository.ProductCategoryPathNodeRecord{{
ID: "1001", Name: "服饰", Level: 1,
}, {
ID: "3003", Name: "连衣裙", Level: 3, ParentID: stringPtr("2002"),
}},
}},
}, nil)
if len(product.GetProductCategories()) != 1 || len(product.GetProductCategories()[0].GetPath()) != 2 {
t.Fatalf("product categories = %#v", product.GetProductCategories())
}
}
func stringPtr(value string) *string { return &value }
func TestProductCategoryFromCreateRejectsMismatchedPlatformParent(t *testing.T) {
_, err := (&ProductServer{}).productCategoryFromCreate(&productv1.CreateProductCategoryInput{
Name: "root",

View File

@ -57,7 +57,14 @@ func (s *ProductServer) ListProductCategories(ctx context.Context, req *productv
return nil, status.Error(codes.InvalidArgument, err.Error())
}
}
values, err := s.repo.ListProductCategories(ctx, id)
if req.PlatformCategoryId != nil && req.GetPlatformCategoryId() <= 0 {
return nil, status.Error(codes.InvalidArgument, "platform_category_id must be positive")
}
values, err := s.repo.ListProductCategories(ctx, repository.ProductCategoryListFilter{
ProductCategoryID: id,
PlatformCategoryID: req.PlatformCategoryId,
Name: strings.TrimSpace(req.GetName()),
})
if err != nil {
return nil, productCategoryGRPCError(err)
}
@ -255,6 +262,14 @@ func toProtoProductCategory(value *repository.ProductCategoryRecord) *productv1.
for _, child := range value.Children {
out.Children = append(out.Children, toProtoProductCategory(child))
}
for _, node := range value.Path {
out.Path = append(out.Path, &productv1.ProductCategoryPathNode{
ProductCategoryId: node.ID,
Name: node.Name,
Level: node.Level,
ParentCategoryId: node.ParentID,
})
}
return out
}

View File

@ -2889,7 +2889,7 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
})
}
return &productv1.Product{
result := &productv1.Product{
ProductId: product.ID,
SpuNo: product.SPUNo,
Title: product.Title,
@ -2924,6 +2924,26 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
GroupIds: append([]string(nil), product.GroupIDs...),
ProductCategoryIds: append([]string(nil), product.ProductCategoryIDs...),
}
for _, category := range product.ProductCategories {
item := &productv1.ProductCategorySummary{
ProductCategoryId: category.ID,
Name: category.Name,
Level: category.Level,
ParentCategoryId: category.ParentID,
ParentCategoryName: category.ParentName,
Path: make([]*productv1.ProductCategoryPathNode, 0, len(category.Path)),
}
for _, node := range category.Path {
item.Path = append(item.Path, &productv1.ProductCategoryPathNode{
ProductCategoryId: node.ID,
Name: node.Name,
Level: node.Level,
ParentCategoryId: node.ParentID,
})
}
result.ProductCategories = append(result.ProductCategories, item)
}
return result
}
func toProtoCartItemProduct(lineID string, record repository.CartItemProductRecord) *productv1.CartItemProduct {