mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
feat: add category_properties field to products and implement group creation with child groups
This commit is contained in:
parent
c2d0aa604f
commit
4e010a6476
@ -89,6 +89,7 @@ type ProductRecord struct {
|
||||
Status productv1.ProductStatus
|
||||
Attrs map[string]any
|
||||
CrossBorderJSON string
|
||||
CategoryPropertiesJSON string
|
||||
FreightChargeType int32
|
||||
FreightFixedAmount int64
|
||||
FreightTemplateID string
|
||||
@ -279,6 +280,7 @@ type CategoryProductRecord struct {
|
||||
SoldQuantity int64
|
||||
StockQuantity int64
|
||||
LockedQuantity int64
|
||||
CategoryPropertiesJSON string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
@ -317,6 +319,14 @@ type CategoryRecord struct {
|
||||
ProductCount int64
|
||||
}
|
||||
|
||||
// GroupListFilter contains optional product-group list constraints.
|
||||
type GroupListFilter struct {
|
||||
OnlyVisible bool
|
||||
FirstLevelName string
|
||||
SecondLevelName string
|
||||
ExactMatch bool
|
||||
}
|
||||
|
||||
// CategoryFieldUpdate selects mutable fields of one category node.
|
||||
type CategoryFieldUpdate struct {
|
||||
ID string
|
||||
@ -525,6 +535,7 @@ CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(pric
|
||||
CREATE INDEX IF NOT EXISTS idx_products_active_created_id ON product.products(created_at DESC, id DESC) WHERE deleted_at IS NULL;
|
||||
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS tenant_id BIGINT;
|
||||
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS store_id BIGINT;
|
||||
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS category_properties JSONB NOT NULL DEFAULT '{}'::JSONB;
|
||||
ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS tenant_id BIGINT;
|
||||
ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS store_id BIGINT;
|
||||
ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS campaign_id BIGINT;
|
||||
@ -541,9 +552,11 @@ CREATE INDEX IF NOT EXISTS idx_products_store_id ON product.products (store_id)
|
||||
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_id ON product.catalog_category (store_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_product_category_campaign_id
|
||||
ON product.catalog_category (campaign_id) WHERE campaign_id IS NOT NULL;
|
||||
DROP INDEX IF EXISTS product.uq_product_category_group_normalized_name;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name
|
||||
ON product.catalog_category (
|
||||
store_id,
|
||||
COALESCE(parent_id, 0),
|
||||
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
|
||||
)
|
||||
WHERE node_type = 2;
|
||||
@ -615,6 +628,10 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
categoryProperties, err := productCategoryPropertiesJSON(product)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
@ -622,7 +639,7 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if _, err := insertProduct(ctx, tx, product, attrs); err != nil {
|
||||
if _, err := insertProduct(ctx, tx, product, attrs, categoryProperties); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
@ -640,6 +657,10 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
categoryProperties, err := productCategoryPropertiesJSON(product)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
@ -647,7 +668,7 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
createdProduct, err := insertProduct(ctx, tx, product, attrs)
|
||||
createdProduct, err := insertProduct(ctx, tx, product, attrs, categoryProperties)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@ -741,6 +762,82 @@ func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category Cat
|
||||
return createdCategory, nil
|
||||
}
|
||||
|
||||
// CreateGroupNode inserts a first-level group or a child of a first-level group.
|
||||
func (r *ProductRepository) CreateGroupNode(ctx context.Context, group CategoryRecord, scope StoreScope) (*CategoryRecord, error) {
|
||||
if err := requireWriteScope(scope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin create group node: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
group.NodeType = 2
|
||||
if group.ParentID == "" {
|
||||
group.Level = 1
|
||||
} else {
|
||||
parent, err := loadCategoryForUpdate(ctx, tx, group.ParentID, scope)
|
||||
if errors.Is(err, ErrCategoryNodeNotFound) {
|
||||
return nil, ErrInvalidProductGroup
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if parent.NodeType != 2 || parent.Level != 1 || parent.ParentID != "" {
|
||||
return nil, ErrInvalidProductGroup
|
||||
}
|
||||
group.ParentID = parent.ID
|
||||
group.Level = 2
|
||||
}
|
||||
createdGroup, err := insertCategoryNode(ctx, tx, group, scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("commit create group node: %w", err)
|
||||
}
|
||||
return createdGroup, nil
|
||||
}
|
||||
|
||||
// CreateGroupChildren inserts a batch of second-level groups under one locked first-level group.
|
||||
func (r *ProductRepository) CreateGroupChildren(ctx context.Context, parentID string, children []CategoryRecord, scope StoreScope) ([]*CategoryRecord, error) {
|
||||
if err := requireWriteScope(scope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(children) == 0 {
|
||||
return nil, errors.New("children is required")
|
||||
}
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin create group children: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
parent, err := loadCategoryForUpdate(ctx, tx, parentID, scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if parent.NodeType != 2 || parent.Level != 1 || parent.ParentID != "" {
|
||||
return nil, ErrInvalidProductGroup
|
||||
}
|
||||
created := make([]*CategoryRecord, 0, len(children))
|
||||
for _, child := range children {
|
||||
child.NodeType = 2
|
||||
child.ParentID = parent.ID
|
||||
child.Level = 2
|
||||
node, err := insertCategoryNode(ctx, tx, child, scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
created = append(created, node)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("commit create group children: %w", err)
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// UpdateCategoryTrees applies all requested root and direct-child patches in a
|
||||
// single transaction. Callers must supply already-validated patch fields.
|
||||
func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []CategoryTreeUpdate, scope StoreScope) error {
|
||||
@ -967,7 +1064,7 @@ func (r *ProductRepository) DeleteGroup(ctx context.Context, groupID string, exp
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if target.NodeType != 2 {
|
||||
if target.NodeType != 2 || (target.Level != 1 && target.Level != 2) {
|
||||
return nil, ErrInvalidProductGroup
|
||||
}
|
||||
if target.Version != expectedVersion {
|
||||
@ -977,20 +1074,72 @@ func (r *ProductRepository) DeleteGroup(ctx context.Context, groupID string, exp
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
groupIDs := []int64{targetID}
|
||||
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, campaign_id, version
|
||||
FROM product.catalog_category
|
||||
WHERE parent_id = $1 AND store_id = $2
|
||||
FOR UPDATE
|
||||
`, targetID, scope.StoreID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load child groups for delete: %w", err)
|
||||
}
|
||||
for rows.Next() {
|
||||
child, err := scanCategory(rows)
|
||||
if err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
if child.NodeType != 2 || child.Level != 2 || child.ParentID != target.ID {
|
||||
rows.Close()
|
||||
return nil, ErrInvalidProductGroup
|
||||
}
|
||||
childID, err := parseID(child.ID, "group_id")
|
||||
if err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
groupIDs = append(groupIDs, childID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("iterate child groups for delete: %w", err)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, fmt.Errorf("close child groups for delete: %w", err)
|
||||
}
|
||||
}
|
||||
placeholders := make([]string, len(groupIDs))
|
||||
args := make([]any, len(groupIDs))
|
||||
for index, id := range groupIDs {
|
||||
placeholders[index] = fmt.Sprintf("$%d", index+1)
|
||||
args[index] = id
|
||||
}
|
||||
whereIDs := strings.Join(placeholders, ", ")
|
||||
result := &GroupDeleteResult{DeletedGroupID: target.ID}
|
||||
if err := tx.QueryRowContext(ctx, `
|
||||
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
|
||||
SELECT COUNT(DISTINCT product_id), COUNT(*)
|
||||
FROM product.product_catalog_bindings
|
||||
WHERE category_id = $1
|
||||
`, targetID).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil {
|
||||
WHERE category_id IN (%s)
|
||||
`, whereIDs), args...).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil {
|
||||
return nil, fmt.Errorf("count group bindings for delete: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`
|
||||
DELETE FROM product.product_catalog_bindings
|
||||
WHERE category_id = $1
|
||||
`, targetID); err != nil {
|
||||
WHERE category_id IN (%s)
|
||||
`, whereIDs), args...); err != nil {
|
||||
return nil, fmt.Errorf("delete group bindings: %w", err)
|
||||
}
|
||||
if target.Level == 1 {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM product.catalog_category
|
||||
WHERE parent_id = $1 AND store_id = $2 AND node_type = 2
|
||||
`, targetID, scope.StoreID); err != nil {
|
||||
return nil, fmt.Errorf("delete child groups: %w", err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM product.catalog_category
|
||||
WHERE id = $1 AND store_id = $2 AND node_type = 2
|
||||
@ -1335,6 +1484,10 @@ func (r *ProductRepository) UpdateProductWithSKUChange(ctx context.Context, inpu
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
categoryProperties, err := productCategoryPropertiesJSON(input.Product)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
brandID, err := nullableID(input.Product.BrandID, "brand_id")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -1403,17 +1556,18 @@ SET title = $2,
|
||||
goods_type = $9,
|
||||
service_guarantees = $10,
|
||||
cross_border = $11::jsonb,
|
||||
freight_charge_type = $12,
|
||||
freight_fixed_amount = $13,
|
||||
freight_template_id = $14,
|
||||
sale_time_type = $15,
|
||||
scheduled_sale_time = $16,
|
||||
category_properties = $12::jsonb,
|
||||
freight_charge_type = $13,
|
||||
freight_fixed_amount = $14,
|
||||
freight_template_id = $15,
|
||||
sale_time_type = $16,
|
||||
scheduled_sale_time = $17,
|
||||
version = version + 1,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND version = $17 AND deleted_at IS NULL AND store_id = $18
|
||||
WHERE id = $1 AND version = $18 AND deleted_at IS NULL AND store_id = $19
|
||||
`, productID, input.Product.Title, input.Product.SellingPoint, brandID, supplierID,
|
||||
stringSliceOrEmpty(input.Product.ImageIDs), input.Product.DetailHTML, input.Product.MemberDiscountEnabled,
|
||||
int16(input.Product.GoodsType), stringSliceOrEmpty(input.Product.ServiceGuarantees), attrs,
|
||||
int16(input.Product.GoodsType), stringSliceOrEmpty(input.Product.ServiceGuarantees), attrs, categoryProperties,
|
||||
int16(input.Product.FreightChargeType), input.Product.FreightFixedAmount, freightTemplateID,
|
||||
int16(input.Product.SaleTimeType), input.Product.ScheduledSaleTime, input.ExpectedVersion, input.Scope.StoreID); err != nil {
|
||||
return nil, fmt.Errorf("update product %s: %w", input.Product.ID, err)
|
||||
@ -3014,6 +3168,7 @@ SELECT p.updated_at,
|
||||
p.spu_no,
|
||||
p.status,
|
||||
COALESCE(to_json(p.image_ids)::text, '[]'),
|
||||
COALESCE(p.category_properties, '{}'::jsonb)::text,
|
||||
COALESCE(sku_summary.price, 0),
|
||||
COALESCE(sku_summary.sold_quantity, 0),
|
||||
COALESCE(sku_summary.stock_quantity, 0),
|
||||
@ -3165,6 +3320,7 @@ SELECT p.updated_at,
|
||||
p.spu_no,
|
||||
p.status,
|
||||
COALESCE(to_json(p.image_ids)::text, '[]'),
|
||||
COALESCE(p.category_properties, '{}'::jsonb)::text,
|
||||
COALESCE(sku_summary.price, 0),
|
||||
COALESCE(sku_summary.sold_quantity, 0),
|
||||
COALESCE(sku_summary.stock_quantity, 0),
|
||||
@ -3349,6 +3505,7 @@ SELECT p.updated_at,
|
||||
p.spu_no,
|
||||
p.status,
|
||||
COALESCE(to_json(p.image_ids)::text, '[]'),
|
||||
COALESCE(p.category_properties, '{}'::jsonb)::text,
|
||||
COALESCE(sku_summary.price, 0),
|
||||
COALESCE(sku_summary.sold_quantity, 0),
|
||||
COALESCE(sku_summary.stock_quantity, 0),
|
||||
@ -3507,10 +3664,16 @@ ORDER BY level ASC, sort_num ASC, id ASC
|
||||
}
|
||||
|
||||
// ListGroupNodes loads product group nodes.
|
||||
func (r *ProductRepository) ListGroupNodes(ctx context.Context, onlyVisible bool, scope StoreScope) ([]*CategoryRecord, error) {
|
||||
func (r *ProductRepository) ListGroupNodes(ctx context.Context, filter GroupListFilter, scope StoreScope) ([]*CategoryRecord, error) {
|
||||
if err := requireWriteScope(scope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
firstLevelName := strings.TrimSpace(filter.FirstLevelName)
|
||||
secondLevelName := strings.TrimSpace(filter.SecondLevelName)
|
||||
if !filter.ExactMatch {
|
||||
firstLevelName = escapeLikeLiteral(firstLevelName)
|
||||
secondLevelName = escapeLikeLiteral(secondLevelName)
|
||||
}
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT c.id,
|
||||
c.node_type,
|
||||
@ -3524,16 +3687,27 @@ SELECT c.id,
|
||||
c.version,
|
||||
COUNT(p.id) AS product_count
|
||||
FROM product.catalog_category AS c
|
||||
LEFT JOIN product.catalog_category AS parent ON parent.id = c.parent_id
|
||||
AND parent.store_id = c.store_id
|
||||
AND parent.node_type = 2
|
||||
LEFT JOIN product.product_catalog_bindings AS b ON b.category_id = c.id
|
||||
LEFT JOIN product.products AS p ON p.id = b.product_id
|
||||
AND p.store_id = c.store_id
|
||||
AND p.deleted_at IS NULL
|
||||
WHERE c.node_type = 2
|
||||
AND c.store_id = $2
|
||||
AND ($1 = false OR c.status = 1)
|
||||
AND c.store_id = $1
|
||||
AND ($2 = false OR c.status = 1)
|
||||
AND ($3 = '' OR CASE
|
||||
WHEN $5 THEN LOWER(CASE WHEN c.level = 1 THEN c.name ELSE COALESCE(parent.name, '') END) = LOWER($3)
|
||||
ELSE CASE WHEN c.level = 1 THEN c.name ELSE COALESCE(parent.name, '') END ILIKE ('%' || $3 || '%') ESCAPE '\'
|
||||
END)
|
||||
AND ($4 = '' OR (c.level = 2 AND CASE
|
||||
WHEN $5 THEN LOWER(c.name) = LOWER($4)
|
||||
ELSE c.name ILIKE ('%' || $4 || '%') ESCAPE '\'
|
||||
END))
|
||||
GROUP BY c.id
|
||||
ORDER BY c.sort_num ASC, c.id ASC
|
||||
`, onlyVisible, scope.StoreID)
|
||||
`, scope.StoreID, filter.OnlyVisible, firstLevelName, secondLevelName, filter.ExactMatch)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query group nodes: %w", err)
|
||||
}
|
||||
@ -3598,6 +3772,7 @@ SELECT id,
|
||||
COALESCE(to_json(service_guarantees)::text, '[]'),
|
||||
status,
|
||||
cross_border,
|
||||
category_properties,
|
||||
freight_charge_type,
|
||||
freight_fixed_amount,
|
||||
freight_template_id,
|
||||
@ -3637,7 +3812,7 @@ ORDER BY created_at ASC
|
||||
return products, nil
|
||||
}
|
||||
|
||||
func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs []byte) (*ProductRecord, error) {
|
||||
func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs, categoryProperties []byte) (*ProductRecord, error) {
|
||||
if err := requireWriteScope(product.Scope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -3674,13 +3849,14 @@ INSERT INTO product.products (
|
||||
service_guarantees,
|
||||
status,
|
||||
cross_border,
|
||||
category_properties,
|
||||
freight_charge_type,
|
||||
freight_fixed_amount,
|
||||
freight_template_id,
|
||||
sale_time_type,
|
||||
scheduled_sale_time
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15::jsonb, $16, $17, $18, $19, $20)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15::jsonb, $16::jsonb, $17, $18, $19, $20, $21)
|
||||
RETURNING id,
|
||||
spu_no,
|
||||
title,
|
||||
@ -3694,6 +3870,7 @@ RETURNING id,
|
||||
COALESCE(to_json(service_guarantees)::text, '[]'),
|
||||
status,
|
||||
cross_border,
|
||||
category_properties,
|
||||
freight_charge_type,
|
||||
freight_fixed_amount,
|
||||
freight_template_id,
|
||||
@ -3705,7 +3882,7 @@ RETURNING id,
|
||||
updated_at
|
||||
`, id, product.Scope.TenantID, product.Scope.StoreID, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs),
|
||||
product.DetailHTML, product.MemberDiscountEnabled, int16(product.GoodsType), stringSliceOrEmpty(product.ServiceGuarantees),
|
||||
statusToDB(product.Status), attrs, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID,
|
||||
statusToDB(product.Status), attrs, categoryProperties, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID,
|
||||
int16(product.SaleTimeType), product.ScheduledSaleTime)
|
||||
|
||||
createdProduct, err := scanProduct(row)
|
||||
@ -4089,6 +4266,7 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) {
|
||||
id int64
|
||||
status int16
|
||||
imageIDsJSON string
|
||||
categoryPropertiesJSON string
|
||||
)
|
||||
if err := scanner.Scan(
|
||||
&rec.UpdatedAt,
|
||||
@ -4098,6 +4276,7 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) {
|
||||
&rec.SPUNo,
|
||||
&status,
|
||||
&imageIDsJSON,
|
||||
&categoryPropertiesJSON,
|
||||
&rec.Price,
|
||||
&rec.SoldQuantity,
|
||||
&rec.StockQuantity,
|
||||
@ -4113,6 +4292,10 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) {
|
||||
return nil, fmt.Errorf("unmarshal category product image_ids: %w", err)
|
||||
}
|
||||
rec.ImageIDs = imageIDs
|
||||
rec.CategoryPropertiesJSON = categoryPropertiesJSON
|
||||
if rec.CategoryPropertiesJSON == "" {
|
||||
rec.CategoryPropertiesJSON = "{}"
|
||||
}
|
||||
return &rec, nil
|
||||
}
|
||||
|
||||
@ -4127,6 +4310,7 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) {
|
||||
goodsType int16
|
||||
status int16
|
||||
attrsJSON []byte
|
||||
categoryPropertiesJSON []byte
|
||||
freightChargeType int16
|
||||
freightTemplateID sql.NullInt64
|
||||
saleTimeType int16
|
||||
@ -4148,6 +4332,7 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) {
|
||||
&serviceGuaranteesJSON,
|
||||
&status,
|
||||
&attrsJSON,
|
||||
&categoryPropertiesJSON,
|
||||
&freightChargeType,
|
||||
&rec.FreightFixedAmount,
|
||||
&freightTemplateID,
|
||||
@ -4185,6 +4370,10 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) {
|
||||
if rec.CrossBorderJSON == "" {
|
||||
rec.CrossBorderJSON = "{}"
|
||||
}
|
||||
rec.CategoryPropertiesJSON = string(categoryPropertiesJSON)
|
||||
if rec.CategoryPropertiesJSON == "" {
|
||||
rec.CategoryPropertiesJSON = "{}"
|
||||
}
|
||||
if len(attrsJSON) > 0 {
|
||||
if err := json.Unmarshal(attrsJSON, &rec.Attrs); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal product attrs: %w", err)
|
||||
@ -4439,6 +4628,22 @@ func productCrossBorderJSON(product ProductRecord) ([]byte, error) {
|
||||
return attrs, nil
|
||||
}
|
||||
|
||||
func productCategoryPropertiesJSON(product ProductRecord) ([]byte, error) {
|
||||
raw := strings.TrimSpace(product.CategoryPropertiesJSON)
|
||||
if raw == "" {
|
||||
return []byte("{}"), nil
|
||||
}
|
||||
var properties map[string]any
|
||||
if err := json.Unmarshal([]byte(raw), &properties); err != nil || properties == nil {
|
||||
return nil, errors.New("category_properties must be a JSON object")
|
||||
}
|
||||
normalized, err := json.Marshal(properties)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal category_properties: %w", err)
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func applySKUAttributes(rec *SKURecord) error {
|
||||
if rec == nil {
|
||||
return nil
|
||||
|
||||
@ -1,6 +1,10 @@
|
||||
package server
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"testing"
|
||||
|
||||
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||
)
|
||||
|
||||
func TestNormalizeNodeNameCollapsesUnicodeWhitespace(t *testing.T) {
|
||||
name, err := normalizeNodeName(" Summer\t\n Sale ", "name")
|
||||
@ -14,3 +18,22 @@ func TestNormalizeNodeNameCollapsesUnicodeWhitespace(t *testing.T) {
|
||||
t.Fatal("normalized name key must ignore case")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupTreeFromCreateRequestAcceptsChildren(t *testing.T) {
|
||||
group, children, err := groupTreeFromCreateRequest(&productv1.CreateGroupRequest{
|
||||
Name: "Parent group",
|
||||
Children: []*productv1.CreateChildGroup{
|
||||
{Name: "Child group"},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("groupTreeFromCreateRequest: %v", err)
|
||||
}
|
||||
if group.Level != 1 || len(children) != 1 || children[0].Level != 2 {
|
||||
t.Fatalf("group = %#v, children = %#v", group, children)
|
||||
}
|
||||
|
||||
if _, _, err := groupTreeFromCreateRequest(&productv1.CreateGroupRequest{Name: "Parent", Children: []*productv1.CreateChildGroup{{Name: "same"}, {Name: "same"}}}); err == nil {
|
||||
t.Fatal("expected duplicate child names to fail")
|
||||
}
|
||||
}
|
||||
|
||||
@ -20,6 +20,7 @@ import (
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/types/known/fieldmaskpb"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||
@ -1170,7 +1171,7 @@ func (s *ProductServer) DeleteCategory(ctx context.Context, req *productv1.Delet
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreateGroup creates a top-level product group.
|
||||
// CreateGroup creates a top-level product group and optional child groups.
|
||||
func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGroupRequest) (*productv1.CreateGroupResponse, error) {
|
||||
if req == nil {
|
||||
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||
@ -1183,18 +1184,22 @@ func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGr
|
||||
return nil, status.Error(codes.Internal, "id generator is not configured")
|
||||
}
|
||||
|
||||
group, err := groupFromCreateRequest(req)
|
||||
group, children, err := groupTreeFromCreateRequest(req)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
group.ID = s.idgen.NextString()
|
||||
for index := range children {
|
||||
children[index].ID = s.idgen.NextString()
|
||||
}
|
||||
|
||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_group", trace.WithAttributes(
|
||||
attribute.String("group.name", group.Name),
|
||||
attribute.Int("group.child_count", len(children)),
|
||||
))
|
||||
defer dbSpan.End()
|
||||
|
||||
createdGroup, err := s.repo.CreateCategoryNode(dbCtx, group, scope)
|
||||
createdGroup, createdChildren, err := s.repo.CreateCategoryTree(dbCtx, group, children, scope)
|
||||
if err != nil {
|
||||
dbSpan.RecordError(err)
|
||||
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||
@ -1205,9 +1210,52 @@ func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGr
|
||||
return nil, status.Errorf(codes.Internal, "create group: %v", err)
|
||||
}
|
||||
|
||||
return &productv1.CreateGroupResponse{
|
||||
Group: toProtoGroupNode(createdGroup),
|
||||
}, nil
|
||||
protoGroup := toProtoGroupNode(createdGroup)
|
||||
for _, child := range createdChildren {
|
||||
protoGroup.Children = append(protoGroup.Children, toProtoGroupNode(child))
|
||||
}
|
||||
return &productv1.CreateGroupResponse{Group: protoGroup}, nil
|
||||
}
|
||||
|
||||
// CreateGroupChildren batch-creates second-level groups under one first-level group.
|
||||
func (s *ProductServer) CreateGroupChildren(ctx context.Context, req *productv1.CreateGroupChildrenRequest) (*productv1.CreateGroupChildrenResponse, error) {
|
||||
if req == nil {
|
||||
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||
}
|
||||
scope, err := requireStoreScope(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parentID, err := normalizeCategoryID(req.GetGroupId(), "group_id")
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
children, err := groupChildrenFromProto(req.GetChildren())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
if s.idgen == nil {
|
||||
return nil, status.Error(codes.Internal, "id generator is not configured")
|
||||
}
|
||||
for index := range children {
|
||||
children[index].ID = s.idgen.NextString()
|
||||
}
|
||||
created, err := s.repo.CreateGroupChildren(ctx, parentID, children, scope)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, repository.ErrGroupNameExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "group name already exists")
|
||||
case errors.Is(err, repository.ErrInvalidProductGroup), errors.Is(err, repository.ErrCategoryNodeNotFound):
|
||||
return nil, status.Error(codes.InvalidArgument, "group_id must identify a first-level group")
|
||||
default:
|
||||
return nil, status.Errorf(codes.Internal, "create group children: %v", err)
|
||||
}
|
||||
}
|
||||
groups := make([]*productv1.GroupNode, 0, len(created))
|
||||
for _, child := range created {
|
||||
groups = append(groups, toProtoGroupNode(child))
|
||||
}
|
||||
return &productv1.CreateGroupChildrenResponse{Groups: groups}, nil
|
||||
}
|
||||
|
||||
// UpdateGroup updates mutable fields on one product group.
|
||||
@ -1297,16 +1345,21 @@ func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroup
|
||||
return nil, err
|
||||
}
|
||||
onlyVisible := false
|
||||
filter := repository.GroupListFilter{}
|
||||
if req != nil {
|
||||
onlyVisible = req.GetOnlyVisible()
|
||||
filter.FirstLevelName = strings.TrimSpace(req.GetFirstLevelName())
|
||||
filter.SecondLevelName = strings.TrimSpace(req.GetSecondLevelName())
|
||||
filter.ExactMatch = req.GetExactMatch()
|
||||
}
|
||||
filter.OnlyVisible = onlyVisible
|
||||
|
||||
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_groups", trace.WithAttributes(
|
||||
attribute.Bool("group.only_visible", onlyVisible),
|
||||
))
|
||||
defer dbSpan.End()
|
||||
|
||||
groups, err := s.repo.ListGroupNodes(dbCtx, onlyVisible, scope)
|
||||
groups, err := s.repo.ListGroupNodes(dbCtx, filter, scope)
|
||||
if err != nil {
|
||||
dbSpan.RecordError(err)
|
||||
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||
@ -1815,29 +1868,63 @@ func normalizeCategoryID(value, field string) (string, error) {
|
||||
return trimmed, nil
|
||||
}
|
||||
|
||||
func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.CategoryRecord, error) {
|
||||
func groupTreeFromCreateRequest(req *productv1.CreateGroupRequest) (repository.CategoryRecord, []repository.CategoryRecord, error) {
|
||||
name, err := normalizeNodeName(req.GetName(), "name")
|
||||
if err != nil {
|
||||
return repository.CategoryRecord{}, err
|
||||
return repository.CategoryRecord{}, nil, err
|
||||
}
|
||||
imageIDs, err := normalizeNodeImageIDs(req.GetImageJson())
|
||||
if err != nil {
|
||||
return repository.CategoryRecord{}, err
|
||||
return repository.CategoryRecord{}, nil, err
|
||||
}
|
||||
statusValue, err := normalizeNodeStatus(req.Status)
|
||||
if err != nil {
|
||||
return repository.CategoryRecord{}, err
|
||||
return repository.CategoryRecord{}, nil, err
|
||||
}
|
||||
|
||||
return repository.CategoryRecord{
|
||||
parent := repository.CategoryRecord{
|
||||
NodeType: groupNodeType,
|
||||
Name: name,
|
||||
Level: 1,
|
||||
ImageIDs: imageIDs,
|
||||
SortNum: req.GetSortNum(),
|
||||
Status: statusValue,
|
||||
CampaignID: req.GetCampaignId(),
|
||||
}, nil
|
||||
}
|
||||
children, err := groupChildrenFromProto(req.GetChildren())
|
||||
if err != nil {
|
||||
return repository.CategoryRecord{}, nil, err
|
||||
}
|
||||
return parent, children, nil
|
||||
}
|
||||
|
||||
func groupChildrenFromProto(items []*productv1.CreateChildGroup) ([]repository.CategoryRecord, error) {
|
||||
if len(items) > 100 {
|
||||
return nil, errors.New("children must contain at most 100 items")
|
||||
}
|
||||
children := make([]repository.CategoryRecord, 0, len(items))
|
||||
names := make(map[string]struct{}, len(items))
|
||||
for _, item := range items {
|
||||
if item == nil {
|
||||
return nil, errors.New("children item is required")
|
||||
}
|
||||
name, err := normalizeNodeName(item.GetName(), "children.name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, exists := names[normalizedNodeNameKey(name)]; exists {
|
||||
return nil, errors.New("children.name must be unique")
|
||||
}
|
||||
names[normalizedNodeNameKey(name)] = struct{}{}
|
||||
imageIDs, err := normalizeNodeImageIDs(item.GetImageJson())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
statusValue, err := normalizeNodeStatus(item.Status)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
children = append(children, repository.CategoryRecord{NodeType: groupNodeType, Name: name, Level: 2, ImageIDs: imageIDs, SortNum: item.GetSortNum(), Status: statusValue})
|
||||
}
|
||||
return children, nil
|
||||
}
|
||||
|
||||
func groupFieldUpdateFromRequest(req *productv1.UpdateGroupRequest) (*repository.CategoryFieldUpdate, error) {
|
||||
@ -1891,22 +1978,11 @@ func groupFieldUpdateFromRequest(req *productv1.UpdateGroupRequest) (*repository
|
||||
return nil, errors.New("status must be 0 or 1")
|
||||
}
|
||||
update.Status = req.Status
|
||||
case "campaign_id":
|
||||
value := ""
|
||||
if req.CampaignId != nil {
|
||||
value = strings.TrimSpace(*req.CampaignId)
|
||||
}
|
||||
if value != "" {
|
||||
if _, err := normalizeCategoryID(value, "campaign_id"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
update.CampaignID = &value
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported update path %q", path)
|
||||
}
|
||||
}
|
||||
if update.Name == nil && update.ImageIDs == nil && update.SortNum == nil && update.Status == nil && update.CampaignID == nil {
|
||||
if update.Name == nil && update.ImageIDs == nil && update.SortNum == nil && update.Status == nil {
|
||||
return nil, errors.New("at least one mutable field is required")
|
||||
}
|
||||
return update, nil
|
||||
@ -1970,6 +2046,10 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P
|
||||
if err != nil {
|
||||
return repository.ProductRecord{}, nil, err
|
||||
}
|
||||
categoryPropertiesJSON, err := categoryPropertiesJSONFromProto(req.GetCategoryProperties())
|
||||
if err != nil {
|
||||
return repository.ProductRecord{}, nil, err
|
||||
}
|
||||
|
||||
record := repository.ProductRecord{
|
||||
SPUNo: spuNo,
|
||||
@ -1984,6 +2064,7 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P
|
||||
ServiceGuarantees: normalizeStringList(req.GetServiceGuarantees()),
|
||||
Status: statusValue,
|
||||
CrossBorderJSON: crossBorderJSON,
|
||||
CategoryPropertiesJSON: categoryPropertiesJSON,
|
||||
FreightChargeType: defaultInt32(req.GetFreightChargeType(), 1),
|
||||
FreightFixedAmount: req.GetFreightFixedAmount(),
|
||||
FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()),
|
||||
@ -2083,6 +2164,12 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro
|
||||
return repository.ProductRecord{}, err
|
||||
}
|
||||
merged.CrossBorderJSON = crossBorderJSON
|
||||
case "category_properties":
|
||||
categoryPropertiesJSON, err := categoryPropertiesJSONFromProto(update.GetCategoryProperties())
|
||||
if err != nil {
|
||||
return repository.ProductRecord{}, err
|
||||
}
|
||||
merged.CategoryPropertiesJSON = categoryPropertiesJSON
|
||||
case "freight_charge_type":
|
||||
merged.FreightChargeType = update.GetFreightChargeType()
|
||||
case "freight_fixed_amount":
|
||||
@ -2403,6 +2490,31 @@ func toProtoCrossBorderInfo(raw string) *productv1.CrossBorderInfo {
|
||||
return info
|
||||
}
|
||||
|
||||
func categoryPropertiesJSONFromProto(properties *structpb.Struct) (string, error) {
|
||||
if properties == nil {
|
||||
return "{}", nil
|
||||
}
|
||||
raw, err := json.Marshal(properties.AsMap())
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("marshal category_properties: %w", err)
|
||||
}
|
||||
return string(raw), nil
|
||||
}
|
||||
|
||||
func categoryPropertiesProto(raw string) *structpb.Struct {
|
||||
properties := make(map[string]any)
|
||||
if strings.TrimSpace(raw) != "" {
|
||||
if err := json.Unmarshal([]byte(raw), &properties); err != nil || properties == nil {
|
||||
return &structpb.Struct{Fields: map[string]*structpb.Value{}}
|
||||
}
|
||||
}
|
||||
result, err := structpb.NewStruct(properties)
|
||||
if err != nil {
|
||||
return &structpb.Struct{Fields: map[string]*structpb.Value{}}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func normalizeStringList(values []string) []string {
|
||||
if len(values) == 0 {
|
||||
return []string{}
|
||||
@ -2612,6 +2724,7 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
|
||||
ServiceGuarantees: product.ServiceGuarantees,
|
||||
CrossBorderJson: product.CrossBorderJSON,
|
||||
CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON),
|
||||
CategoryProperties: categoryPropertiesProto(product.CategoryPropertiesJSON),
|
||||
FreightChargeType: product.FreightChargeType,
|
||||
FreightFixedAmount: product.FreightFixedAmount,
|
||||
FreightTemplateId: product.FreightTemplateID,
|
||||
@ -2670,6 +2783,7 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv
|
||||
SoldQuantity: product.SoldQuantity,
|
||||
StockQuantity: product.StockQuantity,
|
||||
LockedQuantity: product.LockedQuantity,
|
||||
CategoryProperties: categoryPropertiesProto(product.CategoryPropertiesJSON),
|
||||
}
|
||||
}
|
||||
|
||||
@ -2766,7 +2880,6 @@ func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode {
|
||||
SortNum: group.SortNum,
|
||||
Status: group.Status,
|
||||
ProductCount: group.ProductCount,
|
||||
CampaignId: group.CampaignID,
|
||||
Version: group.Version,
|
||||
}
|
||||
}
|
||||
|
||||
@ -29,6 +29,7 @@ CREATE TABLE IF NOT EXISTS product.products (
|
||||
service_guarantees VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||
status SMALLINT NOT NULL DEFAULT 1,
|
||||
cross_border JSONB NOT NULL DEFAULT '{}'::JSONB,
|
||||
category_properties JSONB NOT NULL DEFAULT '{}'::JSONB,
|
||||
freight_charge_type SMALLINT NOT NULL DEFAULT 1,
|
||||
freight_fixed_amount BIGINT NOT NULL DEFAULT 0,
|
||||
freight_template_id BIGINT,
|
||||
@ -130,6 +131,7 @@ CREATE INDEX IF NOT EXISTS idx_catalog_category_campaign_id
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name
|
||||
ON product.catalog_category (
|
||||
store_id,
|
||||
COALESCE(parent_id, 0),
|
||||
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
|
||||
) WHERE node_type = 2;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_sibling_normalized_name
|
||||
|
||||
@ -0,0 +1,15 @@
|
||||
-- Adds category property storage and allows group names to repeat under
|
||||
-- different parents. Run this migration before deploying the application.
|
||||
|
||||
ALTER TABLE product.products
|
||||
ADD COLUMN IF NOT EXISTS category_properties JSONB NOT NULL DEFAULT '{}'::JSONB;
|
||||
|
||||
DROP INDEX IF EXISTS product.uq_product_category_group_normalized_name;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name
|
||||
ON product.catalog_category (
|
||||
store_id,
|
||||
COALESCE(parent_id, 0),
|
||||
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
|
||||
)
|
||||
WHERE node_type = 2;
|
||||
@ -52,6 +52,7 @@ CREATE TABLE IF NOT EXISTS product.products (
|
||||
service_guarantees VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||
status SMALLINT NOT NULL DEFAULT 1,
|
||||
cross_border JSONB NOT NULL DEFAULT '{}'::JSONB,
|
||||
category_properties JSONB NOT NULL DEFAULT '{}'::JSONB,
|
||||
freight_charge_type SMALLINT NOT NULL DEFAULT 1,
|
||||
freight_fixed_amount BIGINT NOT NULL DEFAULT 0,
|
||||
freight_template_id BIGINT,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user