mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
feat(product): 新增前台商品关键字搜索能力
This commit is contained in:
parent
cd60a19cdf
commit
50ef666baf
@ -11,6 +11,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
||||
| `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 |
|
||||
| `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 |
|
||||
| `ListProducts` | 分页返回全部未软删除商品列表 | Admin API |
|
||||
| `SearchProducts` | 按标题关键字分页返回前台可见商品 | 小程序 / H5 BFF |
|
||||
| `UpdateProduct` | 更新 SPU 字段,并更新或替换 SKU 集合 | Admin API |
|
||||
| `UpdateProductStatus` | 显式变更仓库中、上架、已售罄状态 | Admin API |
|
||||
| `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 |
|
||||
@ -27,6 +28,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
||||
| `CreateProduct` | `POST /v1/products` | `CreateProductRequest` | `CreateProductResponse` | 创建商品 SPU,可同时提交 SKU 列表 |
|
||||
| `GetProduct` | `GET /v1/products/{product_id}` | `GetProductRequest` | `GetProductResponse` | 按商品 ID 查询商品详情,返回 SPU 与 SKU 列表 |
|
||||
| `ListProducts` | `GET /v1/products?page=1&page_size=20` | `ListProductsRequest` | `ListProductsResponse` | 分页查询全部未软删除商品 |
|
||||
| `SearchProducts` | gRPC only | `SearchProductsRequest` | `SearchProductsResponse` | 按标题关键字分页查询前台可见商品 |
|
||||
| `UpdateProduct` | `PATCH /v1/products/{product_id}` | `UpdateProductRequest` | `UpdateProductResponse` | 原子更新 SPU 字段,并补丁更新或整体替换 SKU |
|
||||
| `UpdateProductStatus` | `PATCH /v1/products/{product_id}/status` | `UpdateProductStatusRequest` | `UpdateProductStatusResponse` | 使用乐观锁更新商品状态 |
|
||||
| `ListCategoryProducts` | `GET /v1/categories/{category_id}/products?page=1&page_size=20` | `ListCategoryProductsRequest` | `ListCategoryProductsResponse` | 按分类/分组 ID 分页查询商品列表 |
|
||||
|
||||
@ -74,6 +74,15 @@ var (
|
||||
},
|
||||
)
|
||||
|
||||
productSearchesTotal = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Namespace: "ids",
|
||||
Subsystem: "product",
|
||||
Name: "product_searches_total",
|
||||
Help: "Total number of successful storefront product keyword searches.",
|
||||
},
|
||||
)
|
||||
|
||||
categoryTreeListsTotal = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Namespace: "ids",
|
||||
@ -223,6 +232,11 @@ func IncProductLists() {
|
||||
productListsTotal.Inc()
|
||||
}
|
||||
|
||||
// IncProductSearches records a successful storefront product keyword search.
|
||||
func IncProductSearches() {
|
||||
productSearchesTotal.Inc()
|
||||
}
|
||||
|
||||
// IncCategoryTreeLists records a successful category tree query.
|
||||
func IncCategoryTreeLists() {
|
||||
categoryTreeListsTotal.Inc()
|
||||
|
||||
@ -1797,6 +1797,93 @@ LIMIT $1 OFFSET $2
|
||||
return products, total, nil
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (r *ProductRepository) SearchProducts(ctx context.Context, keyword string, page, pageSize int32) ([]*CategoryProductRecord, int64, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
escapedKeyword := escapeLikeLiteral(keyword)
|
||||
containsPattern := "%" + escapedKeyword + "%"
|
||||
prefixPattern := escapedKeyword + "%"
|
||||
onSaleStatus := statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE)
|
||||
offSaleStatus := statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE)
|
||||
|
||||
var total int64
|
||||
if err := r.db.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*)
|
||||
FROM product.products p
|
||||
WHERE p.deleted_at IS NULL
|
||||
AND p.status IN ($2, $3)
|
||||
AND p.title ILIKE $1 ESCAPE '\'
|
||||
`, containsPattern, onSaleStatus, offSaleStatus).Scan(&total); err != nil {
|
||||
return nil, 0, fmt.Errorf("count searched products: %w", err)
|
||||
}
|
||||
if total == 0 {
|
||||
return []*CategoryProductRecord{}, 0, nil
|
||||
}
|
||||
|
||||
offset := int64(page-1) * int64(pageSize)
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT p.updated_at,
|
||||
p.created_at,
|
||||
p.title,
|
||||
p.id,
|
||||
p.spu_no,
|
||||
p.status,
|
||||
COALESCE(to_json(p.image_ids)::text, '[]'),
|
||||
COALESCE(sku_summary.price, 0),
|
||||
COALESCE(sku_summary.sold_quantity, 0),
|
||||
COALESCE(sku_summary.available_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.available_quantity, 0)) AS available_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.status IN ($2, $3)
|
||||
AND p.title ILIKE $1 ESCAPE '\'
|
||||
ORDER BY CASE
|
||||
WHEN LOWER(p.title) = LOWER($4) THEN 0
|
||||
WHEN p.title ILIKE $5 ESCAPE '\' THEN 1
|
||||
ELSE 2
|
||||
END,
|
||||
p.updated_at DESC,
|
||||
p.id DESC
|
||||
LIMIT $6 OFFSET $7
|
||||
`, containsPattern, onSaleStatus, offSaleStatus, keyword, prefixPattern, pageSize, offset)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("query searched products: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
products := make([]*CategoryProductRecord, 0, pageSize)
|
||||
for rows.Next() {
|
||||
product, err := scanCategoryProduct(rows)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
products = append(products, product)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, 0, fmt.Errorf("iterate searched products: %w", err)
|
||||
}
|
||||
return products, total, nil
|
||||
}
|
||||
|
||||
// CountProducts returns aggregate product counts grouped by lifecycle status.
|
||||
func (r *ProductRepository) CountProducts(ctx context.Context) (*ProductCountRecord, error) {
|
||||
var counts ProductCountRecord
|
||||
@ -2893,6 +2980,18 @@ func statusFromDB(status int16) productv1.ProductStatus {
|
||||
}
|
||||
}
|
||||
|
||||
// escapeLikeLiteral makes PostgreSQL LIKE metacharacters literal. The caller
|
||||
// still passes the resulting value as a bound query parameter; this helper is
|
||||
// about preserving search semantics rather than SQL injection prevention.
|
||||
func escapeLikeLiteral(value string) string {
|
||||
replacer := strings.NewReplacer(
|
||||
`\`, `\\`,
|
||||
`%`, `\%`,
|
||||
`_`, `\_`,
|
||||
)
|
||||
return replacer.Replace(value)
|
||||
}
|
||||
|
||||
func parseID(raw, field string) (int64, error) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
|
||||
10
internal/repository/product_repository_test.go
Normal file
10
internal/repository/product_repository_test.go
Normal file
@ -0,0 +1,10 @@
|
||||
package repository
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestEscapeLikeLiteral(t *testing.T) {
|
||||
input := `100%_off\\bundle`
|
||||
if got, want := escapeLikeLiteral(input), `100\%\_off\\\\bundle`; got != want {
|
||||
t.Fatalf("escapeLikeLiteral(%q) = %q, want %q", input, got, want)
|
||||
}
|
||||
}
|
||||
@ -10,6 +10,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
otelcodes "go.opentelemetry.io/otel/codes"
|
||||
@ -39,6 +40,7 @@ const (
|
||||
maxNodeNameLength = 100
|
||||
maxProductsPerGroupRequest = 100
|
||||
maxCartItemProductBatchSize = 100
|
||||
maxSearchKeywordLength = 50
|
||||
)
|
||||
|
||||
// ProductServer implements productv1.ProductServiceServer.
|
||||
@ -367,6 +369,52 @@ func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListPro
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SearchProducts returns storefront-visible products whose titles contain the
|
||||
// supplied keyword. Visibility is enforced inside the repository and cannot be
|
||||
// relaxed by callers.
|
||||
func (s *ProductServer) SearchProducts(ctx context.Context, req *productv1.SearchProductsRequest) (*productv1.SearchProductsResponse, error) {
|
||||
if req == nil {
|
||||
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||
}
|
||||
|
||||
keyword := strings.TrimSpace(req.GetKeyword())
|
||||
keywordLength := utf8.RuneCountInString(keyword)
|
||||
if keyword == "" || keywordLength > maxSearchKeywordLength {
|
||||
return nil, status.Errorf(codes.InvalidArgument, "keyword must contain between 1 and %d characters", maxSearchKeywordLength)
|
||||
}
|
||||
page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize())
|
||||
|
||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.search", trace.WithAttributes(
|
||||
attribute.Int("keyword.length", keywordLength),
|
||||
attribute.Int("page", int(page)),
|
||||
attribute.Int("page_size", int(pageSize)),
|
||||
))
|
||||
defer dbSpan.End()
|
||||
|
||||
products, total, err := s.repo.SearchProducts(dbCtx, keyword, page, pageSize)
|
||||
if err != nil {
|
||||
dbSpan.RecordError(err)
|
||||
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||
s.observer.Logger(ctx).Error("search products failed", zap.Int("keyword_length", keywordLength), zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err))
|
||||
return nil, status.Errorf(codes.Internal, "search products: %v", err)
|
||||
}
|
||||
dbSpan.SetAttributes(attribute.Int64("product.total", total), attribute.Int("product.result_count", len(products)))
|
||||
observability.IncProductSearches()
|
||||
|
||||
protoProducts := make([]*productv1.CategoryProduct, 0, len(products))
|
||||
for _, product := range products {
|
||||
protoProducts = append(protoProducts, toProtoCategoryProduct(product))
|
||||
}
|
||||
|
||||
return &productv1.SearchProductsResponse{
|
||||
Products: protoProducts,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
Total: total,
|
||||
TotalPages: totalPages(total, pageSize),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListCategoryProducts returns a paginated product list under a category.
|
||||
func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1.ListCategoryProductsRequest) (*productv1.ListCategoryProductsResponse, error) {
|
||||
if req == nil || req.GetCategoryId() == "" {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user