mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
feat: add AddProductsToCategory method and update AddProductsToGroup for category and group bindings
This commit is contained in:
parent
cd94e0d0d2
commit
d1b8aa2996
@ -32,6 +32,8 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
||||
| `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 分页查询商品列表 |
|
||||
| `AddProductsToGroup` | `POST /v1/categories/{category_id}/products` | `AddProductsToGroupRequest` | `AddProductsToGroupResponse` | 批量绑定商品到二级分类 |
|
||||
| `AddProductsToGroup` | `POST /v1/groups/{group_id}` | `AddProductsToGroupRequest` | `AddProductsToGroupResponse` | 批量绑定商品到商品分组 |
|
||||
| `ListCategoryTree` | `GET /v1/categories/tree?only_visible=true` | `ListCategoryTreeRequest` | `ListCategoryTreeResponse` | 查询 `node_type = 0` 的商品分类,并按父子层级返回树 |
|
||||
|
||||
### `CreateProduct`
|
||||
|
||||
11
internal/repository/category_binding_test.go
Normal file
11
internal/repository/category_binding_test.go
Normal file
@ -0,0 +1,11 @@
|
||||
package repository
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAddProductsToCategoryRequiresStoreScope(t *testing.T) {
|
||||
repository := &ProductRepository{}
|
||||
err := repository.AddProductsToCategory(nil, "2001", []string{"3001"}, []string{"1001"}, StoreScope{})
|
||||
if err != ErrStoreScopeRequired {
|
||||
t.Fatalf("err = %v, want %v", err, ErrStoreScopeRequired)
|
||||
}
|
||||
}
|
||||
@ -795,9 +795,19 @@ func pointerStringSlice(value *[]string) []string {
|
||||
return *value
|
||||
}
|
||||
|
||||
// AddProductsToGroup binds every product to the requested category or product group in one transaction.
|
||||
// AddProductsToGroup binds every product to a product group in one transaction.
|
||||
// Existing bindings are retained and duplicate bindings are ignored.
|
||||
func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID string, bindingIDs, productIDs []string, scope StoreScope) error {
|
||||
return r.addProductsToCategoryNode(ctx, groupID, bindingIDs, productIDs, 2, 0, "group", scope)
|
||||
}
|
||||
|
||||
// AddProductsToCategory binds every product to a second-level category in one
|
||||
// transaction. Existing bindings are retained and duplicate bindings are ignored.
|
||||
func (r *ProductRepository) AddProductsToCategory(ctx context.Context, categoryID string, bindingIDs, productIDs []string, scope StoreScope) error {
|
||||
return r.addProductsToCategoryNode(ctx, categoryID, bindingIDs, productIDs, 1, 2, "category", scope)
|
||||
}
|
||||
|
||||
func (r *ProductRepository) addProductsToCategoryNode(ctx context.Context, nodeID string, bindingIDs, productIDs []string, nodeType, level int32, nodeLabel string, scope StoreScope) error {
|
||||
if err := requireWriteScope(scope); err != nil {
|
||||
return err
|
||||
}
|
||||
@ -808,7 +818,7 @@ func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID stri
|
||||
return errors.New("binding ids must match product ids")
|
||||
}
|
||||
|
||||
parsedGroupID, err := parseID(groupID, "group_id")
|
||||
parsedNodeID, err := parseID(nodeID, nodeLabel+"_id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -827,20 +837,23 @@ func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID stri
|
||||
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin add products to group: %w", err)
|
||||
return fmt.Errorf("begin add products to %s: %w", nodeLabel, err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
err = tx.QueryRowContext(ctx, `
|
||||
SELECT id
|
||||
FROM product.product_category
|
||||
WHERE id = $1 AND node_type = 2 AND store_id = $2
|
||||
`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID)
|
||||
WHERE id = $1
|
||||
AND node_type = $2
|
||||
AND store_id = $3
|
||||
AND ($4 = 0 OR level = $4)
|
||||
`, parsedNodeID, nodeType, scope.StoreID, level).Scan(&parsedNodeID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID)
|
||||
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, nodeID)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("query category or group node %s: %w", groupID, err)
|
||||
return fmt.Errorf("query %s node %s: %w", nodeLabel, nodeID, err)
|
||||
}
|
||||
|
||||
productPlaceholders := make([]string, len(parsedProductIDs))
|
||||
@ -858,22 +871,22 @@ WHERE deleted_at IS NULL
|
||||
AND id IN (%s)
|
||||
`, len(productArgs), strings.Join(productPlaceholders, ", ")), productArgs...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("query products for category or group binding: %w", err)
|
||||
return fmt.Errorf("query products for %s binding: %w", nodeLabel, err)
|
||||
}
|
||||
|
||||
foundProducts := make(map[int64]struct{}, len(parsedProductIDs))
|
||||
for rows.Next() {
|
||||
var productID int64
|
||||
if err := rows.Scan(&productID); err != nil {
|
||||
return fmt.Errorf("scan product for category or group binding: %w", err)
|
||||
return fmt.Errorf("scan product for %s binding: %w", nodeLabel, err)
|
||||
}
|
||||
foundProducts[productID] = struct{}{}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("iterate products for category or group binding: %w", err)
|
||||
return fmt.Errorf("iterate products for %s binding: %w", nodeLabel, err)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return fmt.Errorf("close products for category or group binding: %w", err)
|
||||
return fmt.Errorf("close products for %s binding: %w", nodeLabel, err)
|
||||
}
|
||||
for i, productID := range parsedProductIDs {
|
||||
if _, ok := foundProducts[productID]; !ok {
|
||||
@ -886,7 +899,7 @@ WHERE deleted_at IS NULL
|
||||
for i, productID := range parsedProductIDs {
|
||||
base := i * 3
|
||||
valuePlaceholders[i] = fmt.Sprintf("($%d, $%d, $%d)", base+1, base+2, base+3)
|
||||
args = append(args, parsedBindingIDs[i], productID, parsedGroupID)
|
||||
args = append(args, parsedBindingIDs[i], productID, parsedNodeID)
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, fmt.Sprintf(`
|
||||
INSERT INTO product.product_category_bindings (id, product_id, category_id)
|
||||
@ -894,11 +907,11 @@ VALUES %s
|
||||
ON CONFLICT (product_id, category_id) DO NOTHING
|
||||
`, strings.Join(valuePlaceholders, ", ")), args...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert product category or group bindings: %w", err)
|
||||
return fmt.Errorf("insert product %s bindings: %w", nodeLabel, err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("commit add products to group: %w", err)
|
||||
return fmt.Errorf("commit add products to %s: %w", nodeLabel, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -885,7 +885,8 @@ func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroup
|
||||
}, nil
|
||||
}
|
||||
|
||||
// AddProductsToGroup adds one or more products to a category or product group.
|
||||
// AddProductsToGroup adds one or more products to either a product group or a
|
||||
// second-level category. Exactly one target id is accepted.
|
||||
func (s *ProductServer) AddProductsToGroup(ctx context.Context, req *productv1.AddProductsToGroupRequest) (*productv1.AddProductsToGroupResponse, error) {
|
||||
if req == nil {
|
||||
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||
@ -899,7 +900,19 @@ func (s *ProductServer) AddProductsToGroup(ctx context.Context, req *productv1.A
|
||||
}
|
||||
|
||||
groupID := strings.TrimSpace(req.GetGroupId())
|
||||
if err := validatePositiveSnowflakeID(groupID, "group_id"); err != nil {
|
||||
categoryID := strings.TrimSpace(req.GetCategoryId())
|
||||
if (groupID == "" && categoryID == "") || (groupID != "" && categoryID != "") {
|
||||
return nil, status.Error(codes.InvalidArgument, "exactly one of group_id or category_id is required")
|
||||
}
|
||||
targetType := "group"
|
||||
targetID := groupID
|
||||
targetField := "group_id"
|
||||
if categoryID != "" {
|
||||
targetType = "category"
|
||||
targetID = categoryID
|
||||
targetField = "category_id"
|
||||
}
|
||||
if err := validatePositiveSnowflakeID(targetID, targetField); err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
productIDs, err := normalizeGroupProductIDs(req.GetProductIds())
|
||||
@ -912,21 +925,27 @@ func (s *ProductServer) AddProductsToGroup(ctx context.Context, req *productv1.A
|
||||
bindingIDs[i] = s.idgen.NextString()
|
||||
}
|
||||
|
||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.group.add_products", trace.WithAttributes(
|
||||
attribute.String("group.id", groupID),
|
||||
attribute.Int("group.product_count", len(productIDs)),
|
||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category_binding.add_products", trace.WithAttributes(
|
||||
attribute.String("binding.target_type", targetType),
|
||||
attribute.String("binding.target_id", targetID),
|
||||
attribute.Int("binding.product_count", len(productIDs)),
|
||||
))
|
||||
defer dbSpan.End()
|
||||
|
||||
if err := s.repo.AddProductsToGroup(dbCtx, groupID, bindingIDs, productIDs, scope); err != nil {
|
||||
if categoryID != "" {
|
||||
err = s.repo.AddProductsToCategory(dbCtx, targetID, bindingIDs, productIDs, scope)
|
||||
} else {
|
||||
err = s.repo.AddProductsToGroup(dbCtx, targetID, bindingIDs, productIDs, scope)
|
||||
}
|
||||
if err != nil {
|
||||
dbSpan.RecordError(err)
|
||||
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||
s.observer.Logger(ctx).Error("add products to group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err))
|
||||
s.observer.Logger(ctx).Error("add products to binding target failed", zap.String("target_type", targetType), zap.String("target_id", targetID), zap.Strings("product_ids", productIDs), zap.Error(err))
|
||||
switch {
|
||||
case errors.Is(err, repository.ErrCategoryNodeNotFound), errors.Is(err, repository.ErrProductNotFound):
|
||||
return nil, status.Error(codes.NotFound, err.Error())
|
||||
default:
|
||||
return nil, status.Errorf(codes.Internal, "add products to group: %v", err)
|
||||
return nil, status.Errorf(codes.Internal, "add products to %s: %v", targetType, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user