From 0d533f019606bc6e7c330f583d400ff24ed186b4 Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Thu, 24 Sep 2026 14:31:59 +0800 Subject: [PATCH] feat: add product list filtering capabilities and corresponding validation --- internal/repository/product_repository.go | 130 +++++++++++++++--- internal/server/list_products_filter_test.go | 38 +++++ internal/server/product_server.go | 102 +++++++++++++- .../sql/add-product-list-filter-indexes.sql | 6 + 4 files changed, 254 insertions(+), 22 deletions(-) create mode 100644 internal/server/list_products_filter_test.go create mode 100644 scripts/sql/add-product-list-filter-indexes.sql diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 6d14f13..575782e 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -262,6 +262,20 @@ type CategoryProductRecord struct { UpdatedAt time.Time } +// 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 + GoodsType *int32 + SoldQuantityMin *int64 + SoldQuantityMax *int64 + PriceMin *int64 + PriceMax *int64 +} + // CategoryRecord is the persistence model for product.product_category. type CategoryRecord struct { ID string @@ -2499,8 +2513,32 @@ func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookup return results, nil } +// ValidateProductGroup verifies that a 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 + } + parsedGroupID, err := parseID(groupID, "group_id") + if err != nil { + return err + } + var found int64 + err = r.db.QueryRowContext(ctx, ` +SELECT id +FROM product.product_category +WHERE id = $1 AND node_type = 2 AND store_id = $2 +`, parsedGroupID, scope.StoreID).Scan(&found) + if errors.Is(err, sql.ErrNoRows) { + return ErrInvalidProductGroup + } + if err != nil { + return fmt.Errorf("validate product group: %w", err) + } + return nil +} + // ListProducts loads paginated summaries for all non-deleted products. -func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int32, scope StoreScope) ([]*CategoryProductRecord, int64, error) { +func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int32, filter ProductListFilter, scope StoreScope) ([]*CategoryProductRecord, int64, error) { if err := requireWriteScope(scope); err != nil { return nil, 0, err } @@ -2511,12 +2549,23 @@ func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int pageSize = 20 } + where, args := productListWhere(filter, scope) + metricJoin := ` +LEFT JOIN LATERAL ( + SELECT MIN(pi.price) AS price, + SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, + SUM(COALESCE(inv.stock_quantity, 0)) AS stock_quantity, + SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity + FROM product.product_items pi + LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id + WHERE pi.product_id = p.id + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE +) sku_summary ON TRUE` + var total int64 - if err := r.db.QueryRowContext(ctx, ` -SELECT COUNT(*) -FROM product.products -WHERE deleted_at IS NULL AND store_id = $1 -`, scope.StoreID).Scan(&total); err != nil { + countQuery := "SELECT COUNT(*) FROM product.products p " + metricJoin + " WHERE " + where + if err := r.db.QueryRowContext(ctx, countQuery, args...).Scan(&total); err != nil { return nil, 0, fmt.Errorf("count products: %w", err) } if total == 0 { @@ -2524,6 +2573,9 @@ WHERE deleted_at IS NULL AND store_id = $1 } offset := int64(page-1) * int64(pageSize) + queryArgs := append(append([]any{}, args...), pageSize, offset) + limitArg := len(args) + 1 + offsetArg := len(args) + 2 rows, err := r.db.QueryContext(ctx, ` SELECT p.updated_at, p.created_at, @@ -2536,22 +2588,10 @@ SELECT p.updated_at, COALESCE(sku_summary.sold_quantity, 0), COALESCE(sku_summary.stock_quantity, 0), COALESCE(sku_summary.locked_quantity, 0) -FROM product.products p -LEFT JOIN LATERAL ( - SELECT MIN(pi.price) AS price, - SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, - SUM(COALESCE(inv.stock_quantity, 0)) AS stock_quantity, - SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity - FROM product.product_items pi - LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id - WHERE pi.product_id = p.id - AND pi.deleted_at IS NULL - AND pi.is_archived = FALSE -) sku_summary ON TRUE -WHERE p.deleted_at IS NULL AND p.store_id = $3 +FROM product.products p `+metricJoin+` +WHERE `+where+` ORDER BY p.created_at DESC, p.id DESC -LIMIT $1 OFFSET $2 -`, pageSize, offset, scope.StoreID) +LIMIT $`+strconv.Itoa(limitArg)+` OFFSET $`+strconv.Itoa(offsetArg), queryArgs...) if err != nil { return nil, 0, fmt.Errorf("query products: %w", err) } @@ -2571,6 +2611,54 @@ LIMIT $1 OFFSET $2 return products, total, nil } +func productListWhere(filter ProductListFilter, scope StoreScope) (string, []any) { + predicates := []string{"p.deleted_at IS NULL", "p.store_id = $1"} + args := []any{scope.StoreID} + add := func(predicate string, value any) { + args = append(args, value) + predicates = append(predicates, fmt.Sprintf(predicate, len(args))) + } + if filter.CreatedAtFrom != nil { + add("p.created_at >= $%d", *filter.CreatedAtFrom) + } + if filter.CreatedAtTo != nil { + add("p.created_at <= $%d", *filter.CreatedAtTo) + } + if filter.TitleKeyword != "" { + add(`p.title ILIKE $%d ESCAPE '\'`, "%"+escapeLikeLiteral(filter.TitleKeyword)+"%") + } + if filter.SPUNo != "" { + add("p.spu_no = $%d", filter.SPUNo) + } + if filter.GroupID != "" { + add(`EXISTS ( + SELECT 1 + FROM product.product_category_bindings pcb + JOIN product.product_category pc ON pc.id = pcb.category_id + WHERE pcb.product_id = p.id + AND pcb.category_id = $%d + AND pc.node_type = 2 + AND pc.store_id = p.store_id +)`, filter.GroupID) + } + if filter.GoodsType != nil { + add("p.goods_type = $%d", *filter.GoodsType) + } + if filter.SoldQuantityMin != nil { + add("COALESCE(sku_summary.sold_quantity, 0) >= $%d", *filter.SoldQuantityMin) + } + if filter.SoldQuantityMax != nil { + add("COALESCE(sku_summary.sold_quantity, 0) <= $%d", *filter.SoldQuantityMax) + } + if filter.PriceMin != nil { + add("COALESCE(sku_summary.price, 0) >= $%d", *filter.PriceMin) + } + if filter.PriceMax != nil { + add("COALESCE(sku_summary.price, 0) <= $%d", *filter.PriceMax) + } + return strings.Join(predicates, " AND "), args +} + // SearchProducts loads storefront-visible product summaries whose titles contain // keyword. Callers cannot opt out of the visibility predicate: soft-deleted and // inventory-only products must never be exposed by keyword search. diff --git a/internal/server/list_products_filter_test.go b/internal/server/list_products_filter_test.go new file mode 100644 index 0000000..3893144 --- /dev/null +++ b/internal/server/list_products_filter_test.go @@ -0,0 +1,38 @@ +package server + +import ( + "testing" + + productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" +) + +func TestProductListFilterFromRequestNormalizesImageFilters(t *testing.T) { + priceMin := int64(0) + priceMax := int64(1999) + filter, err := productListFilterFromRequest(&productv1.ListProductsRequest{ + TitleKeyword: " coffee ", + PriceMin: &priceMin, + PriceMax: &priceMax, + }) + if err != nil { + t.Fatalf("productListFilterFromRequest() error = %v", err) + } + if filter.TitleKeyword != "coffee" { + t.Fatalf("TitleKeyword = %q, want coffee", filter.TitleKeyword) + } + if filter.PriceMin == nil || *filter.PriceMin != 0 { + t.Fatalf("PriceMin = %v, want explicit zero", filter.PriceMin) + } +} + +func TestProductListFilterFromRequestRejectsInvalidRanges(t *testing.T) { + minimum := int64(2) + maximum := int64(1) + _, err := productListFilterFromRequest(&productv1.ListProductsRequest{ + SoldQuantityMin: &minimum, + SoldQuantityMax: &maximum, + }) + if err == nil { + t.Fatal("productListFilterFromRequest() error = nil, want invalid range") + } +} diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 0bee154..ae8d3e9 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -41,6 +41,7 @@ const ( maxProductsPerGroupRequest = 100 maxCartItemProductBatchSize = 100 maxSearchKeywordLength = 50 + maxProductTitleLength = 200 ) // ProductServer implements productv1.ProductServiceServer. @@ -505,6 +506,10 @@ func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListPro return nil, err } page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize()) + filter, err := productListFilterFromRequest(req) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list", trace.WithAttributes( attribute.Int("page", int(page)), @@ -512,7 +517,19 @@ func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListPro )) defer dbSpan.End() - products, total, err := s.repo.ListProducts(dbCtx, page, pageSize, scope) + if filter.GroupID != "" { + if err := s.repo.ValidateProductGroup(dbCtx, filter.GroupID, scope); err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + if errors.Is(err, repository.ErrInvalidProductGroup) { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + s.observer.Logger(ctx).Error("validate product group filter failed", zap.String("group_id", filter.GroupID), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "validate product group filter: %v", err) + } + } + + products, total, err := s.repo.ListProducts(dbCtx, page, pageSize, filter, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -536,6 +553,89 @@ func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListPro }, nil } +func productListFilterFromRequest(req *productv1.ListProductsRequest) (repository.ProductListFilter, error) { + if req == nil { + 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()), + } + if utf8.RuneCountInString(filter.TitleKeyword) > maxProductTitleLength { + return repository.ProductListFilter{}, fmt.Errorf("title_keyword must contain at most %d characters", maxProductTitleLength) + } + if utf8.RuneCountInString(filter.SPUNo) > 100 { + return repository.ProductListFilter{}, errors.New("spu_no must contain at most 100 characters") + } + if filter.GroupID != "" { + if err := validatePositiveID(filter.GroupID, "group_id"); err != nil { + return repository.ProductListFilter{}, err + } + } + if req.CreatedAtFrom != nil { + value := req.GetCreatedAtFrom() + if value < 0 { + return repository.ProductListFilter{}, errors.New("created_at_from must be greater than or equal to 0") + } + createdAtFrom := time.UnixMilli(value) + filter.CreatedAtFrom = &createdAtFrom + } + if req.CreatedAtTo != nil { + value := req.GetCreatedAtTo() + if value < 0 { + return repository.ProductListFilter{}, errors.New("created_at_to must be greater than or equal to 0") + } + createdAtTo := time.UnixMilli(value) + filter.CreatedAtTo = &createdAtTo + } + if filter.CreatedAtFrom != nil && filter.CreatedAtTo != nil && filter.CreatedAtFrom.After(*filter.CreatedAtTo) { + return repository.ProductListFilter{}, errors.New("created_at_from must be less than or equal to created_at_to") + } + if req.GoodsType != nil { + goodsType := req.GetGoodsType() + if goodsType < 1 || goodsType > 4 { + return repository.ProductListFilter{}, errors.New("goods_type must be between 1 and 4") + } + filter.GoodsType = &goodsType + } + if req.SoldQuantityMin != nil { + value := req.GetSoldQuantityMin() + if value < 0 { + return repository.ProductListFilter{}, errors.New("sold_quantity_min must be greater than or equal to 0") + } + filter.SoldQuantityMin = &value + } + if req.SoldQuantityMax != nil { + value := req.GetSoldQuantityMax() + if value < 0 { + return repository.ProductListFilter{}, errors.New("sold_quantity_max must be greater than or equal to 0") + } + filter.SoldQuantityMax = &value + } + if filter.SoldQuantityMin != nil && filter.SoldQuantityMax != nil && *filter.SoldQuantityMin > *filter.SoldQuantityMax { + return repository.ProductListFilter{}, errors.New("sold_quantity_min must be less than or equal to sold_quantity_max") + } + if req.PriceMin != nil { + value := req.GetPriceMin() + if value < 0 { + return repository.ProductListFilter{}, errors.New("price_min must be greater than or equal to 0") + } + filter.PriceMin = &value + } + if req.PriceMax != nil { + value := req.GetPriceMax() + if value < 0 { + return repository.ProductListFilter{}, errors.New("price_max must be greater than or equal to 0") + } + filter.PriceMax = &value + } + if filter.PriceMin != nil && filter.PriceMax != nil && *filter.PriceMin > *filter.PriceMax { + return repository.ProductListFilter{}, errors.New("price_min must be less than or equal to price_max") + } + return filter, nil +} + // SearchProducts returns storefront-visible products whose titles contain the // supplied keyword. Visibility is enforced inside the repository and cannot be // relaxed by callers. diff --git a/scripts/sql/add-product-list-filter-indexes.sql b/scripts/sql/add-product-list-filter-indexes.sql new file mode 100644 index 0000000..eabaf4d --- /dev/null +++ b/scripts/sql/add-product-list-filter-indexes.sql @@ -0,0 +1,6 @@ +-- Index supporting admin product list filters. +-- Run outside a transaction because CREATE INDEX CONCURRENTLY is used. + +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;