mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
feat(product): 支持商品多叶子分类与分类树删除
This commit is contained in:
parent
e7fdf6cc19
commit
891bae4742
@ -45,7 +45,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
|||||||
| `product_id` | 服务内 Snowflake 生成 | `product.products.id` |
|
| `product_id` | 服务内 Snowflake 生成 | `product.products.id` |
|
||||||
| `sku_id` | 服务内 Snowflake 生成,每个 SKU 一个 | `product.product_items.id` |
|
| `sku_id` | 服务内 Snowflake 生成,每个 SKU 一个 | `product.product_items.id` |
|
||||||
| `inventory_id` | 服务内 Snowflake 生成,每个 SKU 库存行一个 | `product.product_item_inventory.id` |
|
| `inventory_id` | 服务内 Snowflake 生成,每个 SKU 库存行一个 | `product.product_item_inventory.id` |
|
||||||
| 分类绑定 ID | 传入 `leaf_category_id` 时服务内 Snowflake 生成 | `product.product_category_bindings.id` |
|
| 分类绑定 ID | 每个 `leaf_category_ids` 项由服务内 Snowflake 生成 | `product.product_category_bindings.id` |
|
||||||
|
|
||||||
常用请求字段:
|
常用请求字段:
|
||||||
|
|
||||||
@ -54,7 +54,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
|||||||
| `spu_no` | 是 | 商品业务编码,未删除商品内唯一 |
|
| `spu_no` | 是 | 商品业务编码,未删除商品内唯一 |
|
||||||
| `title` | 是 | 商品标题 |
|
| `title` | 是 | 商品标题 |
|
||||||
| `selling_point` | 否 | 商品卖点 |
|
| `selling_point` | 否 | 商品卖点 |
|
||||||
| `leaf_category_id` | 否 | 已存在的分类/分组节点 ID;传入后会写入分类绑定 |
|
| `leaf_category_ids` | 否 | 已存在的二级分类 ID 列表;传入后会写入全部分类绑定 |
|
||||||
| `image_ids` | 否 | 商品图片 ID 列表 |
|
| `image_ids` | 否 | 商品图片 ID 列表 |
|
||||||
| `brand_id` / `supplier_id` | 否 | 品牌、供应商 ID |
|
| `brand_id` / `supplier_id` | 否 | 品牌、供应商 ID |
|
||||||
| `status` | 否 | 未传时默认 `PRODUCT_STATUS_INVENTORY`;可取 `INVENTORY`、`ON_SALE`、`OFF_SALE` |
|
| `status` | 否 | 未传时默认 `PRODUCT_STATUS_INVENTORY`;可取 `INVENTORY`、`ON_SALE`、`OFF_SALE` |
|
||||||
@ -72,7 +72,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
|||||||
"spu_no": "SPU202607100001",
|
"spu_no": "SPU202607100001",
|
||||||
"title": "澳洲和牛家庭装",
|
"title": "澳洲和牛家庭装",
|
||||||
"selling_point": "原切谷饲,冷链到家",
|
"selling_point": "原切谷饲,冷链到家",
|
||||||
"leaf_category_id": "726390485721088000",
|
"leaf_category_ids": ["726390485721088000"],
|
||||||
"skus": [
|
"skus": [
|
||||||
{
|
{
|
||||||
"sku_no": "SKU20260710000101",
|
"sku_no": "SKU20260710000101",
|
||||||
|
|||||||
@ -22,6 +22,7 @@ var ErrProductNotFound = errors.New("product not found")
|
|||||||
var ErrCategoryNodeNotFound = errors.New("category or group node not found")
|
var ErrCategoryNodeNotFound = errors.New("category or group node not found")
|
||||||
var ErrCategoryVersionConflict = errors.New("category version conflict")
|
var ErrCategoryVersionConflict = errors.New("category version conflict")
|
||||||
var ErrCategoryTreeConflict = errors.New("category tree conflict")
|
var ErrCategoryTreeConflict = errors.New("category tree conflict")
|
||||||
|
var ErrInvalidLeafCategory = errors.New("category must be an existing second-level category")
|
||||||
|
|
||||||
// ErrSKUNotFound is returned when a SKU does not exist.
|
// ErrSKUNotFound is returned when a SKU does not exist.
|
||||||
var ErrSKUNotFound = errors.New("sku not found")
|
var ErrSKUNotFound = errors.New("sku not found")
|
||||||
@ -68,8 +69,8 @@ type ProductRecord struct {
|
|||||||
FreightTemplateID string
|
FreightTemplateID string
|
||||||
SaleTimeType int32
|
SaleTimeType int32
|
||||||
ScheduledSaleTime *time.Time
|
ScheduledSaleTime *time.Time
|
||||||
LeafCategoryID string
|
LeafCategoryIDs []string
|
||||||
CategoryBindingID string
|
CategoryBindingIDs []string
|
||||||
Version int32
|
Version int32
|
||||||
DeletedAt *time.Time
|
DeletedAt *time.Time
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
@ -174,6 +175,19 @@ type ProductUpdateInput struct {
|
|||||||
Product ProductRecord
|
Product ProductRecord
|
||||||
ExpectedVersion int32
|
ExpectedVersion int32
|
||||||
SKUChange *SKUChange
|
SKUChange *SKUChange
|
||||||
|
// LeafCategoryIDs is nil when category bindings must remain unchanged. A
|
||||||
|
// non-nil empty slice clears all leaf-category bindings.
|
||||||
|
LeafCategoryIDs *[]string
|
||||||
|
CategoryBindingIDs []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// CategoryDeleteResult summarizes a destructive category deletion.
|
||||||
|
type CategoryDeleteResult struct {
|
||||||
|
DeletedCategoryID string
|
||||||
|
DeletedLevel int32
|
||||||
|
DeletedCategoryCount int32
|
||||||
|
UnboundProductCount int64
|
||||||
|
UnboundBindingCount int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// SKUChangeResult records the SKU IDs affected by a product update.
|
// SKUChangeResult records the SKU IDs affected by a product update.
|
||||||
@ -236,6 +250,7 @@ type CategoryTreeUpdate struct {
|
|||||||
CategoryID string
|
CategoryID string
|
||||||
Category *CategoryFieldUpdate
|
Category *CategoryFieldUpdate
|
||||||
Children []CategoryFieldUpdate
|
Children []CategoryFieldUpdate
|
||||||
|
NewChildren []CategoryRecord
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProductRepository provides CRUD access to product tables only [ARC-PROD-001].
|
// ProductRepository provides CRUD access to product tables only [ARC-PROD-001].
|
||||||
@ -401,8 +416,8 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P
|
|||||||
createdSKUs = append(createdSKUs, *createdSKU)
|
createdSKUs = append(createdSKUs, *createdSKU)
|
||||||
}
|
}
|
||||||
|
|
||||||
if product.LeafCategoryID != "" {
|
if len(product.LeafCategoryIDs) > 0 {
|
||||||
if err := insertCategoryBinding(ctx, tx, product.CategoryBindingID, createdProduct.ID, product.LeafCategoryID); err != nil {
|
if err := replaceProductLeafCategoryBindings(ctx, tx, createdProduct.ID, product.LeafCategoryIDs, product.CategoryBindingIDs); err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -505,6 +520,14 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for _, child := range tree.NewChildren {
|
||||||
|
child.NodeType = 1
|
||||||
|
child.ParentID = tree.CategoryID
|
||||||
|
child.Level = 2
|
||||||
|
if _, err := insertCategoryNode(ctx, tx, child); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if err := tx.Commit(); err != nil {
|
if err := tx.Commit(); err != nil {
|
||||||
return fmt.Errorf("commit update category trees: %w", err)
|
return fmt.Errorf("commit update category trees: %w", err)
|
||||||
@ -512,6 +535,112 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteCategory removes a leaf category or a complete top-level category tree
|
||||||
|
// and all affected product bindings in one transaction. Product rows and group
|
||||||
|
// bindings are deliberately retained.
|
||||||
|
func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID string, expectedVersion int32) (*CategoryDeleteResult, error) {
|
||||||
|
if expectedVersion < 0 {
|
||||||
|
return nil, errors.New("expected_version must be non-negative")
|
||||||
|
}
|
||||||
|
tx, err := r.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("begin delete category: %w", err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
target, err := loadCategoryForUpdate(ctx, tx, categoryID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if target.NodeType != 1 || (target.Level != 1 && target.Level != 2) {
|
||||||
|
return nil, ErrCategoryTreeConflict
|
||||||
|
}
|
||||||
|
if target.Version != expectedVersion {
|
||||||
|
return nil, ErrCategoryVersionConflict
|
||||||
|
}
|
||||||
|
|
||||||
|
categoryIDs := []int64{}
|
||||||
|
targetID, err := parseID(target.ID, "category_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if target.Level == 1 {
|
||||||
|
rows, err := tx.QueryContext(ctx, `
|
||||||
|
SELECT id, node_type, name, parent_id, level,
|
||||||
|
COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, version
|
||||||
|
FROM product.product_category
|
||||||
|
WHERE parent_id = $1
|
||||||
|
FOR UPDATE
|
||||||
|
`, targetID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("load category children for delete: %w", err)
|
||||||
|
}
|
||||||
|
for rows.Next() {
|
||||||
|
child, err := scanCategory(rows)
|
||||||
|
if err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if child.NodeType != 1 || child.Level != 2 || child.ParentID != target.ID {
|
||||||
|
rows.Close()
|
||||||
|
return nil, ErrCategoryTreeConflict
|
||||||
|
}
|
||||||
|
childID, err := parseID(child.ID, "category_id")
|
||||||
|
if err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
categoryIDs = append(categoryIDs, childID)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return nil, fmt.Errorf("iterate category children for delete: %w", err)
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return nil, fmt.Errorf("close category children for delete: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
categoryIDs = append(categoryIDs, targetID)
|
||||||
|
placeholders := make([]string, len(categoryIDs))
|
||||||
|
args := make([]any, len(categoryIDs))
|
||||||
|
for index, id := range categoryIDs {
|
||||||
|
placeholders[index] = fmt.Sprintf("$%d", index+1)
|
||||||
|
args[index] = id
|
||||||
|
}
|
||||||
|
whereIDs := strings.Join(placeholders, ", ")
|
||||||
|
|
||||||
|
result := &CategoryDeleteResult{
|
||||||
|
DeletedCategoryID: target.ID,
|
||||||
|
DeletedLevel: target.Level,
|
||||||
|
DeletedCategoryCount: int32(len(categoryIDs)),
|
||||||
|
}
|
||||||
|
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
|
||||||
|
SELECT COUNT(DISTINCT product_id), COUNT(*)
|
||||||
|
FROM product.product_category_bindings
|
||||||
|
WHERE category_id IN (%s)
|
||||||
|
`, whereIDs), args...).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil {
|
||||||
|
return nil, fmt.Errorf("count category bindings for delete: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`
|
||||||
|
DELETE FROM product.product_category_bindings
|
||||||
|
WHERE category_id IN (%s)
|
||||||
|
`, whereIDs), args...); err != nil {
|
||||||
|
return nil, fmt.Errorf("delete category bindings: %w", err)
|
||||||
|
}
|
||||||
|
if target.Level == 1 {
|
||||||
|
if _, err := tx.ExecContext(ctx, `DELETE FROM product.product_category WHERE parent_id = $1`, targetID); err != nil {
|
||||||
|
return nil, fmt.Errorf("delete child categories: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx, `DELETE FROM product.product_category WHERE id = $1`, targetID); err != nil {
|
||||||
|
return nil, fmt.Errorf("delete category: %w", err)
|
||||||
|
}
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return nil, fmt.Errorf("commit delete category: %w", err)
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string) (*CategoryRecord, error) {
|
func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string) (*CategoryRecord, error) {
|
||||||
id, err := parseID(categoryID, "category_id")
|
id, err := parseID(categoryID, "category_id")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -833,6 +962,11 @@ FOR UPDATE
|
|||||||
if currentVersion != input.ExpectedVersion {
|
if currentVersion != input.ExpectedVersion {
|
||||||
return nil, ErrProductVersionConflict
|
return nil, ErrProductVersionConflict
|
||||||
}
|
}
|
||||||
|
if input.LeafCategoryIDs != nil {
|
||||||
|
if err := replaceProductLeafCategoryBindings(ctx, tx, input.Product.ID, *input.LeafCategoryIDs, input.CategoryBindingIDs); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if input.SKUChange != nil && input.SKUChange.Mode == SKUChangeModeReplaceAll && statusFromDB(currentStatus) == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE {
|
if input.SKUChange != nil && input.SKUChange.Mode == SKUChangeModeReplaceAll && statusFromDB(currentStatus) == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE {
|
||||||
return nil, ErrSKUReplacementRequiresNotOnSale
|
return nil, ErrSKUReplacementRequiresNotOnSale
|
||||||
@ -907,6 +1041,87 @@ WHERE id = $1 AND version = $17 AND deleted_at IS NULL
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, productID string, leafCategoryIDs []string, bindingIDs []string) error {
|
||||||
|
if len(leafCategoryIDs) != len(bindingIDs) {
|
||||||
|
return errors.New("leaf category ids and category binding ids must have the same length")
|
||||||
|
}
|
||||||
|
parsedProductID, err := parseID(productID, "product_id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
parsedLeafCategoryIDs := make([]int64, len(leafCategoryIDs))
|
||||||
|
seenCategoryIDs := make(map[int64]struct{}, len(leafCategoryIDs))
|
||||||
|
for index, categoryID := range leafCategoryIDs {
|
||||||
|
parsedLeafCategoryIDs[index], err = parseID(categoryID, "leaf_category_id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, duplicate := seenCategoryIDs[parsedLeafCategoryIDs[index]]; duplicate {
|
||||||
|
return errors.New("leaf_category_ids must not contain duplicates")
|
||||||
|
}
|
||||||
|
seenCategoryIDs[parsedLeafCategoryIDs[index]] = struct{}{}
|
||||||
|
if _, err := parseID(bindingIDs[index], "category binding id"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(parsedLeafCategoryIDs) > 0 {
|
||||||
|
placeholders := make([]string, len(parsedLeafCategoryIDs))
|
||||||
|
args := make([]any, len(parsedLeafCategoryIDs))
|
||||||
|
for index, categoryID := range parsedLeafCategoryIDs {
|
||||||
|
placeholders[index] = fmt.Sprintf("$%d", index+1)
|
||||||
|
args[index] = categoryID
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
|
||||||
|
SELECT id
|
||||||
|
FROM product.product_category
|
||||||
|
WHERE node_type = 1
|
||||||
|
AND level = 2
|
||||||
|
AND id IN (%s)
|
||||||
|
FOR KEY SHARE
|
||||||
|
`, strings.Join(placeholders, ", ")), args...)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("validate leaf categories: %w", err)
|
||||||
|
}
|
||||||
|
found := make(map[int64]struct{}, len(parsedLeafCategoryIDs))
|
||||||
|
for rows.Next() {
|
||||||
|
var categoryID int64
|
||||||
|
if err := rows.Scan(&categoryID); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return fmt.Errorf("scan leaf category: %w", err)
|
||||||
|
}
|
||||||
|
found[categoryID] = struct{}{}
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return fmt.Errorf("iterate leaf categories: %w", err)
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return fmt.Errorf("close leaf categories: %w", err)
|
||||||
|
}
|
||||||
|
if len(found) != len(parsedLeafCategoryIDs) {
|
||||||
|
return ErrInvalidLeafCategory
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = 1
|
||||||
|
AND c.level = 2
|
||||||
|
`, parsedProductID); err != nil {
|
||||||
|
return fmt.Errorf("delete product leaf category bindings: %w", err)
|
||||||
|
}
|
||||||
|
for index, categoryID := range leafCategoryIDs {
|
||||||
|
if err := insertCategoryBinding(ctx, tx, bindingIDs[index], productID, categoryID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// UpdateProductStatus changes the product lifecycle state using optimistic locking.
|
// UpdateProductStatus changes the product lifecycle state using optimistic locking.
|
||||||
func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID string, next productv1.ProductStatus, expectedVersion int32) (*ProductStatusUpdate, error) {
|
func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID string, next productv1.ProductStatus, expectedVersion int32) (*ProductStatusUpdate, error) {
|
||||||
if expectedVersion < 0 {
|
if expectedVersion < 0 {
|
||||||
@ -1412,10 +1627,47 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (*
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
leafCategoryIDs, err := r.listProductLeafCategoryIDs(ctx, productID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
product.LeafCategoryIDs = leafCategoryIDs
|
||||||
|
|
||||||
return product, skus[productID], nil
|
return product, skus[productID], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) listProductLeafCategoryIDs(ctx context.Context, productID string) ([]string, error) {
|
||||||
|
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 = 1
|
||||||
|
AND c.level = 2
|
||||||
|
ORDER BY c.sort_num, c.id
|
||||||
|
`, parsedProductID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("list product leaf category ids: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
leafCategoryIDs := make([]string, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var categoryID int64
|
||||||
|
if err := rows.Scan(&categoryID); err != nil {
|
||||||
|
return nil, fmt.Errorf("scan product leaf category id: %w", err)
|
||||||
|
}
|
||||||
|
leafCategoryIDs = append(leafCategoryIDs, formatID(categoryID))
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, fmt.Errorf("iterate product leaf category ids: %w", err)
|
||||||
|
}
|
||||||
|
return leafCategoryIDs, nil
|
||||||
|
}
|
||||||
|
|
||||||
// BatchGetCartItemProducts loads current catalog facts for cart lines in request order.
|
// BatchGetCartItemProducts loads current catalog facts for cart lines in request order.
|
||||||
// It includes archived SKUs, but treats soft-deleted SPUs and SKUs as unavailable.
|
// It includes archived SKUs, but treats soft-deleted SPUs and SKUs as unavailable.
|
||||||
func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookups []CartItemProductLookup) ([]CartItemProductRecord, error) {
|
func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookups []CartItemProductLookup) ([]CartItemProductRecord, error) {
|
||||||
|
|||||||
@ -85,8 +85,8 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
|
|||||||
skus[i].ID = s.idgen.NextString()
|
skus[i].ID = s.idgen.NextString()
|
||||||
skus[i].Inventory = &repository.InventoryRecord{ID: s.idgen.NextString()}
|
skus[i].Inventory = &repository.InventoryRecord{ID: s.idgen.NextString()}
|
||||||
}
|
}
|
||||||
if product.LeafCategoryID != "" {
|
for range product.LeafCategoryIDs {
|
||||||
product.CategoryBindingID = s.idgen.NextString()
|
product.CategoryBindingIDs = append(product.CategoryBindingIDs, s.idgen.NextString())
|
||||||
}
|
}
|
||||||
|
|
||||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes(
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes(
|
||||||
@ -103,6 +103,9 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
|
|||||||
if errors.Is(err, repository.ErrDuplicateSPUNo) {
|
if errors.Is(err, repository.ErrDuplicateSPUNo) {
|
||||||
return nil, status.Errorf(codes.AlreadyExists, "spu_no already exists: %s", product.SPUNo)
|
return nil, status.Errorf(codes.AlreadyExists, "spu_no already exists: %s", product.SPUNo)
|
||||||
}
|
}
|
||||||
|
if errors.Is(err, repository.ErrInvalidLeafCategory) {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
return nil, status.Errorf(codes.Internal, "create product: %v", err)
|
return nil, status.Errorf(codes.Internal, "create product: %v", err)
|
||||||
}
|
}
|
||||||
observability.IncProductsCreated()
|
observability.IncProductsCreated()
|
||||||
@ -253,10 +256,23 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update
|
|||||||
|
|
||||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId())))
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId())))
|
||||||
defer dbSpan.End()
|
defer dbSpan.End()
|
||||||
|
var leafCategoryIDs *[]string
|
||||||
|
var categoryBindingIDs []string
|
||||||
|
if containsUpdatePath(req.GetUpdateMask().GetPaths(), "leaf_category_ids") {
|
||||||
|
leafCategoryIDs = &merged.LeafCategoryIDs
|
||||||
|
if s.idgen == nil {
|
||||||
|
return nil, status.Error(codes.Internal, "id generator is not configured")
|
||||||
|
}
|
||||||
|
for range merged.LeafCategoryIDs {
|
||||||
|
categoryBindingIDs = append(categoryBindingIDs, s.idgen.NextString())
|
||||||
|
}
|
||||||
|
}
|
||||||
result, err := s.repo.UpdateProductWithSKUChange(dbCtx, repository.ProductUpdateInput{
|
result, err := s.repo.UpdateProductWithSKUChange(dbCtx, repository.ProductUpdateInput{
|
||||||
Product: merged,
|
Product: merged,
|
||||||
ExpectedVersion: req.GetExpectedVersion(),
|
ExpectedVersion: req.GetExpectedVersion(),
|
||||||
SKUChange: skuChange,
|
SKUChange: skuChange,
|
||||||
|
LeafCategoryIDs: leafCategoryIDs,
|
||||||
|
CategoryBindingIDs: categoryBindingIDs,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
dbSpan.RecordError(err)
|
dbSpan.RecordError(err)
|
||||||
@ -270,6 +286,8 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update
|
|||||||
return nil, status.Error(codes.FailedPrecondition, err.Error())
|
return nil, status.Error(codes.FailedPrecondition, err.Error())
|
||||||
case errors.Is(err, repository.ErrSKUNotFound), errors.Is(err, repository.ErrSKUArchived):
|
case errors.Is(err, repository.ErrSKUNotFound), errors.Is(err, repository.ErrSKUArchived):
|
||||||
return nil, status.Error(codes.NotFound, err.Error())
|
return nil, status.Error(codes.NotFound, err.Error())
|
||||||
|
case errors.Is(err, repository.ErrInvalidLeafCategory):
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
default:
|
default:
|
||||||
s.observer.Logger(ctx).Error("update product failed", zap.String("product_id", req.GetProductId()), zap.Error(err))
|
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)
|
return nil, status.Errorf(codes.Internal, "update product: %v", err)
|
||||||
@ -506,6 +524,14 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1.
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
}
|
}
|
||||||
|
for updateIndex := range updates {
|
||||||
|
for childIndex := range updates[updateIndex].NewChildren {
|
||||||
|
if s.idgen == nil {
|
||||||
|
return nil, status.Error(codes.Internal, "id generator is not configured")
|
||||||
|
}
|
||||||
|
updates[updateIndex].NewChildren[childIndex].ID = s.idgen.NextString()
|
||||||
|
}
|
||||||
|
}
|
||||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category_trees.update", trace.WithAttributes(attribute.Int("category.tree_count", len(updates))))
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category_trees.update", trace.WithAttributes(attribute.Int("category.tree_count", len(updates))))
|
||||||
defer dbSpan.End()
|
defer dbSpan.End()
|
||||||
if err := s.repo.UpdateCategoryTrees(dbCtx, updates); err != nil {
|
if err := s.repo.UpdateCategoryTrees(dbCtx, updates); err != nil {
|
||||||
@ -542,6 +568,46 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1.
|
|||||||
return &productv1.UpdateCategoryTreesResponse{Categories: categories}, nil
|
return &productv1.UpdateCategoryTreesResponse{Categories: categories}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteCategory removes a single second-level category or a full top-level
|
||||||
|
// category tree. It never deletes products themselves.
|
||||||
|
func (s *ProductServer) DeleteCategory(ctx context.Context, req *productv1.DeleteCategoryRequest) (*productv1.DeleteCategoryResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
categoryID, err := normalizeCategoryID(req.GetCategoryId(), "category_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
if req.GetExpectedVersion() < 0 {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative")
|
||||||
|
}
|
||||||
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category.delete", trace.WithAttributes(attribute.String("category.id", categoryID)))
|
||||||
|
defer dbSpan.End()
|
||||||
|
result, err := s.repo.DeleteCategory(dbCtx, categoryID, req.GetExpectedVersion())
|
||||||
|
if err != nil {
|
||||||
|
dbSpan.RecordError(err)
|
||||||
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, repository.ErrCategoryNodeNotFound):
|
||||||
|
return nil, status.Error(codes.NotFound, "category not found")
|
||||||
|
case errors.Is(err, repository.ErrCategoryVersionConflict):
|
||||||
|
return nil, status.Error(codes.Aborted, "category version conflict")
|
||||||
|
case errors.Is(err, repository.ErrCategoryTreeConflict):
|
||||||
|
return nil, status.Error(codes.FailedPrecondition, "target is not a deletable product category")
|
||||||
|
default:
|
||||||
|
s.observer.Logger(ctx).Error("delete category failed", zap.String("category_id", categoryID), zap.Error(err))
|
||||||
|
return nil, status.Error(codes.Internal, "delete category")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &productv1.DeleteCategoryResponse{
|
||||||
|
DeletedCategoryId: result.DeletedCategoryID,
|
||||||
|
DeletedLevel: result.DeletedLevel,
|
||||||
|
DeletedCategoryCount: result.DeletedCategoryCount,
|
||||||
|
UnboundProductCount: result.UnboundProductCount,
|
||||||
|
UnboundBindingCount: result.UnboundBindingCount,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// CreateGroup creates a top-level product group.
|
// CreateGroup creates a top-level product group.
|
||||||
func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGroupRequest) (*productv1.CreateGroupResponse, error) {
|
func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGroupRequest) (*productv1.CreateGroupResponse, error) {
|
||||||
if req == nil {
|
if req == nil {
|
||||||
@ -844,7 +910,22 @@ func categoryTreeUpdatesFromRequest(req *productv1.UpdateCategoryTreesRequest) (
|
|||||||
}
|
}
|
||||||
update.Children = append(update.Children, *patch)
|
update.Children = append(update.Children, *patch)
|
||||||
}
|
}
|
||||||
if update.Category == nil && len(update.Children) == 0 {
|
newChildNames := make(map[string]struct{}, len(tree.GetNewChildCategories()))
|
||||||
|
for _, child := range tree.GetNewChildCategories() {
|
||||||
|
if child == nil {
|
||||||
|
return nil, nil, errors.New("new_child_categories item is required")
|
||||||
|
}
|
||||||
|
newChild, err := newChildCategoryFromProto(child)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
if _, exists := newChildNames[newChild.Name]; exists {
|
||||||
|
return nil, nil, errors.New("new_child_categories.name must be unique")
|
||||||
|
}
|
||||||
|
newChildNames[newChild.Name] = struct{}{}
|
||||||
|
update.NewChildren = append(update.NewChildren, newChild)
|
||||||
|
}
|
||||||
|
if update.Category == nil && len(update.Children) == 0 && len(update.NewChildren) == 0 {
|
||||||
return nil, nil, errors.New("category tree patch must update category or child_categories")
|
return nil, nil, errors.New("category tree patch must update category or child_categories")
|
||||||
}
|
}
|
||||||
sort.Slice(update.Children, func(i, j int) bool { return update.Children[i].ID < update.Children[j].ID })
|
sort.Slice(update.Children, func(i, j int) bool { return update.Children[i].ID < update.Children[j].ID })
|
||||||
@ -856,6 +937,28 @@ func categoryTreeUpdatesFromRequest(req *productv1.UpdateCategoryTreesRequest) (
|
|||||||
return updates, rootIDs, nil
|
return updates, rootIDs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func newChildCategoryFromProto(child *productv1.CreateChildCategory) (repository.CategoryRecord, error) {
|
||||||
|
name, err := normalizeNodeName(child.GetName(), "new_child_categories.name")
|
||||||
|
if err != nil {
|
||||||
|
return repository.CategoryRecord{}, err
|
||||||
|
}
|
||||||
|
imageIDs, err := normalizeNodeImageIDs(child.GetImageJson())
|
||||||
|
if err != nil {
|
||||||
|
return repository.CategoryRecord{}, err
|
||||||
|
}
|
||||||
|
statusValue, err := normalizeNodeStatus(child.Status)
|
||||||
|
if err != nil {
|
||||||
|
return repository.CategoryRecord{}, err
|
||||||
|
}
|
||||||
|
return repository.CategoryRecord{
|
||||||
|
NodeType: categoryNodeType,
|
||||||
|
Name: name,
|
||||||
|
ImageIDs: imageIDs,
|
||||||
|
SortNum: child.GetSortNum(),
|
||||||
|
Status: statusValue,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
func categoryFieldUpdateFromProto(id string, patch *productv1.CategoryFieldPatch, field string) (*repository.CategoryFieldUpdate, error) {
|
func categoryFieldUpdateFromProto(id string, patch *productv1.CategoryFieldPatch, field string) (*repository.CategoryFieldUpdate, error) {
|
||||||
if patch == nil {
|
if patch == nil {
|
||||||
return nil, fmt.Errorf("%s is required", field)
|
return nil, fmt.Errorf("%s is required", field)
|
||||||
@ -1019,8 +1122,12 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P
|
|||||||
FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()),
|
FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()),
|
||||||
SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1),
|
SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1),
|
||||||
ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()),
|
ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()),
|
||||||
LeafCategoryID: strings.TrimSpace(req.GetLeafCategoryId()),
|
|
||||||
}
|
}
|
||||||
|
leafCategoryIDs, err := normalizeLeafCategoryIDs(req.GetLeafCategoryIds())
|
||||||
|
if err != nil {
|
||||||
|
return repository.ProductRecord{}, nil, err
|
||||||
|
}
|
||||||
|
record.LeafCategoryIDs = leafCategoryIDs
|
||||||
if record.FreightFixedAmount < 0 {
|
if record.FreightFixedAmount < 0 {
|
||||||
return repository.ProductRecord{}, nil, errors.New("freight_fixed_amount must be greater than or equal to 0")
|
return repository.ProductRecord{}, nil, errors.New("freight_fixed_amount must be greater than or equal to 0")
|
||||||
}
|
}
|
||||||
@ -1102,6 +1209,12 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro
|
|||||||
merged.ScheduledSaleTime = timestampToTime(update.GetScheduledSaleTime())
|
merged.ScheduledSaleTime = timestampToTime(update.GetScheduledSaleTime())
|
||||||
case "goods_type":
|
case "goods_type":
|
||||||
merged.GoodsType = update.GetGoodsType()
|
merged.GoodsType = update.GetGoodsType()
|
||||||
|
case "leaf_category_ids":
|
||||||
|
leafCategoryIDs, err := normalizeLeafCategoryIDs(update.GetLeafCategoryIds())
|
||||||
|
if err != nil {
|
||||||
|
return repository.ProductRecord{}, err
|
||||||
|
}
|
||||||
|
merged.LeafCategoryIDs = leafCategoryIDs
|
||||||
default:
|
default:
|
||||||
return repository.ProductRecord{}, fmt.Errorf("unsupported update field %q", path)
|
return repository.ProductRecord{}, fmt.Errorf("unsupported update field %q", path)
|
||||||
}
|
}
|
||||||
@ -1109,6 +1222,15 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro
|
|||||||
return merged, nil
|
return merged, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func containsUpdatePath(paths []string, target string) bool {
|
||||||
|
for _, path := range paths {
|
||||||
|
if path == target {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func validateProductForUpdate(product repository.ProductRecord) error {
|
func validateProductForUpdate(product repository.ProductRecord) error {
|
||||||
if strings.TrimSpace(product.Title) == "" {
|
if strings.TrimSpace(product.Title) == "" {
|
||||||
return errors.New("title is required")
|
return errors.New("title is required")
|
||||||
@ -1382,6 +1504,29 @@ func normalizeStringList(values []string) []string {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func normalizeLeafCategoryIDs(values []string) ([]string, error) {
|
||||||
|
if len(values) > 100 {
|
||||||
|
return nil, errors.New("leaf_category_ids must contain at most 100 items")
|
||||||
|
}
|
||||||
|
leafCategoryIDs := make([]string, 0, len(values))
|
||||||
|
seen := make(map[string]struct{}, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
categoryID := strings.TrimSpace(value)
|
||||||
|
if categoryID == "" {
|
||||||
|
return nil, errors.New("leaf_category_ids must not contain an empty id")
|
||||||
|
}
|
||||||
|
if _, err := normalizeCategoryID(categoryID, "leaf_category_ids"); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if _, duplicate := seen[categoryID]; duplicate {
|
||||||
|
return nil, errors.New("leaf_category_ids must not contain duplicates")
|
||||||
|
}
|
||||||
|
seen[categoryID] = struct{}{}
|
||||||
|
leafCategoryIDs = append(leafCategoryIDs, categoryID)
|
||||||
|
}
|
||||||
|
return leafCategoryIDs, nil
|
||||||
|
}
|
||||||
|
|
||||||
func normalizeGroupProductIDs(values []string) ([]string, error) {
|
func normalizeGroupProductIDs(values []string) ([]string, error) {
|
||||||
productIDs := normalizeStringList(values)
|
productIDs := normalizeStringList(values)
|
||||||
if len(productIDs) == 0 {
|
if len(productIDs) == 0 {
|
||||||
@ -1506,6 +1651,7 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
|
|||||||
ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime),
|
ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime),
|
||||||
Version: product.Version,
|
Version: product.Version,
|
||||||
DeletedAt: timePtrToMillisString(product.DeletedAt),
|
DeletedAt: timePtrToMillisString(product.DeletedAt),
|
||||||
|
LeafCategoryIds: append([]string(nil), product.LeafCategoryIDs...),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user