feat: update product group handling to support leaf groups and brand product bindings

This commit is contained in:
BXY 2026-10-28 15:27:32 +08:00
parent 99e9b200d9
commit d1a4207d3e
4 changed files with 269 additions and 70 deletions

View File

@ -354,9 +354,18 @@ func (r *ProductRepository) ReplaceProductsGroup(ctx context.Context, productIDs
defer tx.Rollback()
err = tx.QueryRowContext(ctx, `
SELECT id
FROM product.catalog_category
WHERE id = $1 AND node_type = 2 AND level = 2 AND store_id = $2
SELECT c.id
FROM product.catalog_category AS c
WHERE c.id = $1
AND c.node_type = 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 = $2
AND child.node_type = 2
)
`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID)
if errors.Is(err, sql.ErrNoRows) {
return 0, fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID)

View File

@ -388,12 +388,20 @@ type CategoryRecord struct {
Version int32
// ProductCount is populated when listing product groups.
ProductCount int64
// ProductIDs is populated for second-level product groups when listing groups.
ProductIDs []string
// IsLeaf and BrandProducts are populated when listing product groups.
IsLeaf bool
BrandProducts []GroupBrandProductRecord
// Children is populated for catalog-category tree operations.
Children []CategoryRecord
}
// GroupBrandProductRecord is one leaf group's direct product bindings for a brand.
type GroupBrandProductRecord struct {
BrandID string
BrandName string
ProductIDs []string
}
// 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) {
@ -1397,10 +1405,10 @@ func pointerStringSlice(value *[]string) []string {
return *value
}
// AddProductsToGroup binds every product to a second-level product group in one transaction.
// AddProductsToGroup binds every product to a leaf product group in one transaction.
// Existing bindings are retained and duplicate bindings are ignored.
func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID string, bindingIDs, productIDs []string, scope StoreScope) error {
return r.addProductsToCategoryNode(ctx, groupID, bindingIDs, productIDs, 2, 2, "group", scope)
return r.addProductsToCategoryNode(ctx, groupID, bindingIDs, productIDs, 2, -1, "group", scope)
}
// AddProductsToCategory binds every product to a terminal catalog category at
@ -1453,7 +1461,7 @@ WHERE c.id = $1
SELECT 1 FROM product.catalog_category child
WHERE child.parent_id = c.id
AND child.store_id = $3
AND child.node_type = 1
AND child.node_type = $2
)))
`, parsedNodeID, nodeType, scope.StoreID, level).Scan(&parsedNodeID)
if errors.Is(err, sql.ErrNoRows) {
@ -1552,9 +1560,18 @@ func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID
defer tx.Rollback()
err = tx.QueryRowContext(ctx, `
SELECT id
FROM product.catalog_category
WHERE id = $1 AND node_type = 2 AND level = 2 AND store_id = $2
SELECT c.id
FROM product.catalog_category AS c
WHERE c.id = $1
AND c.node_type = 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 = $2
AND child.node_type = 2
)
`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID)
if errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID)
@ -1975,14 +1992,20 @@ func replaceProductGroupBindings(ctx context.Context, tx *sql.Tx, productID stri
args[index] = groupID
}
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
SELECT id
FROM product.catalog_category
WHERE node_type = 2
AND level = 2
AND store_id = $%d
AND id IN (%s)
SELECT c.id
FROM product.catalog_category AS c
WHERE c.node_type = 2
AND c.store_id = $%d
AND c.id IN (%s)
AND NOT EXISTS (
SELECT 1
FROM product.catalog_category child
WHERE child.parent_id = c.id
AND child.store_id = $%d
AND child.node_type = 2
)
FOR KEY SHARE
`, len(args)+1, strings.Join(placeholders, ", ")), append(args, scope.StoreID)...)
`, len(args)+1, strings.Join(placeholders, ", "), len(args)+1), append(args, scope.StoreID)...)
if err != nil {
return fmt.Errorf("validate product groups: %w", err)
}
@ -3427,7 +3450,7 @@ ORDER BY pi.product_id ASC, pi.price ASC, pi.id ASC
return result, nil
}
// ValidateProductGroup verifies that a second-level group belongs to the current store.
// ValidateProductGroup verifies that a leaf group belongs to the current store.
func (r *ProductRepository) ValidateProductGroup(ctx context.Context, groupID string, scope StoreScope) error {
if err := requireWriteScope(scope); err != nil {
return err
@ -3438,9 +3461,18 @@ func (r *ProductRepository) ValidateProductGroup(ctx context.Context, groupID st
}
var found int64
err = r.db.QueryRowContext(ctx, `
SELECT id
FROM product.catalog_category
WHERE id = $1 AND node_type = 2 AND level = 2 AND store_id = $2
SELECT c.id
FROM product.catalog_category AS c
WHERE c.id = $1
AND c.node_type = 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 = $2
AND child.node_type = 2
)
`, parsedGroupID, scope.StoreID).Scan(&found)
if errors.Is(err, sql.ErrNoRows) {
return ErrInvalidProductGroup
@ -4275,10 +4307,16 @@ ORDER BY level ASC, sort_num ASC, id ASC
return categories, nil
}
// ListGroupNodes loads product group nodes.
func (r *ProductRepository) ListGroupNodes(ctx context.Context, filter GroupListFilter, scope StoreScope) ([]*CategoryRecord, error) {
// ListGroupNodes loads one page of product group nodes and their leaf-brand bindings.
func (r *ProductRepository) ListGroupNodes(ctx context.Context, filter GroupListFilter, page, pageSize int32, scope StoreScope) ([]*CategoryRecord, int64, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
return nil, 0, err
}
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 20
}
firstLevelName := strings.TrimSpace(filter.FirstLevelName)
secondLevelName := strings.TrimSpace(filter.SecondLevelName)
@ -4286,6 +4324,32 @@ func (r *ProductRepository) ListGroupNodes(ctx context.Context, filter GroupList
firstLevelName = escapeLikeLiteral(firstLevelName)
secondLevelName = escapeLikeLiteral(secondLevelName)
}
var total int64
if err := r.db.QueryRowContext(ctx, `
SELECT COUNT(*)
FROM product.catalog_category AS c
LEFT JOIN product.catalog_category AS parent ON parent.id = c.parent_id
AND parent.store_id = c.store_id
AND parent.node_type = 2
WHERE c.node_type = 2
AND c.store_id = $1
AND ($2 = false OR c.status = 1)
AND ($3 = '' OR CASE
WHEN $5 THEN LOWER(CASE WHEN c.level = 1 THEN c.name ELSE COALESCE(parent.name, '') END) = LOWER($3)
ELSE CASE WHEN c.level = 1 THEN c.name ELSE COALESCE(parent.name, '') END ILIKE ('%' || $3 || '%') ESCAPE '\\'
END)
AND ($4 = '' OR (c.level = 2 AND CASE
WHEN $5 THEN LOWER(c.name) = LOWER($4)
ELSE c.name ILIKE ('%' || $4 || '%') ESCAPE '\\'
END))
`, scope.StoreID, filter.OnlyVisible, firstLevelName, secondLevelName, filter.ExactMatch).Scan(&total); err != nil {
return nil, 0, fmt.Errorf("count group nodes: %w", err)
}
if total == 0 {
return []*CategoryRecord{}, 0, nil
}
offset := int64(page-1) * int64(pageSize)
rows, err := r.db.QueryContext(ctx, `
SELECT c.id,
c.node_type,
@ -4298,11 +4362,13 @@ SELECT c.id,
c.campaign_id,
c.version,
COUNT(p.id) AS product_count,
COALESCE(
json_agg(p.id::text ORDER BY p.created_at DESC, p.id DESC)
FILTER (WHERE c.level = 2 AND p.id IS NOT NULL),
'[]'::json
)::text AS product_ids
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 = 2
) AS is_leaf
FROM product.catalog_category AS c
LEFT JOIN product.catalog_category AS parent ON parent.id = c.parent_id
AND parent.store_id = c.store_id
@ -4324,9 +4390,10 @@ WHERE c.node_type = 2
END))
GROUP BY c.id
ORDER BY c.sort_num ASC, c.id ASC
`, scope.StoreID, filter.OnlyVisible, firstLevelName, secondLevelName, filter.ExactMatch)
LIMIT $6 OFFSET $7
`, scope.StoreID, filter.OnlyVisible, firstLevelName, secondLevelName, filter.ExactMatch, pageSize, offset)
if err != nil {
return nil, fmt.Errorf("query group nodes: %w", err)
return nil, 0, fmt.Errorf("query group nodes: %w", err)
}
defer rows.Close()
@ -4334,15 +4401,116 @@ ORDER BY c.sort_num ASC, c.id ASC
for rows.Next() {
group, err := scanGroup(rows)
if err != nil {
return nil, err
return nil, 0, err
}
groups = append(groups, group)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate group nodes: %w", err)
return nil, 0, fmt.Errorf("iterate group nodes: %w", err)
}
if err := r.populateGroupBrandProducts(ctx, groups, scope); err != nil {
return nil, 0, err
}
return groups, nil
return groups, total, nil
}
func (r *ProductRepository) populateGroupBrandProducts(ctx context.Context, groups []*CategoryRecord, scope StoreScope) error {
leafIDs := make([]int64, 0, len(groups))
groupsByID := make(map[string]*CategoryRecord, len(groups))
for _, group := range groups {
if !group.IsLeaf {
continue
}
id, err := parseID(group.ID, "group_id")
if err != nil {
return err
}
leafIDs = append(leafIDs, id)
groupsByID[group.ID] = group
}
if len(leafIDs) == 0 {
return nil
}
placeholders, idArgs := productIDPlaceholders(leafIDs, 3)
args := append([]any{scope.TenantID, scope.StoreID}, idArgs...)
rows, err := r.db.QueryContext(ctx, `
SELECT c.id,
COALESCE(p.brand_id, 0) AS brand_id,
CASE
WHEN p.brand_id IS NULL THEN '未设置品牌'
WHEN b.id IS NULL THEN '品牌已删除'
ELSE b.name
END AS brand_name,
p.id
FROM product.catalog_category AS c
JOIN product.product_catalog_bindings AS binding ON binding.category_id = c.id
JOIN product.products AS p ON p.id = binding.product_id
AND p.tenant_id = $1
AND p.store_id = $2
AND p.deleted_at IS NULL
LEFT JOIN product.brands AS b ON b.id = p.brand_id
AND b.tenant_id = $1
AND b.store_id = $2
AND b.deleted_at IS NULL
WHERE c.id IN (`+placeholders+`)
AND c.node_type = 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 = $2
AND child.node_type = 2
)
ORDER BY c.id ASC,
CASE WHEN p.brand_id IS NULL THEN 1 ELSE 0 END ASC,
LOWER(CASE
WHEN p.brand_id IS NULL THEN '未设置品牌'
WHEN b.id IS NULL THEN '品牌已删除'
ELSE b.name
END) ASC,
COALESCE(p.brand_id, 0) ASC,
p.created_at DESC,
p.id DESC`, args...)
if err != nil {
return fmt.Errorf("query group brand products: %w", err)
}
defer rows.Close()
lastBrandKey := make(map[string]string, len(groupsByID))
for rows.Next() {
var groupID, brandID, productID int64
var name string
if err := rows.Scan(&groupID, &brandID, &name, &productID); err != nil {
return fmt.Errorf("scan group brand product: %w", err)
}
groupKey := formatID(groupID)
group := groupsByID[groupKey]
if group == nil {
continue
}
brandKey := fmt.Sprintf("%d", brandID)
if lastBrandKey[groupKey] != brandKey {
brandIDValue := ""
if brandID != 0 {
brandIDValue = formatID(brandID)
}
group.BrandProducts = append(group.BrandProducts, GroupBrandProductRecord{
BrandID: brandIDValue,
BrandName: name,
ProductIDs: []string{},
})
lastBrandKey[groupKey] = brandKey
}
brand := &group.BrandProducts[len(group.BrandProducts)-1]
brand.ProductIDs = append(brand.ProductIDs, formatID(productID))
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterate group brand products: %w", err)
}
return nil
}
func (r *ProductRepository) loadProductByID(ctx context.Context, productID string, scope StoreScope) (*ProductRecord, error) {
@ -5195,18 +5363,18 @@ func scanInventory(scanner rowScanner) (*InventoryRecord, error) {
func scanGroup(scanner rowScanner) (*CategoryRecord, error) {
var (
rec CategoryRecord
id int64
parentID sql.NullInt64
imageIDsJSON []byte
nodeType int16
level int16
status int16
campaignID sql.NullInt64
productIDsJSON []byte
rec CategoryRecord
id int64
parentID sql.NullInt64
imageIDsJSON []byte
nodeType int16
level int16
status int16
campaignID sql.NullInt64
isLeaf bool
)
if err := scanner.Scan(
&id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status, &campaignID, &rec.Version, &rec.ProductCount, &productIDsJSON,
&id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status, &campaignID, &rec.Version, &rec.ProductCount, &isLeaf,
); err != nil {
return nil, fmt.Errorf("scan group: %w", err)
}
@ -5222,11 +5390,7 @@ func scanGroup(scanner rowScanner) (*CategoryRecord, error) {
return nil, fmt.Errorf("unmarshal group image_ids: %w", err)
}
rec.ImageIDs = imageIDs
productIDs, err := parseStringArrayJSON(string(productIDsJSON))
if err != nil {
return nil, fmt.Errorf("unmarshal group product_ids: %w", err)
}
rec.ProductIDs = productIDs
rec.IsLeaf = isLeaf
rec.Status = int32(status)
if campaignID.Valid {
rec.CampaignID = formatID(campaignID.Int64)

View File

@ -30,27 +30,35 @@ func TestCategoryImageIDsRoundTripThroughExistingProtoField(t *testing.T) {
}
}
func TestGroupNodeIncludesProductIDsOnlyForSecondLevelGroups(t *testing.T) {
func TestGroupNodeIncludesBrandProductsOnlyForLeafGroups(t *testing.T) {
parent := toProtoGroupNode(&repository.CategoryRecord{
ID: "1001",
Level: 1,
ProductIDs: []string{"legacy-binding"},
ID: "1001",
Level: 1,
IsLeaf: false,
})
if parent.GetProductIds() != nil {
t.Fatalf("parent product_ids = %#v, want omitted", parent.GetProductIds())
if parent.GetIsLeaf() || parent.GetBrands() != nil {
t.Fatalf("parent = %#v, want non-leaf without brands", parent)
}
leaf := toProtoGroupNode(&repository.CategoryRecord{
ID: "1002",
Level: 2,
ProductIDs: []string{"2002", "2001"},
ID: "1002",
Level: 1,
IsLeaf: true,
BrandProducts: []repository.GroupBrandProductRecord{{
BrandID: "3001",
BrandName: "Brand",
ProductIDs: []string{"2002", "2001"},
}},
})
if got := leaf.GetProductIds(); len(got) != 2 || got[0] != "2002" || got[1] != "2001" {
t.Fatalf("leaf product_ids = %#v", got)
if !leaf.GetIsLeaf() || len(leaf.GetBrands()) != 1 {
t.Fatalf("leaf = %#v, want one brand", leaf)
}
if got := leaf.GetBrands()[0].GetProductIds(); len(got) != 2 || got[0] != "2002" || got[1] != "2001" {
t.Fatalf("brand product_ids = %#v", got)
}
emptyLeaf := toProtoGroupNode(&repository.CategoryRecord{ID: "1003", Level: 2})
if got := emptyLeaf.GetProductIds(); got == nil || len(got) != 0 {
t.Fatalf("empty leaf product_ids = %#v, want []", got)
emptyLeaf := toProtoGroupNode(&repository.CategoryRecord{ID: "1003", Level: 2, IsLeaf: true})
if got := emptyLeaf.GetBrands(); got == nil || len(got) != 0 {
t.Fatalf("empty leaf brands = %#v, want []", got)
}
}

View File

@ -1025,7 +1025,7 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1
if targetNodeType == 2 {
if err := s.repo.ValidateProductGroup(ctx, req.GetCategoryId(), scope); err != nil {
if errors.Is(err, repository.ErrInvalidProductGroup) {
return nil, status.Error(codes.NotFound, "second-level product group not found")
return nil, status.Error(codes.NotFound, "leaf product group not found")
}
return nil, status.Errorf(codes.Internal, "validate product group: %v", err)
}
@ -1494,14 +1494,20 @@ func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroup
))
defer dbSpan.End()
groups, err := s.repo.ListGroupNodes(dbCtx, filter, scope)
page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize())
groups, total, err := s.repo.ListGroupNodes(dbCtx, filter, page, pageSize, scope)
if err != nil {
dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error())
s.observer.Logger(ctx).Error("list groups failed", zap.Bool("only_visible", onlyVisible), zap.Error(err))
return nil, status.Errorf(codes.Internal, "list groups: %v", err)
}
dbSpan.SetAttributes(attribute.Int("group.result_count", len(groups)))
dbSpan.SetAttributes(
attribute.Int("group.result_count", len(groups)),
attribute.Int64("group.total", total),
attribute.Int("page", int(page)),
attribute.Int("page_size", int(pageSize)),
)
protoGroups := make([]*productv1.GroupNode, 0, len(groups))
for _, group := range groups {
@ -1509,7 +1515,11 @@ func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroup
}
return &productv1.ListGroupsResponse{
Groups: protoGroups,
Groups: protoGroups,
Page: page,
PageSize: pageSize,
Total: total,
TotalPages: totalPages(total, pageSize),
}, nil
}
@ -3217,10 +3227,18 @@ func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode {
SortNum: group.SortNum,
Status: group.Status,
ProductCount: group.ProductCount,
IsLeaf: group.IsLeaf,
Version: group.Version,
}
if group.Level == 2 {
node.ProductIds = append([]string{}, group.ProductIDs...)
if group.IsLeaf {
node.Brands = make([]*productv1.GroupBrandProductSummary, 0, len(group.BrandProducts))
for _, brand := range group.BrandProducts {
node.Brands = append(node.Brands, &productv1.GroupBrandProductSummary{
BrandId: brand.BrandID,
BrandName: brand.BrandName,
ProductIds: append([]string{}, brand.ProductIDs...),
})
}
}
return node
}