feat: add product category validation and update product list filter to use ProductCategoryID

This commit is contained in:
BXY 2026-10-07 19:40:07 +08:00
parent cdc47d888f
commit 2776c4d55c
8 changed files with 113 additions and 33 deletions

View File

@ -42,6 +42,37 @@ type ProductCategoryListFilter struct {
Page, PageSize int32 Page, PageSize int32
} }
// ValidateProductCategory verifies that categoryID identifies a non-deleted
// standard product category in the active tenant and store. The category may
// be disabled: admin product-list filtering must still support historical
// products under disabled categories.
func (r *ProductRepository) ValidateProductCategory(ctx context.Context, categoryID string, scope StoreScope) error {
if err := requireWriteScope(scope); err != nil {
return err
}
parsed, err := parseID(categoryID, "category_id")
if err != nil {
return err
}
var exists bool
err = r.db.QueryRowContext(ctx, `
SELECT EXISTS(
SELECT 1
FROM product.product_category
WHERE id = $1
AND tenant_id = $2
AND store_id = $3
AND deleted_at IS NULL
)`, parsed, scope.TenantID, scope.StoreID).Scan(&exists)
if err != nil {
return fmt.Errorf("validate product category: %w", err)
}
if !exists {
return ErrProductCategoryNotFound
}
return nil
}
func (r *ProductRepository) CreateProductCategory(ctx context.Context, root *ProductCategoryRecord, scope StoreScope) (*ProductCategoryRecord, error) { func (r *ProductRepository) CreateProductCategory(ctx context.Context, root *ProductCategoryRecord, scope StoreScope) (*ProductCategoryRecord, error) {
if root == nil || !scope.Valid() { if root == nil || !scope.Valid() {
return nil, errors.New("product category and store scope are required") return nil, errors.New("product category and store scope are required")

View File

@ -278,17 +278,20 @@ type CategoryProductRecord struct {
// ProductListFilter contains the optional constraints for an admin product list. // ProductListFilter contains the optional constraints for an admin product list.
type ProductListFilter struct { type ProductListFilter struct {
CreatedAtFrom *time.Time CreatedAtFrom *time.Time
CreatedAtTo *time.Time CreatedAtTo *time.Time
TitleKeyword string TitleKeyword string
SPUNo string SPUNo string
GroupID string GroupID string
CategoryID string // ProductCategoryID identifies the standard business taxonomy stored in
GoodsType *int32 // product.product_category. It is intentionally separate from storefront
SoldQuantityMin *int64 // catalog categories and product groups.
SoldQuantityMax *int64 ProductCategoryID string
PriceMin *int64 GoodsType *int32
PriceMax *int64 SoldQuantityMin *int64
SoldQuantityMax *int64
PriceMin *int64
PriceMax *int64
} }
// CategoryRecord is the persistence model for product.catalog_category. // CategoryRecord is the persistence model for product.catalog_category.
@ -2839,18 +2842,33 @@ func productListWhere(filter ProductListFilter, scope StoreScope) (string, []any
AND pc.store_id = p.store_id AND pc.store_id = p.store_id
)`, filter.GroupID) )`, filter.GroupID)
} }
if filter.CategoryID != "" { if filter.ProductCategoryID != "" {
args = append(args, filter.CategoryID) args = append(args, filter.ProductCategoryID)
argPos := len(args) argPos := len(args)
predicates = append(predicates, fmt.Sprintf(`EXISTS ( predicates = append(predicates, fmt.Sprintf(`EXISTS (
WITH RECURSIVE category_descendants AS (
SELECT c.id
FROM product.product_category c
WHERE c.id = $%d
AND c.tenant_id = p.tenant_id
AND c.store_id = p.store_id
AND c.deleted_at IS NULL
UNION
SELECT child.id
FROM product.product_category child
JOIN category_descendants parent ON child.parent_id = parent.id
WHERE child.tenant_id = p.tenant_id
AND child.store_id = p.store_id
AND child.deleted_at IS NULL
)
SELECT 1 SELECT 1
FROM product.product_catalog_bindings pcb FROM product.product_category_bindings pcb
JOIN product.catalog_category pc ON pc.id = pcb.category_id JOIN category_descendants descendant ON descendant.id = pcb.product_category_id
WHERE pcb.product_id = p.id WHERE pcb.product_id = p.id
AND pc.node_type = 1 AND pcb.tenant_id = p.tenant_id
AND pc.store_id = p.store_id AND pcb.store_id = p.store_id
AND (pcb.category_id = $%d OR pc.parent_id = $%d) AND pcb.deleted_at IS NULL
)`, argPos, argPos)) )`, argPos))
} }
if filter.GoodsType != nil { if filter.GoodsType != nil {
add("p.goods_type = $%d", *filter.GoodsType) add("p.goods_type = $%d", *filter.GoodsType)

View File

@ -1,6 +1,9 @@
package repository package repository
import "testing" import (
"strings"
"testing"
)
func TestEscapeLikeLiteral(t *testing.T) { func TestEscapeLikeLiteral(t *testing.T) {
input := `100%_off\\bundle` input := `100%_off\\bundle`
@ -51,3 +54,23 @@ func TestReplaceProductGroupBindingsRequiresStoreScope(t *testing.T) {
t.Fatalf("err = %v, want %v", err, ErrStoreScopeRequired) t.Fatalf("err = %v, want %v", err, ErrStoreScopeRequired)
} }
} }
func TestProductListWhereUsesBusinessProductCategoryTree(t *testing.T) {
where, args := productListWhere(ProductListFilter{ProductCategoryID: "2001"}, StoreScope{StoreID: 1001})
for _, expected := range []string{
"WITH RECURSIVE category_descendants",
"product.product_category c",
"product.product_category_bindings pcb",
"pcb.product_category_id",
} {
if !strings.Contains(where, expected) {
t.Fatalf("category predicate missing %q:\n%s", expected, where)
}
}
if strings.Contains(where, "product.product_catalog_bindings") {
t.Fatalf("category predicate must not query storefront catalog bindings:\n%s", where)
}
if len(args) != 2 || args[0] != int64(1001) || args[1] != "2001" {
t.Fatalf("args = %#v, want [1001 2001]", args)
}
}

View File

@ -21,8 +21,8 @@ func TestProductListFilterFromRequestNormalizesImageFilters(t *testing.T) {
if filter.TitleKeyword != "coffee" { if filter.TitleKeyword != "coffee" {
t.Fatalf("TitleKeyword = %q, want coffee", filter.TitleKeyword) t.Fatalf("TitleKeyword = %q, want coffee", filter.TitleKeyword)
} }
if filter.CategoryID != "11111" { if filter.ProductCategoryID != "11111" {
t.Fatalf("CategoryID = %q, want 11111", filter.CategoryID) t.Fatalf("ProductCategoryID = %q, want 11111", filter.ProductCategoryID)
} }
if filter.PriceMin == nil || *filter.PriceMin != 0 { if filter.PriceMin == nil || *filter.PriceMin != 0 {
t.Fatalf("PriceMin = %v, want explicit zero", filter.PriceMin) t.Fatalf("PriceMin = %v, want explicit zero", filter.PriceMin)

View File

@ -677,15 +677,15 @@ func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListPro
return nil, status.Errorf(codes.Internal, "validate product group filter: %v", err) return nil, status.Errorf(codes.Internal, "validate product group filter: %v", err)
} }
} }
if filter.CategoryID != "" { if filter.ProductCategoryID != "" {
if err := s.repo.ValidateCatalogCategory(dbCtx, filter.CategoryID, scope); err != nil { if err := s.repo.ValidateProductCategory(dbCtx, filter.ProductCategoryID, scope); err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
if errors.Is(err, repository.ErrInvalidCatalogCategory) { if errors.Is(err, repository.ErrProductCategoryNotFound) {
return nil, status.Error(codes.InvalidArgument, err.Error()) return nil, status.Error(codes.InvalidArgument, err.Error())
} }
s.observer.Logger(ctx).Error("validate catalog category filter failed", zap.String("category_id", filter.CategoryID), zap.Error(err)) s.observer.Logger(ctx).Error("validate product category filter failed", zap.String("category_id", filter.ProductCategoryID), zap.Error(err))
return nil, status.Errorf(codes.Internal, "validate catalog category filter: %v", err) return nil, status.Errorf(codes.Internal, "validate product category filter: %v", err)
} }
} }
@ -718,10 +718,10 @@ func productListFilterFromRequest(req *productv1.ListProductsRequest) (repositor
return repository.ProductListFilter{}, errors.New("request is required") return repository.ProductListFilter{}, errors.New("request is required")
} }
filter := repository.ProductListFilter{ filter := repository.ProductListFilter{
TitleKeyword: strings.TrimSpace(req.GetTitleKeyword()), TitleKeyword: strings.TrimSpace(req.GetTitleKeyword()),
SPUNo: strings.TrimSpace(req.GetSpuNo()), SPUNo: strings.TrimSpace(req.GetSpuNo()),
GroupID: strings.TrimSpace(req.GetGroupId()), GroupID: strings.TrimSpace(req.GetGroupId()),
CategoryID: strings.TrimSpace(req.GetCategoryId()), ProductCategoryID: strings.TrimSpace(req.GetCategoryId()),
} }
if utf8.RuneCountInString(filter.TitleKeyword) > maxProductTitleLength { if utf8.RuneCountInString(filter.TitleKeyword) > maxProductTitleLength {
return repository.ProductListFilter{}, fmt.Errorf("title_keyword must contain at most %d characters", maxProductTitleLength) return repository.ProductListFilter{}, fmt.Errorf("title_keyword must contain at most %d characters", maxProductTitleLength)
@ -734,8 +734,8 @@ func productListFilterFromRequest(req *productv1.ListProductsRequest) (repositor
return repository.ProductListFilter{}, err return repository.ProductListFilter{}, err
} }
} }
if filter.CategoryID != "" { if filter.ProductCategoryID != "" {
if err := validatePositiveID(filter.CategoryID, "category_id"); err != nil { if err := validatePositiveID(filter.ProductCategoryID, "category_id"); err != nil {
return repository.ProductListFilter{}, err return repository.ProductListFilter{}, err
} }
} }

View File

@ -202,6 +202,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_bindings_active
ON product.product_category_bindings (product_id, product_category_id) WHERE deleted_at IS NULL; ON product.product_category_bindings (product_id, product_category_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category
ON product.product_category_bindings (store_id, product_category_id) WHERE deleted_at IS NULL; ON product.product_category_bindings (store_id, product_category_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_product
ON product.product_category_bindings (store_id, product_category_id, product_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_product CREATE INDEX IF NOT EXISTS idx_product_category_bindings_product
ON product.product_category_bindings (store_id, product_id) WHERE deleted_at IS NULL; ON product.product_category_bindings (store_id, product_id) WHERE deleted_at IS NULL;

View File

@ -4,3 +4,7 @@
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_products_store_active_created_id CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_products_store_active_created_id
ON product.products (store_id, created_at DESC, id DESC) ON product.products (store_id, created_at DESC, id DESC)
WHERE deleted_at IS NULL; WHERE deleted_at IS NULL;
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_product_category_bindings_category_product
ON product.product_category_bindings (store_id, product_category_id, product_id)
WHERE deleted_at IS NULL;

View File

@ -197,6 +197,8 @@ CREATE TABLE IF NOT EXISTS product.product_category_bindings (
); );
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_bindings_active CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_bindings_active
ON product.product_category_bindings (product_id, product_category_id) WHERE deleted_at IS NULL; ON product.product_category_bindings (product_id, product_category_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_product
ON product.product_category_bindings (store_id, product_category_id, product_id) WHERE deleted_at IS NULL;
CREATE TABLE IF NOT EXISTS product.product_items ( CREATE TABLE IF NOT EXISTS product.product_items (
id BIGINT PRIMARY KEY, id BIGINT PRIMARY KEY,