mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
feat: add support for product group bindings in product repository and server
This commit is contained in:
parent
800a78a5ad
commit
cd94e0d0d2
@ -48,6 +48,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
||||
| `sku_id` | 服务内 Snowflake 生成,每个 SKU 一个 | `product.product_items.id` |
|
||||
| `inventory_id` | 服务内 Snowflake 生成,每个 SKU 库存行一个 | `product.product_item_inventory.id` |
|
||||
| 分类绑定 ID | 每个 `leaf_category_ids` 项由服务内 Snowflake 生成 | `product.product_category_bindings.id` |
|
||||
| 分组绑定 ID | 每个 `group_ids` 项由服务内 Snowflake 生成 | `product.product_category_bindings.id` |
|
||||
|
||||
常用请求字段:
|
||||
|
||||
@ -57,6 +58,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
||||
| `title` | 是 | 商品标题 |
|
||||
| `selling_point` | 否 | 商品卖点 |
|
||||
| `leaf_category_ids` | 否 | 已存在的二级分类 ID 列表;传入后会写入全部分类绑定 |
|
||||
| `group_ids` | 否 | 已存在的商品分组 ID 列表;传入后会写入全部商品分组绑定 |
|
||||
| `image_ids` | 否 | 商品图片 ID 列表 |
|
||||
| `brand_id` / `supplier_id` | 否 | 品牌、供应商 ID |
|
||||
| `status` | 否 | 未传时默认 `PRODUCT_STATUS_INVENTORY`;可取 `INVENTORY`、`ON_SALE`、`OFF_SALE` |
|
||||
@ -75,6 +77,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
||||
"title": "澳洲和牛家庭装",
|
||||
"selling_point": "原切谷饲,冷链到家",
|
||||
"leaf_category_ids": ["726390485721088000"],
|
||||
"group_ids": ["726390485721088001"],
|
||||
"skus": [
|
||||
{
|
||||
"sku_no": "SKU20260710000101",
|
||||
|
||||
@ -25,6 +25,10 @@ var ErrCategoryVersionConflict = errors.New("category version conflict")
|
||||
var ErrCategoryTreeConflict = errors.New("category tree conflict")
|
||||
var ErrInvalidLeafCategory = errors.New("category must be an existing second-level category")
|
||||
|
||||
// ErrInvalidProductGroup is returned when a requested node is not a group in
|
||||
// the current store.
|
||||
var ErrInvalidProductGroup = errors.New("group must be an existing product group")
|
||||
|
||||
// ErrSKUNotFound is returned when a SKU does not exist.
|
||||
var ErrSKUNotFound = errors.New("sku not found")
|
||||
|
||||
@ -84,6 +88,8 @@ type ProductRecord struct {
|
||||
ScheduledSaleTime *time.Time
|
||||
LeafCategoryIDs []string
|
||||
CategoryBindingIDs []string
|
||||
GroupIDs []string
|
||||
GroupBindingIDs []string
|
||||
Version int32
|
||||
DeletedAt *time.Time
|
||||
CreatedAt time.Time
|
||||
@ -199,7 +205,11 @@ type ProductUpdateInput struct {
|
||||
// non-nil empty slice clears all leaf-category bindings.
|
||||
LeafCategoryIDs *[]string
|
||||
CategoryBindingIDs []string
|
||||
Scope StoreScope
|
||||
// GroupIDs is nil when group bindings must remain unchanged. A non-nil
|
||||
// empty slice clears all product-group bindings.
|
||||
GroupIDs *[]string
|
||||
GroupBindingIDs []string
|
||||
Scope StoreScope
|
||||
}
|
||||
|
||||
// CategoryDeleteResult summarizes a destructive category deletion.
|
||||
@ -469,6 +479,11 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
if len(product.GroupIDs) > 0 {
|
||||
if err := replaceProductGroupBindings(ctx, tx, createdProduct.ID, product.GroupIDs, product.GroupBindingIDs, product.Scope); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, nil, fmt.Errorf("commit create product: %w", err)
|
||||
@ -819,7 +834,7 @@ func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID stri
|
||||
err = tx.QueryRowContext(ctx, `
|
||||
SELECT id
|
||||
FROM product.product_category
|
||||
WHERE id = $1 AND store_id = $2
|
||||
WHERE id = $1 AND node_type = 2 AND store_id = $2
|
||||
`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID)
|
||||
@ -919,7 +934,7 @@ func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID
|
||||
err = tx.QueryRowContext(ctx, `
|
||||
SELECT id
|
||||
FROM product.product_category
|
||||
WHERE id = $1 AND store_id = $2
|
||||
WHERE id = $1 AND node_type = 2 AND store_id = $2
|
||||
`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID)
|
||||
@ -1041,6 +1056,11 @@ FOR UPDATE
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if input.GroupIDs != nil {
|
||||
if err := replaceProductGroupBindings(ctx, tx, input.Product.ID, *input.GroupIDs, input.GroupBindingIDs, input.Scope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if input.SKUChange != nil && input.SKUChange.Mode == SKUChangeModeReplaceAll && statusFromDB(currentStatus) == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE {
|
||||
return nil, ErrSKUReplacementRequiresNotOnSale
|
||||
@ -1201,6 +1221,92 @@ WHERE b.product_id = $1
|
||||
return nil
|
||||
}
|
||||
|
||||
// replaceProductGroupBindings replaces only the product's group bindings. It
|
||||
// deliberately leaves category bindings intact.
|
||||
func replaceProductGroupBindings(ctx context.Context, tx *sql.Tx, productID string, groupIDs []string, bindingIDs []string, scope StoreScope) error {
|
||||
if err := requireWriteScope(scope); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(groupIDs) != len(bindingIDs) {
|
||||
return errors.New("group ids and group binding ids must have the same length")
|
||||
}
|
||||
parsedProductID, err := parseID(productID, "product_id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parsedGroupIDs := make([]int64, len(groupIDs))
|
||||
seenGroupIDs := make(map[int64]struct{}, len(groupIDs))
|
||||
for index, groupID := range groupIDs {
|
||||
parsedGroupIDs[index], err = parseID(groupID, "group_id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, duplicate := seenGroupIDs[parsedGroupIDs[index]]; duplicate {
|
||||
return errors.New("group_ids must not contain duplicates")
|
||||
}
|
||||
seenGroupIDs[parsedGroupIDs[index]] = struct{}{}
|
||||
if _, err := parseID(bindingIDs[index], "group binding id"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if len(parsedGroupIDs) > 0 {
|
||||
placeholders := make([]string, len(parsedGroupIDs))
|
||||
args := make([]any, len(parsedGroupIDs))
|
||||
for index, groupID := range parsedGroupIDs {
|
||||
placeholders[index] = fmt.Sprintf("$%d", index+1)
|
||||
args[index] = groupID
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
|
||||
SELECT id
|
||||
FROM product.product_category
|
||||
WHERE node_type = 2
|
||||
AND store_id = $%d
|
||||
AND id IN (%s)
|
||||
FOR KEY SHARE
|
||||
`, len(args)+1, strings.Join(placeholders, ", ")), append(args, scope.StoreID)...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("validate product groups: %w", err)
|
||||
}
|
||||
found := make(map[int64]struct{}, len(parsedGroupIDs))
|
||||
for rows.Next() {
|
||||
var groupID int64
|
||||
if err := rows.Scan(&groupID); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("scan product group: %w", err)
|
||||
}
|
||||
found[groupID] = struct{}{}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("iterate product groups: %w", err)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return fmt.Errorf("close product groups: %w", err)
|
||||
}
|
||||
if len(found) != len(parsedGroupIDs) {
|
||||
return ErrInvalidProductGroup
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM product.product_category_bindings AS b
|
||||
USING product.product_category AS c
|
||||
WHERE b.product_id = $1
|
||||
AND b.category_id = c.id
|
||||
AND c.node_type = 2
|
||||
AND c.store_id = $2
|
||||
`, parsedProductID, scope.StoreID); err != nil {
|
||||
return fmt.Errorf("delete product group bindings: %w", err)
|
||||
}
|
||||
for index, groupID := range groupIDs {
|
||||
if err := insertCategoryBinding(ctx, tx, bindingIDs[index], productID, groupID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateProductStatus changes the product lifecycle state using optimistic locking.
|
||||
func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID string, next productv1.ProductStatus, expectedVersion int32, scope StoreScope) (*ProductStatusUpdate, error) {
|
||||
if err := requireWriteScope(scope); err != nil {
|
||||
@ -2058,6 +2164,11 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string, sc
|
||||
return nil, nil, err
|
||||
}
|
||||
product.LeafCategoryIDs = leafCategoryIDs
|
||||
groupIDs, err := r.listProductGroupIDs(ctx, productID, scope)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
product.GroupIDs = groupIDs
|
||||
|
||||
return product, skus[productID], nil
|
||||
}
|
||||
@ -2124,6 +2235,41 @@ ORDER BY c.sort_num, c.id
|
||||
return leafCategoryIDs, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepository) listProductGroupIDs(ctx context.Context, productID string, scope StoreScope) ([]string, error) {
|
||||
if err := requireWriteScope(scope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parsedProductID, err := parseID(productID, "product_id")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT c.id
|
||||
FROM product.product_category_bindings AS b
|
||||
JOIN product.product_category AS c ON c.id = b.category_id
|
||||
WHERE b.product_id = $1
|
||||
AND c.node_type = 2
|
||||
AND c.store_id = $2
|
||||
ORDER BY c.sort_num, c.id
|
||||
`, parsedProductID, scope.StoreID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list product group ids: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
groupIDs := make([]string, 0)
|
||||
for rows.Next() {
|
||||
var groupID int64
|
||||
if err := rows.Scan(&groupID); err != nil {
|
||||
return nil, fmt.Errorf("scan product group id: %w", err)
|
||||
}
|
||||
groupIDs = append(groupIDs, formatID(groupID))
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate product group ids: %w", err)
|
||||
}
|
||||
return groupIDs, nil
|
||||
}
|
||||
|
||||
// BatchGetCartItemProducts loads current catalog facts for cart lines in request order.
|
||||
// It includes archived SKUs, but treats soft-deleted SPUs and SKUs as unavailable.
|
||||
func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookups []CartItemProductLookup, scope StoreScope) ([]CartItemProductRecord, error) {
|
||||
|
||||
@ -44,3 +44,10 @@ func TestReplaceProductLeafCategoryBindingsRequiresStoreScope(t *testing.T) {
|
||||
t.Fatalf("err = %v, want %v", err, ErrStoreScopeRequired)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplaceProductGroupBindingsRequiresStoreScope(t *testing.T) {
|
||||
err := replaceProductGroupBindings(nil, nil, "1001", []string{"2001"}, []string{"3001"}, StoreScope{})
|
||||
if err != ErrStoreScopeRequired {
|
||||
t.Fatalf("err = %v, want %v", err, ErrStoreScopeRequired)
|
||||
}
|
||||
}
|
||||
|
||||
@ -95,6 +95,9 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
|
||||
for range product.LeafCategoryIDs {
|
||||
product.CategoryBindingIDs = append(product.CategoryBindingIDs, s.idgen.NextString())
|
||||
}
|
||||
for range product.GroupIDs {
|
||||
product.GroupBindingIDs = append(product.GroupBindingIDs, s.idgen.NextString())
|
||||
}
|
||||
|
||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes(
|
||||
attribute.String("product.spu_no", product.SPUNo),
|
||||
@ -113,6 +116,9 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
|
||||
if errors.Is(err, repository.ErrInvalidLeafCategory) {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
if errors.Is(err, repository.ErrInvalidProductGroup) {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
return nil, status.Errorf(codes.Internal, "create product: %v", err)
|
||||
}
|
||||
observability.IncProductsCreated()
|
||||
@ -314,6 +320,8 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update
|
||||
defer dbSpan.End()
|
||||
var leafCategoryIDs *[]string
|
||||
var categoryBindingIDs []string
|
||||
var groupIDs *[]string
|
||||
var groupBindingIDs []string
|
||||
if containsUpdatePath(req.GetUpdateMask().GetPaths(), "leaf_category_ids") {
|
||||
leafCategoryIDs = &merged.LeafCategoryIDs
|
||||
if s.idgen == nil {
|
||||
@ -323,12 +331,23 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update
|
||||
categoryBindingIDs = append(categoryBindingIDs, s.idgen.NextString())
|
||||
}
|
||||
}
|
||||
if containsUpdatePath(req.GetUpdateMask().GetPaths(), "group_ids") {
|
||||
groupIDs = &merged.GroupIDs
|
||||
if s.idgen == nil {
|
||||
return nil, status.Error(codes.Internal, "id generator is not configured")
|
||||
}
|
||||
for range merged.GroupIDs {
|
||||
groupBindingIDs = append(groupBindingIDs, s.idgen.NextString())
|
||||
}
|
||||
}
|
||||
result, err := s.repo.UpdateProductWithSKUChange(dbCtx, repository.ProductUpdateInput{
|
||||
Product: merged,
|
||||
ExpectedVersion: req.GetExpectedVersion(),
|
||||
SKUChange: skuChange,
|
||||
LeafCategoryIDs: leafCategoryIDs,
|
||||
CategoryBindingIDs: categoryBindingIDs,
|
||||
GroupIDs: groupIDs,
|
||||
GroupBindingIDs: groupBindingIDs,
|
||||
Scope: scope,
|
||||
})
|
||||
if err != nil {
|
||||
@ -345,6 +364,8 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update
|
||||
return nil, status.Error(codes.NotFound, err.Error())
|
||||
case errors.Is(err, repository.ErrInvalidLeafCategory):
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
case errors.Is(err, repository.ErrInvalidProductGroup):
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
default:
|
||||
s.observer.Logger(ctx).Error("update product failed", zap.String("product_id", req.GetProductId()), zap.Error(err))
|
||||
return nil, status.Errorf(codes.Internal, "update product: %v", err)
|
||||
@ -1430,6 +1451,11 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P
|
||||
return repository.ProductRecord{}, nil, err
|
||||
}
|
||||
record.LeafCategoryIDs = leafCategoryIDs
|
||||
groupIDs, err := normalizeGroupIDs(req.GetGroupIds())
|
||||
if err != nil {
|
||||
return repository.ProductRecord{}, nil, err
|
||||
}
|
||||
record.GroupIDs = groupIDs
|
||||
if record.FreightFixedAmount < 0 {
|
||||
return repository.ProductRecord{}, nil, errors.New("freight_fixed_amount must be greater than or equal to 0")
|
||||
}
|
||||
@ -1517,6 +1543,12 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro
|
||||
return repository.ProductRecord{}, err
|
||||
}
|
||||
merged.LeafCategoryIDs = leafCategoryIDs
|
||||
case "group_ids":
|
||||
groupIDs, err := normalizeGroupIDs(update.GetGroupIds())
|
||||
if err != nil {
|
||||
return repository.ProductRecord{}, err
|
||||
}
|
||||
merged.GroupIDs = groupIDs
|
||||
default:
|
||||
return repository.ProductRecord{}, fmt.Errorf("unsupported update field %q", path)
|
||||
}
|
||||
@ -1829,6 +1861,29 @@ func normalizeLeafCategoryIDs(values []string) ([]string, error) {
|
||||
return leafCategoryIDs, nil
|
||||
}
|
||||
|
||||
func normalizeGroupIDs(values []string) ([]string, error) {
|
||||
if len(values) > 100 {
|
||||
return nil, errors.New("group_ids must contain at most 100 items")
|
||||
}
|
||||
groupIDs := make([]string, 0, len(values))
|
||||
seen := make(map[string]struct{}, len(values))
|
||||
for _, value := range values {
|
||||
groupID := strings.TrimSpace(value)
|
||||
if groupID == "" {
|
||||
return nil, errors.New("group_ids must not contain an empty id")
|
||||
}
|
||||
if _, err := normalizeCategoryID(groupID, "group_ids"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, duplicate := seen[groupID]; duplicate {
|
||||
return nil, errors.New("group_ids must not contain duplicates")
|
||||
}
|
||||
seen[groupID] = struct{}{}
|
||||
groupIDs = append(groupIDs, groupID)
|
||||
}
|
||||
return groupIDs, nil
|
||||
}
|
||||
|
||||
func normalizeGroupProductIDs(values []string) ([]string, error) {
|
||||
productIDs := normalizeStringList(values)
|
||||
if len(productIDs) == 0 {
|
||||
@ -1954,6 +2009,7 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
|
||||
Version: product.Version,
|
||||
DeletedAt: timePtrToMillisString(product.DeletedAt),
|
||||
LeafCategoryIds: append([]string(nil), product.LeafCategoryIDs...),
|
||||
GroupIds: append([]string(nil), product.GroupIDs...),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user