feat(product): add paginated admin product listing

This commit is contained in:
BXY 2026-08-05 17:04:59 +08:00
parent 6b55143fc7
commit 077ac90438
5 changed files with 150 additions and 15 deletions

View File

@ -10,6 +10,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|-----|------|-----------|
| `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 |
| `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 |
| `ListProducts` | 分页返回全部未软删除商品列表 | Admin API |
| `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 |
| `ListCategoryTree` | 返回商品分类树,子节点挂载在父节点 `children` 下 | 微信小程序分类页 / BFF |
@ -17,12 +18,13 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
## 接口清单
当前商品服务对外暴露 3 个接口,REST 路径由 `google.api.http` 注解提供给 APISIX gRPC-Transcode 使用。
商品服务对外接口的 REST 路径由 `google.api.http` 注解提供给 APISIX gRPC-Transcode 使用。
| RPC | REST | 请求 | 响应 | 说明 |
|---|---|---|---|---|
| `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` | 分页查询全部未软删除商品 |
| `ListCategoryProducts` | `GET /v1/categories/{category_id}/products?page=1&page_size=20` | `ListCategoryProductsRequest` | `ListCategoryProductsResponse` | 按分类/分组 ID 分页查询商品列表 |
| `ListCategoryTree` | `GET /v1/categories/tree?only_visible=true` | `ListCategoryTreeRequest` | `ListCategoryTreeResponse` | 查询 `node_type = 0` 的商品分类,并按父子层级返回树 |
@ -103,6 +105,15 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
响应 `product` 包含 SPU 基础信息、SKU 列表、`created_at`、`updated_at`。时间字段统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。
### `ListProducts`
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 |
| `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` |
返回全部 `deleted_at IS NULL` 的商品,不按商品状态筛选,按 `created_at DESC, id DESC` 稳定排序。响应字段和聚合规则与 `ListCategoryProducts` 相同:`price` 为未删除 SKU 的最低售价(分),`sold_quantity` 为未删除 SKU 的累计销量。
### `ListCategoryProducts`
| 字段 | 类型 | 必填 | 说明 |
@ -214,8 +225,8 @@ cp .env.example .env
| gRPC 健康检查 | `grpc.health.v1.Health/Check` | 注册标准 gRPC Health Checking |
| Prometheus 指标 | `GET /metrics` | 暴露 Go runtime、process、RPC 与商品业务指标 |
| RPC 指标 | `ids_product_grpc_requests_total`, `ids_product_grpc_request_duration_seconds` | 按 `method`、`code` 维度统计请求数和耗时 |
| 商品业务指标 | `ids_product_products_created_total`, `ids_product_category_product_lists_total`, `ids_product_category_tree_lists_total` | 统计商品创建成功数、分类商品查询成功数和分类树查询成功数 |
| 链路追踪 | OTLP HTTP | gRPC 自动 span,并为商品创建、商品查询、分类商品查询补充业务 span |
| 商品业务指标 | `ids_product_products_created_total`, `ids_product_product_lists_total`, `ids_product_category_product_lists_total`, `ids_product_category_tree_lists_total` | 统计商品创建成功数、全商品查询成功数、分类商品查询成功数和分类树查询成功数 |
| 链路追踪 | OTLP HTTP | gRPC 自动 span,并为商品创建、商品查询、全商品查询、分类商品查询补充业务 span |
| 结构化日志 | stdout | access log 与错误日志包含 `trace_id`、`span_id`、`correlation_id` |
### 构建与运行
@ -245,6 +256,10 @@ grpcurl -plaintext -d '{"spu_no":"<spu-no>","title":"商品标题","selling_poin
# 分页查询分类商品
grpcurl -plaintext -d '{"category_id":"<snowflake-category-id>","page":1,"page_size":20}' \
localhost:50052 ids.product.v1.ProductService/ListCategoryProducts
# 分页查询全部未软删除商品
grpcurl -plaintext -d '{"page":1,"page_size":20}' \
localhost:50052 ids.product.v1.ProductService/ListProducts
```
## 数据模型

View File

@ -65,6 +65,15 @@ var (
},
)
productListsTotal = promauto.NewCounter(
prometheus.CounterOpts{
Namespace: "ids",
Subsystem: "product",
Name: "product_lists_total",
Help: "Total number of successful all-product list queries.",
},
)
categoryTreeListsTotal = promauto.NewCounter(
prometheus.CounterOpts{
Namespace: "ids",
@ -209,6 +218,11 @@ func IncCategoryProductLists() {
categoryProductListsTotal.Inc()
}
// IncProductLists records a successful all-product list query.
func IncProductLists() {
productListsTotal.Inc()
}
// IncCategoryTreeLists records a successful category tree query.
func IncCategoryTreeLists() {
categoryTreeListsTotal.Inc()

View File

@ -94,7 +94,7 @@ type InventoryRecord struct {
UpdatedAt time.Time
}
// CategoryProductRecord is the product summary returned by category product lists.
// CategoryProductRecord is the product summary returned by product list endpoints.
type CategoryProductRecord struct {
ID string
SPUNo string
@ -202,6 +202,7 @@ ALTER TABLE product.product_items
CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_products_active_created_id ON product.products(created_at DESC, id DESC) WHERE deleted_at IS NULL;
`
if _, err := r.db.ExecContext(ctx, ddl); err != nil {
return fmt.Errorf("ensure product tables: %w", err)
@ -729,6 +730,70 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (*
return product, skus[productID], nil
}
// ListProducts loads paginated summaries for all non-deleted products.
func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int32) ([]*CategoryProductRecord, int64, error) {
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 20
}
var total int64
if err := r.db.QueryRowContext(ctx, `
SELECT COUNT(*)
FROM product.products
WHERE deleted_at IS NULL
`).Scan(&total); err != nil {
return nil, 0, fmt.Errorf("count 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)
FROM product.products p
LEFT JOIN LATERAL (
SELECT MIN(pi.price) AS price,
SUM(COALESCE(inv.sold_quantity, 0)) AS sold_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
) sku_summary ON TRUE
WHERE p.deleted_at IS NULL
ORDER BY p.created_at DESC, p.id DESC
LIMIT $1 OFFSET $2
`, pageSize, offset)
if err != nil {
return nil, 0, fmt.Errorf("query 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 products: %w", err)
}
return products, total, nil
}
// ListCategoryProducts loads paginated product summaries for a category ID.
func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*CategoryProductRecord, int64, error) {
parsedCategoryID, err := parseID(categoryID, "category id")

View File

@ -149,6 +149,40 @@ func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProduc
}, nil
}
// ListProducts returns a paginated list of all non-deleted products.
func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListProductsRequest) (*productv1.ListProductsResponse, error) {
page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize())
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list", trace.WithAttributes(
attribute.Int("page", int(page)),
attribute.Int("page_size", int(pageSize)),
))
defer dbSpan.End()
products, total, err := s.repo.ListProducts(dbCtx, page, pageSize)
if err != nil {
dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error())
s.observer.Logger(ctx).Error("list products failed", zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err))
return nil, status.Errorf(codes.Internal, "list products: %v", err)
}
dbSpan.SetAttributes(attribute.Int64("product.total", total), attribute.Int("product.result_count", len(products)))
observability.IncProductLists()
protoProducts := make([]*productv1.CategoryProduct, 0, len(products))
for _, product := range products {
protoProducts = append(protoProducts, toProtoCategoryProduct(product))
}
return &productv1.ListProductsResponse{
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() == "" {
@ -159,17 +193,7 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1
return nil, status.Error(codes.InvalidArgument, "category_id must be a positive snowflake id")
}
page := req.GetPage()
if page <= 0 {
page = 1
}
pageSize := req.GetPageSize()
if pageSize <= 0 {
pageSize = defaultPageSize
}
if pageSize > maxPageSize {
pageSize = maxPageSize
}
page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize())
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_by_category", trace.WithAttributes(
attribute.String("category.id", req.GetCategoryId()),
@ -202,6 +226,19 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1
}, nil
}
func normalizedPage(page, pageSize int32) (int32, int32) {
if page <= 0 {
page = 1
}
if pageSize <= 0 {
pageSize = defaultPageSize
}
if pageSize > maxPageSize {
pageSize = maxPageSize
}
return page, pageSize
}
// ListCategoryTree returns product category nodes as a parent-child hierarchy.
func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.ListCategoryTreeRequest) (*productv1.ListCategoryTreeResponse, error) {
onlyVisible := false

View File

@ -101,6 +101,10 @@ CREATE INDEX IF NOT EXISTS idx_products_goods_type
CREATE INDEX IF NOT EXISTS idx_products_deleted_at
ON product.products (deleted_at);
CREATE INDEX IF NOT EXISTS idx_products_active_created_id
ON product.products (created_at DESC, id DESC)
WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no
ON product.products (spu_no)
WHERE deleted_at IS NULL;