diff --git a/internal/repository/product_category_repository.go b/internal/repository/product_category_repository.go index be1a3a0..3b75371 100644 --- a/internal/repository/product_category_repository.go +++ b/internal/repository/product_category_repository.go @@ -42,6 +42,37 @@ type ProductCategoryListFilter struct { 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) { if root == nil || !scope.Valid() { return nil, errors.New("product category and store scope are required") diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 9d2afa8..fdbbe9b 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -278,17 +278,20 @@ type CategoryProductRecord struct { // ProductListFilter contains the optional constraints for an admin product list. type ProductListFilter struct { - CreatedAtFrom *time.Time - CreatedAtTo *time.Time - TitleKeyword string - SPUNo string - GroupID string - CategoryID string - GoodsType *int32 - SoldQuantityMin *int64 - SoldQuantityMax *int64 - PriceMin *int64 - PriceMax *int64 + CreatedAtFrom *time.Time + CreatedAtTo *time.Time + TitleKeyword string + SPUNo string + GroupID string + // ProductCategoryID identifies the standard business taxonomy stored in + // product.product_category. It is intentionally separate from storefront + // catalog categories and product groups. + ProductCategoryID string + GoodsType *int32 + SoldQuantityMin *int64 + SoldQuantityMax *int64 + PriceMin *int64 + PriceMax *int64 } // 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 )`, filter.GroupID) } - if filter.CategoryID != "" { - args = append(args, filter.CategoryID) + if filter.ProductCategoryID != "" { + args = append(args, filter.ProductCategoryID) argPos := len(args) 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 - FROM product.product_catalog_bindings pcb - JOIN product.catalog_category pc ON pc.id = pcb.category_id + FROM product.product_category_bindings pcb + JOIN category_descendants descendant ON descendant.id = pcb.product_category_id WHERE pcb.product_id = p.id - AND pc.node_type = 1 - AND pc.store_id = p.store_id - AND (pcb.category_id = $%d OR pc.parent_id = $%d) -)`, argPos, argPos)) + AND pcb.tenant_id = p.tenant_id + AND pcb.store_id = p.store_id + AND pcb.deleted_at IS NULL +)`, argPos)) } if filter.GoodsType != nil { add("p.goods_type = $%d", *filter.GoodsType) diff --git a/internal/repository/product_repository_test.go b/internal/repository/product_repository_test.go index 9a69f63..e68d600 100644 --- a/internal/repository/product_repository_test.go +++ b/internal/repository/product_repository_test.go @@ -1,6 +1,9 @@ package repository -import "testing" +import ( + "strings" + "testing" +) func TestEscapeLikeLiteral(t *testing.T) { input := `100%_off\\bundle` @@ -51,3 +54,23 @@ func TestReplaceProductGroupBindingsRequiresStoreScope(t *testing.T) { 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) + } +} diff --git a/internal/server/list_products_filter_test.go b/internal/server/list_products_filter_test.go index 6251a6f..3c23c6c 100644 --- a/internal/server/list_products_filter_test.go +++ b/internal/server/list_products_filter_test.go @@ -21,8 +21,8 @@ func TestProductListFilterFromRequestNormalizesImageFilters(t *testing.T) { if filter.TitleKeyword != "coffee" { t.Fatalf("TitleKeyword = %q, want coffee", filter.TitleKeyword) } - if filter.CategoryID != "11111" { - t.Fatalf("CategoryID = %q, want 11111", filter.CategoryID) + if filter.ProductCategoryID != "11111" { + t.Fatalf("ProductCategoryID = %q, want 11111", filter.ProductCategoryID) } if filter.PriceMin == nil || *filter.PriceMin != 0 { t.Fatalf("PriceMin = %v, want explicit zero", filter.PriceMin) diff --git a/internal/server/product_server.go b/internal/server/product_server.go index ab05fe4..6778afc 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -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) } } - if filter.CategoryID != "" { - if err := s.repo.ValidateCatalogCategory(dbCtx, filter.CategoryID, scope); err != nil { + if filter.ProductCategoryID != "" { + if err := s.repo.ValidateProductCategory(dbCtx, filter.ProductCategoryID, scope); err != nil { dbSpan.RecordError(err) 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()) } - s.observer.Logger(ctx).Error("validate catalog category filter failed", zap.String("category_id", filter.CategoryID), zap.Error(err)) - return nil, status.Errorf(codes.Internal, "validate catalog category filter: %v", 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 product category filter: %v", err) } } @@ -718,10 +718,10 @@ func productListFilterFromRequest(req *productv1.ListProductsRequest) (repositor return repository.ProductListFilter{}, errors.New("request is required") } filter := repository.ProductListFilter{ - TitleKeyword: strings.TrimSpace(req.GetTitleKeyword()), - SPUNo: strings.TrimSpace(req.GetSpuNo()), - GroupID: strings.TrimSpace(req.GetGroupId()), - CategoryID: strings.TrimSpace(req.GetCategoryId()), + TitleKeyword: strings.TrimSpace(req.GetTitleKeyword()), + SPUNo: strings.TrimSpace(req.GetSpuNo()), + GroupID: strings.TrimSpace(req.GetGroupId()), + ProductCategoryID: strings.TrimSpace(req.GetCategoryId()), } if utf8.RuneCountInString(filter.TitleKeyword) > 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 } } - if filter.CategoryID != "" { - if err := validatePositiveID(filter.CategoryID, "category_id"); err != nil { + if filter.ProductCategoryID != "" { + if err := validatePositiveID(filter.ProductCategoryID, "category_id"); err != nil { return repository.ProductListFilter{}, err } } diff --git a/scripts/sql/02-product-schema.sql b/scripts/sql/02-product-schema.sql index b5815b2..91126fb 100644 --- a/scripts/sql/02-product-schema.sql +++ b/scripts/sql/02-product-schema.sql @@ -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; 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; +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 ON product.product_category_bindings (store_id, product_id) WHERE deleted_at IS NULL; diff --git a/scripts/sql/add-product-list-filter-indexes.sql b/scripts/sql/add-product-list-filter-indexes.sql index eabaf4d..a803903 100644 --- a/scripts/sql/add-product-list-filter-indexes.sql +++ b/scripts/sql/add-product-list-filter-indexes.sql @@ -4,3 +4,7 @@ CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_products_store_active_created_id ON product.products (store_id, created_at DESC, id DESC) 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; diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index a981da9..2e80341 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -197,6 +197,8 @@ CREATE TABLE IF NOT EXISTS product.product_category_bindings ( ); 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; +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 ( id BIGINT PRIMARY KEY,