From 548ed1995466f83b945830bd3640a4202c165902 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Wed, 8 Jul 2026 14:41:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E7=B1=BB=E5=88=AB=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 25 ++++++- docs/ARCHITECTURE.md | 2 + internal/observability/observability.go | 14 ++++ internal/repository/product_repository.go | 76 +++++++++++++++++++++- internal/server/product_server.go | 79 +++++++++++++++++++++++ 5 files changed, 194 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6c20ba5..985b402 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 | | `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 | | `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 | +| `ListCategoryTree` | 返回商品分类树,子节点挂载在父节点 `children` 下 | 微信小程序分类页 / BFF | 契约定义见 [`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 列表 | | `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 分页查询商品列表 | +| `ListCategoryTree` | `GET /v1/categories/tree?only_visible=true` | `ListCategoryTreeRequest` | `ListCategoryTreeResponse` | 查询 `node_type = 0` 的商品分类,并按父子层级返回树 | ### `CreateProduct` @@ -71,6 +73,27 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `total` | `int64` | 分类/分组下商品总数 | | `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 | | 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_products_created_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` | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index fd19f74..4ac31a5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -75,12 +75,14 @@ | `CreateProduct` | 后台 / 运营系统 | 创建商品 SPU 及可选 SKU 列表。 | | `GetProduct` | BFF / 后台 | 根据单个 `product_id` 返回 SPU 及其 SKU 列表。 | | `ListCategoryProducts` | BFF / 商城前台 | 根据分类/分组节点分页返回商品列表。 | +| `ListCategoryTree` | 微信小程序分类页 / BFF | 返回 `node_type = 0` 的商品分类树,子分类挂载在父分类 `children` 下。 | ### 3.2 查询实现约束 1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product.products` 与 `product.product_items` 之间做本域关联或分步查询,但不得访问其他 Schema。 2. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。 3. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。 +4. **[ARC-PROD-007] 分类树组装边界:** repository 只查询 `product.product_category` 的扁平分类数据;父子层级组装由 `internal/server` 完成,不允许通过跨 Schema 查询补齐分类展示信息。 --- diff --git a/internal/observability/observability.go b/internal/observability/observability.go index 658055f..52d6ba9 100644 --- a/internal/observability/observability.go +++ b/internal/observability/observability.go @@ -64,6 +64,15 @@ var ( 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. @@ -200,6 +209,11 @@ func IncCategoryProductLists() { categoryProductListsTotal.Inc() } +// IncCategoryTreeLists records a successful category tree query. +func IncCategoryTreeLists() { + categoryTreeListsTotal.Inc() +} + // MetricsServer exposes Prometheus scrape and health endpoints. func MetricsServer(addr string, healthCheck func(context.Context) error) *http.Server { mux := http.NewServeMux() diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index b7e2bde..f5ba283 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -43,6 +43,17 @@ type SKURecord struct { 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]. type ProductRepository struct { db *sql.DB @@ -419,6 +430,41 @@ LIMIT $2 OFFSET $3 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) { products, err := r.loadProductsByIDs(ctx, []string{productID}) if err != nil { @@ -554,7 +600,7 @@ SELECT pi.id, pi.product_id, pi.name, pi.price, - COALESCE(inv.available_quantity, 0), + COALESCE(inv.sold_quantity, 0), pi.attributes, pi.created_at, pi.updated_at @@ -634,6 +680,34 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { 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) { if strings.TrimSpace(raw) == "" { return []byte("{}"), nil diff --git a/internal/server/product_server.go b/internal/server/product_server.go index d585a3a..314da9b 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -161,6 +161,33 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 }, 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 { if total <= 0 || pageSize <= 0 { return 0 @@ -289,3 +316,55 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco 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{}, + } +}