添加 查询类别接口

This commit is contained in:
BXY0414 2026-07-08 14:41:16 +08:00
parent 114c9578bb
commit 548ed19954
5 changed files with 194 additions and 2 deletions

View File

@ -11,6 +11,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
| `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 | | `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 |
| `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 | | `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 |
| `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 | | `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 |
| `ListCategoryTree` | 返回商品分类树,子节点挂载在父节点 `children` 下 | 微信小程序分类页 / BFF |
契约定义见 [`ids-proto`](https://llms.idsbuybuybuy.com/ecommerce/ids-proto) 的 `proto/ids/product/v1/product.proto`。 契约定义见 [`ids-proto`](https://llms.idsbuybuybuy.com/ecommerce/ids-proto) 的 `proto/ids/product/v1/product.proto`。
@ -23,6 +24,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
| `CreateProduct` | `POST /v1/products` | `CreateProductRequest` | `CreateProductResponse` | 创建商品 SPU,可同时提交 SKU 列表 | | `CreateProduct` | `POST /v1/products` | `CreateProductRequest` | `CreateProductResponse` | 创建商品 SPU,可同时提交 SKU 列表 |
| `GetProduct` | `GET /v1/products/{product_id}` | `GetProductRequest` | `GetProductResponse` | 按商品 ID 查询商品详情,返回 SPU 与 SKU 列表 | | `GetProduct` | `GET /v1/products/{product_id}` | `GetProductRequest` | `GetProductResponse` | 按商品 ID 查询商品详情,返回 SPU 与 SKU 列表 |
| `ListCategoryProducts` | `GET /v1/categories/{category_id}/products?page=1&page_size=20` | `ListCategoryProductsRequest` | `ListCategoryProductsResponse` | 按分类/分组 ID 分页查询商品列表 | | `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` 的商品分类,并按父子层级返回树 |
### `CreateProduct` ### `CreateProduct`
@ -71,6 +73,27 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
| `total` | `int64` | 分类/分组下商品总数 | | `total` | `int64` | 分类/分组下商品总数 |
| `total_pages` | `int32` | 总页数 | | `total_pages` | `int32` | 总页数 |
### `ListCategoryTree`
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `only_visible` | `bool` | 否 | 为 `true` 时只返回 `status = 1` 的分类;为 `false` 时返回全部 `node_type = 0` 分类 |
响应 `categories` 为树形分类列表。一级分类位于最外层,子分类挂载在父分类的 `children` 下。
`CategoryNode` 字段:
| 字段 | 类型 | 说明 |
|---|---|---|
| `category_id` | `string` | 分类节点 ID,对应 `product.product_category.id` |
| `name` | `string` | 分类展示名称 |
| `parent_id` | `string` | 父级分类 ID;一级分类为空字符串 |
| `level` | `int32` | 分类层级 |
| `image_json` | `string` | 分类图片 JSON,原样返回 |
| `sort_num` | `int32` | 同级排序值 |
| `status` | `int32` | 节点状态:`0` 隐藏,`1` 显示 |
| `children` | `CategoryNode[]` | 子分类列表 |
## 技术栈 ## 技术栈
| 项 | 选型 | | 项 | 选型 |
@ -138,7 +161,7 @@ cp .env.example .env
| gRPC 健康检查 | `grpc.health.v1.Health/Check` | 注册标准 gRPC Health Checking | | gRPC 健康检查 | `grpc.health.v1.Health/Check` | 注册标准 gRPC Health Checking |
| Prometheus 指标 | `GET /metrics` | 暴露 Go runtime、process、RPC 与商品业务指标 | | Prometheus 指标 | `GET /metrics` | 暴露 Go runtime、process、RPC 与商品业务指标 |
| RPC 指标 | `ids_product_grpc_requests_total`, `ids_product_grpc_request_duration_seconds` | 按 `method`、`code` 维度统计请求数和耗时 | | 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_products_created_total`, `ids_product_category_product_lists_total`, `ids_product_category_tree_lists_total` | 统计商品创建成功数、分类商品查询成功数和分类树查询成功数 |
| 链路追踪 | OTLP HTTP | gRPC 自动 span,并为商品创建、商品查询、分类商品查询补充业务 span | | 链路追踪 | OTLP HTTP | gRPC 自动 span,并为商品创建、商品查询、分类商品查询补充业务 span |
| 结构化日志 | stdout | access log 与错误日志包含 `trace_id`、`span_id`、`correlation_id` | | 结构化日志 | stdout | access log 与错误日志包含 `trace_id`、`span_id`、`correlation_id` |

View File

@ -75,12 +75,14 @@
| `CreateProduct` | 后台 / 运营系统 | 创建商品 SPU 及可选 SKU 列表。 | | `CreateProduct` | 后台 / 运营系统 | 创建商品 SPU 及可选 SKU 列表。 |
| `GetProduct` | BFF / 后台 | 根据单个 `product_id` 返回 SPU 及其 SKU 列表。 | | `GetProduct` | BFF / 后台 | 根据单个 `product_id` 返回 SPU 及其 SKU 列表。 |
| `ListCategoryProducts` | BFF / 商城前台 | 根据分类/分组节点分页返回商品列表。 | | `ListCategoryProducts` | BFF / 商城前台 | 根据分类/分组节点分页返回商品列表。 |
| `ListCategoryTree` | 微信小程序分类页 / BFF | 返回 `node_type = 0` 的商品分类树,子分类挂载在父分类 `children` 下。 |
### 3.2 查询实现约束 ### 3.2 查询实现约束
1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product.products` 与 `product.product_items` 之间做本域关联或分步查询,但不得访问其他 Schema。 1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product.products` 与 `product.product_items` 之间做本域关联或分步查询,但不得访问其他 Schema。
2. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。 2. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。
3. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。 3. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。
4. **[ARC-PROD-007] 分类树组装边界:** repository 只查询 `product.product_category` 的扁平分类数据;父子层级组装由 `internal/server` 完成,不允许通过跨 Schema 查询补齐分类展示信息。
--- ---

View File

@ -64,6 +64,15 @@ var (
Help: "Total number of successful category product list queries.", Help: "Total number of successful category product list queries.",
}, },
) )
categoryTreeListsTotal = promauto.NewCounter(
prometheus.CounterOpts{
Namespace: "ids",
Subsystem: "product",
Name: "category_tree_lists_total",
Help: "Total number of successful category tree queries.",
},
)
) )
// Observer wires OTLP tracing and trace-aware structured logging. // Observer wires OTLP tracing and trace-aware structured logging.
@ -200,6 +209,11 @@ func IncCategoryProductLists() {
categoryProductListsTotal.Inc() categoryProductListsTotal.Inc()
} }
// IncCategoryTreeLists records a successful category tree query.
func IncCategoryTreeLists() {
categoryTreeListsTotal.Inc()
}
// MetricsServer exposes Prometheus scrape and health endpoints. // MetricsServer exposes Prometheus scrape and health endpoints.
func MetricsServer(addr string, healthCheck func(context.Context) error) *http.Server { func MetricsServer(addr string, healthCheck func(context.Context) error) *http.Server {
mux := http.NewServeMux() mux := http.NewServeMux()

View File

@ -43,6 +43,17 @@ type SKURecord struct {
UpdatedAt time.Time UpdatedAt time.Time
} }
// CategoryRecord is the persistence model for product.product_category.
type CategoryRecord struct {
ID string
Name string
ParentID string
Level int32
ImageJSON string
SortNum int32
Status int32
}
// ProductRepository provides CRUD access to product tables only [ARC-PROD-001]. // ProductRepository provides CRUD access to product tables only [ARC-PROD-001].
type ProductRepository struct { type ProductRepository struct {
db *sql.DB db *sql.DB
@ -419,6 +430,41 @@ LIMIT $2 OFFSET $3
return products, skuMap, total, nil return products, skuMap, total, nil
} }
// ListCategoryTreeNodes loads product category nodes for storefront category trees.
func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) {
rows, err := r.db.QueryContext(ctx, `
SELECT id,
name,
parent_id,
level,
image_json,
sort_num,
status
FROM product.product_category
WHERE node_type = 0
AND ($1 = false OR status = 1)
ORDER BY level ASC, sort_num ASC, id ASC
`, onlyVisible)
if err != nil {
return nil, fmt.Errorf("query category tree nodes: %w", err)
}
defer rows.Close()
categories := make([]*CategoryRecord, 0)
for rows.Next() {
category, err := scanCategory(rows)
if err != nil {
return nil, err
}
categories = append(categories, category)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate category tree nodes: %w", err)
}
return categories, nil
}
func (r *ProductRepository) loadProductByID(ctx context.Context, productID string) (*ProductRecord, error) { func (r *ProductRepository) loadProductByID(ctx context.Context, productID string) (*ProductRecord, error) {
products, err := r.loadProductsByIDs(ctx, []string{productID}) products, err := r.loadProductsByIDs(ctx, []string{productID})
if err != nil { if err != nil {
@ -554,7 +600,7 @@ SELECT pi.id,
pi.product_id, pi.product_id,
pi.name, pi.name,
pi.price, pi.price,
COALESCE(inv.available_quantity, 0), COALESCE(inv.sold_quantity, 0),
pi.attributes, pi.attributes,
pi.created_at, pi.created_at,
pi.updated_at pi.updated_at
@ -634,6 +680,34 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) {
return &rec, nil return &rec, nil
} }
func scanCategory(scanner rowScanner) (*CategoryRecord, error) {
var (
rec CategoryRecord
id int64
parentID sql.NullInt64
imageJSON []byte
level int16
status int16
)
if err := scanner.Scan(
&id, &rec.Name, &parentID, &level, &imageJSON, &rec.SortNum, &status,
); err != nil {
return nil, fmt.Errorf("scan category: %w", err)
}
rec.ID = formatID(id)
if parentID.Valid {
rec.ParentID = formatID(parentID.Int64)
}
rec.Level = int32(level)
rec.ImageJSON = string(imageJSON)
if rec.ImageJSON == "" {
rec.ImageJSON = "[]"
}
rec.Status = int32(status)
return &rec, nil
}
func normalizeAttributesJSON(raw string) ([]byte, error) { func normalizeAttributesJSON(raw string) ([]byte, error) {
if strings.TrimSpace(raw) == "" { if strings.TrimSpace(raw) == "" {
return []byte("{}"), nil return []byte("{}"), nil

View File

@ -161,6 +161,33 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1
}, nil }, nil
} }
// 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
if req != nil {
onlyVisible = req.GetOnlyVisible()
}
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_category_tree", trace.WithAttributes(
attribute.Bool("category.only_visible", onlyVisible),
))
defer dbSpan.End()
categories, err := s.repo.ListCategoryTreeNodes(dbCtx, onlyVisible)
if err != nil {
dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error())
s.observer.Logger(ctx).Error("list category tree failed", zap.Bool("only_visible", onlyVisible), zap.Error(err))
return nil, status.Errorf(codes.Internal, "list category tree: %v", err)
}
dbSpan.SetAttributes(attribute.Int("category.result_count", len(categories)))
observability.IncCategoryTreeLists()
return &productv1.ListCategoryTreeResponse{
Categories: buildCategoryTree(categories),
}, nil
}
func totalPages(total int64, pageSize int32) int32 { func totalPages(total int64, pageSize int32) int32 {
if total <= 0 || pageSize <= 0 { if total <= 0 || pageSize <= 0 {
return 0 return 0
@ -289,3 +316,55 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
UpdatedAt: timestamppb.New(product.UpdatedAt), UpdatedAt: timestamppb.New(product.UpdatedAt),
} }
} }
func buildCategoryTree(categories []*repository.CategoryRecord) []*productv1.CategoryNode {
nodes := make(map[string]*productv1.CategoryNode, len(categories))
records := make(map[string]*repository.CategoryRecord, len(categories))
orderedIDs := make([]string, 0, len(categories))
for _, category := range categories {
if category == nil || category.ID == "" {
continue
}
nodes[category.ID] = toProtoCategoryNode(category)
records[category.ID] = category
orderedIDs = append(orderedIDs, category.ID)
}
roots := make([]*productv1.CategoryNode, 0)
for _, id := range orderedIDs {
node := nodes[id]
record := records[id]
if node == nil || record == nil {
continue
}
parentID := record.ParentID
parent, parentExists := nodes[parentID]
parentRecord := records[parentID]
if parentID == "" || !parentExists || parentRecord == nil || parentID == id || parentRecord.Level >= record.Level {
roots = append(roots, node)
continue
}
parent.Children = append(parent.Children, node)
}
return roots
}
func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.CategoryNode {
if category == nil {
return nil
}
return &productv1.CategoryNode{
CategoryId: category.ID,
Name: category.Name,
ParentId: category.ParentID,
Level: category.Level,
ImageJson: category.ImageJSON,
SortNum: category.SortNum,
Status: category.Status,
Children: []*productv1.CategoryNode{},
}
}