diff --git a/internal/repository/product_batch.go b/internal/repository/product_batch.go new file mode 100644 index 0000000..10e6b04 --- /dev/null +++ b/internal/repository/product_batch.go @@ -0,0 +1,403 @@ +package repository + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + + productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" +) + +// ErrNoActiveSKU is returned when a product has no sellable/active SKUs for batch price. +var ErrNoActiveSKU = errors.New("product has no active sku") + +// ErrInvalidCatalogCategory is returned when a filter target is not a catalog category. +var ErrInvalidCatalogCategory = errors.New("category must be an existing catalog category") + +const maxProductBatchSize = 100 + +// ValidateCatalogCategory ensures categoryID is a storefront catalog category (node_type=1). +func (r *ProductRepository) ValidateCatalogCategory(ctx context.Context, categoryID string, scope StoreScope) error { + if err := requireWriteScope(scope); err != nil { + return err + } + id, err := parseID(categoryID, "category_id") + if err != nil { + return err + } + var nodeType int16 + err = r.db.QueryRowContext(ctx, ` +SELECT node_type +FROM product.catalog_category +WHERE id = $1 AND store_id = $2 +`, id, scope.StoreID).Scan(&nodeType) + if errors.Is(err, sql.ErrNoRows) { + return ErrInvalidCatalogCategory + } + if err != nil { + return fmt.Errorf("validate catalog category: %w", err) + } + if nodeType != 1 { + return ErrInvalidCatalogCategory + } + return nil +} + +func parseBatchProductIDs(productIDs []string) ([]int64, []string, error) { + if len(productIDs) == 0 { + return nil, nil, errors.New("product_ids is required") + } + seen := make(map[string]struct{}, len(productIDs)) + unique := make([]string, 0, len(productIDs)) + for _, raw := range productIDs { + id := strings.TrimSpace(raw) + if id == "" { + continue + } + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + unique = append(unique, id) + } + if len(unique) == 0 { + return nil, nil, errors.New("product_ids is required") + } + if len(unique) > maxProductBatchSize { + return nil, nil, fmt.Errorf("product_ids must contain at most %d items", maxProductBatchSize) + } + parsed := make([]int64, len(unique)) + for i, id := range unique { + n, err := parseID(id, "product_id") + if err != nil { + return nil, nil, err + } + parsed[i] = n + } + return parsed, unique, nil +} + +func productIDPlaceholders(ids []int64, start int) (string, []any) { + placeholders := make([]string, len(ids)) + args := make([]any, len(ids)) + for i, id := range ids { + placeholders[i] = fmt.Sprintf("$%d", start+i) + args[i] = id + } + return strings.Join(placeholders, ", "), args +} + +func (r *ProductRepository) lockProductsInStore(ctx context.Context, tx *sql.Tx, productIDs []int64, originalIDs []string, scope StoreScope) error { + ph, args := productIDPlaceholders(productIDs, 2) + queryArgs := append([]any{scope.StoreID}, args...) + rows, err := tx.QueryContext(ctx, fmt.Sprintf(` +SELECT id +FROM product.products +WHERE store_id = $1 + AND deleted_at IS NULL + AND id IN (%s) +FOR UPDATE +`, ph), queryArgs...) + if err != nil { + return fmt.Errorf("lock products: %w", err) + } + defer rows.Close() + + found := make(map[int64]struct{}, len(productIDs)) + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return fmt.Errorf("scan locked product: %w", err) + } + found[id] = struct{}{} + } + if err := rows.Err(); err != nil { + return fmt.Errorf("iterate locked products: %w", err) + } + for i, id := range productIDs { + if _, ok := found[id]; !ok { + return fmt.Errorf("%w: %s", ErrProductNotFound, originalIDs[i]) + } + } + return nil +} + +// BatchUpdateProductStatus sets status for every listed product using the current row version. +func (r *ProductRepository) BatchUpdateProductStatus(ctx context.Context, productIDs []string, next productv1.ProductStatus, scope StoreScope) (int32, error) { + if err := requireWriteScope(scope); err != nil { + return 0, err + } + if next != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY && + next != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && + next != productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE { + return 0, fmt.Errorf("unsupported product status") + } + parsed, originals, err := parseBatchProductIDs(productIDs) + if err != nil { + return 0, err + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return 0, fmt.Errorf("begin batch update product status: %w", err) + } + defer tx.Rollback() + + if err := r.lockProductsInStore(ctx, tx, parsed, originals, scope); err != nil { + return 0, err + } + + updated := int32(0) + for i, id := range parsed { + var previousDBStatus int16 + var currentVersion int32 + err := tx.QueryRowContext(ctx, ` +SELECT status, version +FROM product.products +WHERE id = $1 AND deleted_at IS NULL AND store_id = $2 +`, id, scope.StoreID).Scan(&previousDBStatus, ¤tVersion) + if errors.Is(err, sql.ErrNoRows) { + return 0, fmt.Errorf("%w: %s", ErrProductNotFound, originals[i]) + } + if err != nil { + return 0, fmt.Errorf("load product %s: %w", originals[i], err) + } + previous := statusFromDB(previousDBStatus) + if previous == next { + updated++ + continue + } + if next == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE { + sellable, err := hasSellableSKU(ctx, tx, id) + if err != nil { + return 0, err + } + if !sellable { + return 0, fmt.Errorf("cannot put product on sale without a sellable sku: %s", originals[i]) + } + } + res, err := tx.ExecContext(ctx, ` +UPDATE product.products +SET status = $2, version = version + 1, updated_at = NOW() +WHERE id = $1 AND version = $3 AND deleted_at IS NULL AND store_id = $4 +`, id, statusToDB(next), currentVersion, scope.StoreID) + if err != nil { + return 0, fmt.Errorf("update product status %s: %w", originals[i], err) + } + affected, err := res.RowsAffected() + if err != nil { + return 0, fmt.Errorf("rows affected for %s: %w", originals[i], err) + } + if affected == 0 { + return 0, ErrProductVersionConflict + } + updated++ + } + + if err := tx.Commit(); err != nil { + return 0, fmt.Errorf("commit batch update product status: %w", err) + } + return updated, nil +} + +// BatchDeleteProducts soft-deletes products and their SKUs in one store transaction. +func (r *ProductRepository) BatchDeleteProducts(ctx context.Context, productIDs []string, scope StoreScope) error { + if err := requireWriteScope(scope); err != nil { + return err + } + parsed, originals, err := parseBatchProductIDs(productIDs) + if err != nil { + return err + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin batch delete products: %w", err) + } + defer tx.Rollback() + + if err := r.lockProductsInStore(ctx, tx, parsed, originals, scope); err != nil { + return err + } + + ph, args := productIDPlaceholders(parsed, 2) + queryArgs := append([]any{scope.StoreID}, args...) + res, err := tx.ExecContext(ctx, fmt.Sprintf(` +UPDATE product.products +SET deleted_at = COALESCE(deleted_at, NOW()), updated_at = NOW() +WHERE store_id = $1 + AND deleted_at IS NULL + AND id IN (%s) +`, ph), queryArgs...) + if err != nil { + return fmt.Errorf("batch delete products: %w", err) + } + affected, err := res.RowsAffected() + if err != nil { + return fmt.Errorf("rows affected: %w", err) + } + if affected != int64(len(parsed)) { + return ErrProductNotFound + } + + if _, err := tx.ExecContext(ctx, fmt.Sprintf(` +UPDATE product.product_items +SET deleted_at = COALESCE(deleted_at, NOW()), updated_at = NOW() +WHERE deleted_at IS NULL + AND product_id IN (%s) +`, ph), args...); err != nil { + return fmt.Errorf("batch delete product skus: %w", err) + } + + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit batch delete products: %w", err) + } + return nil +} + +// BatchUpdateProductPricesResult counts products and SKUs updated by BatchUpdateProductPrices. +type BatchUpdateProductPricesResult struct { + UpdatedProductCount int32 + UpdatedSKUCount int32 +} + +// BatchUpdateProductPrices sets price on every active SKU of the listed products. +func (r *ProductRepository) BatchUpdateProductPrices(ctx context.Context, productIDs []string, price int64, scope StoreScope) (*BatchUpdateProductPricesResult, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + if price <= 0 { + return nil, errors.New("price must be greater than 0") + } + parsed, originals, err := parseBatchProductIDs(productIDs) + if err != nil { + return nil, err + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin batch update product prices: %w", err) + } + defer tx.Rollback() + + if err := r.lockProductsInStore(ctx, tx, parsed, originals, scope); err != nil { + return nil, err + } + + result := &BatchUpdateProductPricesResult{} + for i, id := range parsed { + res, err := tx.ExecContext(ctx, ` +UPDATE product.product_items +SET price = $2, version = version + 1, updated_at = NOW() +WHERE product_id = $1 + AND deleted_at IS NULL + AND is_archived = FALSE +`, id, price) + if err != nil { + return nil, fmt.Errorf("update sku prices for %s: %w", originals[i], err) + } + skuCount, err := res.RowsAffected() + if err != nil { + return nil, fmt.Errorf("sku rows affected for %s: %w", originals[i], err) + } + if skuCount == 0 { + return nil, fmt.Errorf("%w: %s", ErrNoActiveSKU, originals[i]) + } + if _, err := tx.ExecContext(ctx, ` +UPDATE product.products +SET version = version + 1, updated_at = NOW() +WHERE id = $1 AND deleted_at IS NULL AND store_id = $2 +`, id, scope.StoreID); err != nil { + return nil, fmt.Errorf("bump product version %s: %w", originals[i], err) + } + result.UpdatedProductCount++ + result.UpdatedSKUCount += int32(skuCount) + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit batch update product prices: %w", err) + } + return result, nil +} + +// ReplaceProductsGroup clears all group bindings for the products and binds them to groupID. +func (r *ProductRepository) ReplaceProductsGroup(ctx context.Context, productIDs []string, groupID string, bindingIDs []string, scope StoreScope) (int32, error) { + if err := requireWriteScope(scope); err != nil { + return 0, err + } + parsed, originals, err := parseBatchProductIDs(productIDs) + if err != nil { + return 0, err + } + if len(bindingIDs) != len(parsed) { + return 0, errors.New("binding ids must match product ids") + } + parsedGroupID, err := parseID(groupID, "group_id") + if err != nil { + return 0, err + } + parsedBindingIDs := make([]int64, len(bindingIDs)) + for i, bindingID := range bindingIDs { + parsedBindingIDs[i], err = parseID(bindingID, "category binding id") + if err != nil { + return 0, err + } + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return 0, fmt.Errorf("begin replace products group: %w", err) + } + defer tx.Rollback() + + err = tx.QueryRowContext(ctx, ` +SELECT id +FROM product.catalog_category +WHERE id = $1 AND node_type = 2 AND store_id = $2 +`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID) + if errors.Is(err, sql.ErrNoRows) { + return 0, fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID) + } + if err != nil { + return 0, fmt.Errorf("query group %s: %w", groupID, err) + } + + if err := r.lockProductsInStore(ctx, tx, parsed, originals, scope); err != nil { + return 0, err + } + + ph, args := productIDPlaceholders(parsed, 2) + queryArgs := append([]any{scope.StoreID}, args...) + if _, err := tx.ExecContext(ctx, fmt.Sprintf(` +DELETE FROM product.product_catalog_bindings pcb +USING product.catalog_category pc +WHERE pcb.category_id = pc.id + AND pc.node_type = 2 + AND pc.store_id = $1 + AND pcb.product_id IN (%s) +`, ph), queryArgs...); err != nil { + return 0, fmt.Errorf("clear group bindings: %w", err) + } + + valuePlaceholders := make([]string, len(parsed)) + insertArgs := make([]any, 0, len(parsed)*3) + for i, productID := range parsed { + base := i * 3 + valuePlaceholders[i] = fmt.Sprintf("($%d, $%d, $%d)", base+1, base+2, base+3) + insertArgs = append(insertArgs, parsedBindingIDs[i], productID, parsedGroupID) + } + if _, err := tx.ExecContext(ctx, fmt.Sprintf(` +INSERT INTO product.product_catalog_bindings (id, product_id, category_id) +VALUES %s +ON CONFLICT (product_id, category_id) DO NOTHING +`, strings.Join(valuePlaceholders, ", ")), insertArgs...); err != nil { + return 0, fmt.Errorf("insert group bindings: %w", err) + } + + if err := tx.Commit(); err != nil { + return 0, fmt.Errorf("commit replace products group: %w", err) + } + return int32(len(parsed)), nil +} diff --git a/internal/repository/product_batch_test.go b/internal/repository/product_batch_test.go new file mode 100644 index 0000000..4c632d5 --- /dev/null +++ b/internal/repository/product_batch_test.go @@ -0,0 +1,20 @@ +package repository + +import "testing" + +func TestParseBatchProductIDs(t *testing.T) { + parsed, unique, err := parseBatchProductIDs([]string{" 11111 ", "11111", "22222"}) + if err != nil { + t.Fatalf("parseBatchProductIDs() error = %v", err) + } + if len(unique) != 2 || unique[0] != "11111" || unique[1] != "22222" { + t.Fatalf("unique = %v, want [11111 22222]", unique) + } + if len(parsed) != 2 || parsed[0] != 11111 || parsed[1] != 22222 { + t.Fatalf("parsed = %v, want [11111 22222]", parsed) + } + + if _, _, err := parseBatchProductIDs(nil); err == nil { + t.Fatal("parseBatchProductIDs(nil) error = nil, want required") + } +} diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 52bb080..a30d1bb 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -278,6 +278,7 @@ type ProductListFilter struct { TitleKeyword string SPUNo string GroupID string + CategoryID string GoodsType *int32 SoldQuantityMin *int64 SoldQuantityMax *int64 @@ -2719,6 +2720,19 @@ func productListWhere(filter ProductListFilter, scope StoreScope) (string, []any AND pc.node_type = 2 AND pc.store_id = p.store_id )`, filter.GroupID) + } + if filter.CategoryID != "" { + args = append(args, filter.CategoryID) + argPos := len(args) + predicates = append(predicates, fmt.Sprintf(`EXISTS ( + SELECT 1 + FROM product.product_catalog_bindings pcb + JOIN product.catalog_category pc ON pc.id = pcb.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)) } if filter.GoodsType != nil { add("p.goods_type = $%d", *filter.GoodsType) diff --git a/internal/server/list_products_filter_test.go b/internal/server/list_products_filter_test.go index 3893144..6251a6f 100644 --- a/internal/server/list_products_filter_test.go +++ b/internal/server/list_products_filter_test.go @@ -11,6 +11,7 @@ func TestProductListFilterFromRequestNormalizesImageFilters(t *testing.T) { priceMax := int64(1999) filter, err := productListFilterFromRequest(&productv1.ListProductsRequest{ TitleKeyword: " coffee ", + CategoryId: " 11111 ", PriceMin: &priceMin, PriceMax: &priceMax, }) @@ -20,11 +21,23 @@ 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.PriceMin == nil || *filter.PriceMin != 0 { t.Fatalf("PriceMin = %v, want explicit zero", filter.PriceMin) } } +func TestProductListFilterFromRequestRejectsInvalidCategoryID(t *testing.T) { + _, err := productListFilterFromRequest(&productv1.ListProductsRequest{ + CategoryId: "not-a-id", + }) + if err == nil { + t.Fatal("productListFilterFromRequest() error = nil, want invalid category_id") + } +} + func TestProductListFilterFromRequestRejectsInvalidRanges(t *testing.T) { minimum := int64(2) maximum := int64(1) diff --git a/internal/server/product_batch_server.go b/internal/server/product_batch_server.go new file mode 100644 index 0000000..68cd528 --- /dev/null +++ b/internal/server/product_batch_server.go @@ -0,0 +1,177 @@ +package server + +import ( + "context" + "errors" + + "go.opentelemetry.io/otel/attribute" + otelcodes "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/trace" + "go.uber.org/zap" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" + "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" +) + +// BatchUpdateProductStatus changes lifecycle status for multiple products. +func (s *ProductServer) BatchUpdateProductStatus(ctx context.Context, req *productv1.BatchUpdateProductStatusRequest) (*productv1.BatchUpdateProductStatusResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + productIDs, err := normalizeGroupProductIDs(req.GetProductIds()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + next := req.GetStatus() + if next == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED { + return nil, status.Error(codes.InvalidArgument, "status is required") + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.batch.status", trace.WithAttributes( + attribute.Int("product.count", len(productIDs)), + attribute.Int("product.status", int(next)), + )) + defer dbSpan.End() + + updated, err := s.repo.BatchUpdateProductStatus(dbCtx, productIDs, next, scope) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + switch { + case errors.Is(err, repository.ErrProductNotFound): + return nil, status.Error(codes.NotFound, "product not found") + case errors.Is(err, repository.ErrProductVersionConflict): + return nil, status.Error(codes.Aborted, "product version conflict") + default: + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + } + return &productv1.BatchUpdateProductStatusResponse{UpdatedCount: updated}, nil +} + +// BatchDeleteProducts soft-deletes multiple products in one store. +func (s *ProductServer) BatchDeleteProducts(ctx context.Context, req *productv1.BatchDeleteProductsRequest) (*productv1.BatchDeleteProductsResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + productIDs, err := normalizeGroupProductIDs(req.GetProductIds()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.batch.delete", trace.WithAttributes( + attribute.Int("product.count", len(productIDs)), + )) + defer dbSpan.End() + + if err := s.repo.BatchDeleteProducts(dbCtx, productIDs, scope); err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + if errors.Is(err, repository.ErrProductNotFound) { + return nil, status.Error(codes.NotFound, "product not found") + } + s.observer.Logger(ctx).Error("batch delete products failed", zap.Strings("product_ids", productIDs), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "batch delete products: %v", err) + } + return &productv1.BatchDeleteProductsResponse{}, nil +} + +// BatchUpdateProductPrices sets one absolute price on all active SKUs of each product. +func (s *ProductServer) BatchUpdateProductPrices(ctx context.Context, req *productv1.BatchUpdateProductPricesRequest) (*productv1.BatchUpdateProductPricesResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + productIDs, err := normalizeGroupProductIDs(req.GetProductIds()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if req.GetPrice() <= 0 { + return nil, status.Error(codes.InvalidArgument, "price must be greater than 0") + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.batch.price", trace.WithAttributes( + attribute.Int("product.count", len(productIDs)), + attribute.Int64("product.price", req.GetPrice()), + )) + defer dbSpan.End() + + result, err := s.repo.BatchUpdateProductPrices(dbCtx, productIDs, req.GetPrice(), scope) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + switch { + case errors.Is(err, repository.ErrProductNotFound): + return nil, status.Error(codes.NotFound, "product not found") + case errors.Is(err, repository.ErrNoActiveSKU): + return nil, status.Error(codes.FailedPrecondition, err.Error()) + default: + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + } + return &productv1.BatchUpdateProductPricesResponse{ + UpdatedProductCount: result.UpdatedProductCount, + UpdatedSkuCount: result.UpdatedSKUCount, + }, nil +} + +// ReplaceProductsGroup atomically replaces group bindings for multiple products. +func (s *ProductServer) ReplaceProductsGroup(ctx context.Context, req *productv1.ReplaceProductsGroupRequest) (*productv1.ReplaceProductsGroupResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + productIDs, err := normalizeGroupProductIDs(req.GetProductIds()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + groupID := req.GetGroupId() + if err := validatePositiveSnowflakeID(groupID, "group_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + bindingIDs := make([]string, len(productIDs)) + for i := range productIDs { + bindingIDs[i] = s.idgen.NextString() + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.batch.replace_group", trace.WithAttributes( + attribute.String("group.id", groupID), + attribute.Int("product.count", len(productIDs)), + )) + defer dbSpan.End() + + updated, err := s.repo.ReplaceProductsGroup(dbCtx, productIDs, groupID, bindingIDs, scope) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + switch { + case errors.Is(err, repository.ErrCategoryNodeNotFound): + return nil, status.Error(codes.NotFound, "group not found") + case errors.Is(err, repository.ErrProductNotFound): + return nil, status.Error(codes.NotFound, "product not found") + default: + s.observer.Logger(ctx).Error("replace products group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "replace products group: %v", err) + } + } + return &productv1.ReplaceProductsGroupResponse{UpdatedCount: updated}, nil +} diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 0fafb11..657e516 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -662,6 +662,17 @@ 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 { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + if errors.Is(err, repository.ErrInvalidCatalogCategory) { + 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) + } + } products, total, err := s.repo.ListProducts(dbCtx, page, pageSize, filter, scope) if err != nil { @@ -695,6 +706,7 @@ func productListFilterFromRequest(req *productv1.ListProductsRequest) (repositor TitleKeyword: strings.TrimSpace(req.GetTitleKeyword()), SPUNo: strings.TrimSpace(req.GetSpuNo()), GroupID: strings.TrimSpace(req.GetGroupId()), + CategoryID: strings.TrimSpace(req.GetCategoryId()), } if utf8.RuneCountInString(filter.TitleKeyword) > maxProductTitleLength { return repository.ProductListFilter{}, fmt.Errorf("title_keyword must contain at most %d characters", maxProductTitleLength) @@ -707,6 +719,11 @@ func productListFilterFromRequest(req *productv1.ListProductsRequest) (repositor return repository.ProductListFilter{}, err } } + if filter.CategoryID != "" { + if err := validatePositiveID(filter.CategoryID, "category_id"); err != nil { + return repository.ProductListFilter{}, err + } + } if req.CreatedAtFrom != nil { value := req.GetCreatedAtFrom() if value < 0 {