feat: add category_properties field to products and implement group creation with child groups

This commit is contained in:
BXY 2026-10-10 18:27:19 +08:00
parent c2d0aa604f
commit 4e010a6476
6 changed files with 474 additions and 115 deletions

View File

@ -89,6 +89,7 @@ type ProductRecord struct {
Status productv1.ProductStatus Status productv1.ProductStatus
Attrs map[string]any Attrs map[string]any
CrossBorderJSON string CrossBorderJSON string
CategoryPropertiesJSON string
FreightChargeType int32 FreightChargeType int32
FreightFixedAmount int64 FreightFixedAmount int64
FreightTemplateID string FreightTemplateID string
@ -270,17 +271,18 @@ type ProductStatusUpdate struct {
// CategoryProductRecord is the product summary returned by product list endpoints. // CategoryProductRecord is the product summary returned by product list endpoints.
type CategoryProductRecord struct { type CategoryProductRecord struct {
ID string ID string
SPUNo string SPUNo string
Title string Title string
Status productv1.ProductStatus Status productv1.ProductStatus
ImageIDs []string ImageIDs []string
Price int64 Price int64
SoldQuantity int64 SoldQuantity int64
StockQuantity int64 StockQuantity int64
LockedQuantity int64 LockedQuantity int64
CreatedAt time.Time CategoryPropertiesJSON string
UpdatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time
} }
// ProductListFilter contains the optional constraints for an admin product list. // ProductListFilter contains the optional constraints for an admin product list.
@ -317,6 +319,14 @@ type CategoryRecord struct {
ProductCount int64 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. // CategoryFieldUpdate selects mutable fields of one category node.
type CategoryFieldUpdate struct { type CategoryFieldUpdate struct {
ID string 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; 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 tenant_id BIGINT;
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS store_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 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 store_id BIGINT;
ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS campaign_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_catalog_category_store_id ON product.catalog_category (store_id);
CREATE INDEX IF NOT EXISTS idx_product_category_campaign_id CREATE INDEX IF NOT EXISTS idx_product_category_campaign_id
ON product.catalog_category (campaign_id) WHERE campaign_id IS NOT NULL; 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 CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name
ON product.catalog_category ( ON product.catalog_category (
store_id, store_id,
COALESCE(parent_id, 0),
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g'))) lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
) )
WHERE node_type = 2; WHERE node_type = 2;
@ -615,6 +628,10 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe
if err != nil { if err != nil {
return err return err
} }
categoryProperties, err := productCategoryPropertiesJSON(product)
if err != nil {
return err
}
tx, err := r.db.BeginTx(ctx, nil) tx, err := r.db.BeginTx(ctx, nil)
if err != nil { if err != nil {
@ -622,7 +639,7 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe
} }
defer tx.Rollback() defer tx.Rollback()
if _, err := insertProduct(ctx, tx, product, attrs); err != nil { if _, err := insertProduct(ctx, tx, product, attrs, categoryProperties); err != nil {
return err return err
} }
if err := tx.Commit(); err != nil { if err := tx.Commit(); err != nil {
@ -640,6 +657,10 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
categoryProperties, err := productCategoryPropertiesJSON(product)
if err != nil {
return nil, nil, err
}
tx, err := r.db.BeginTx(ctx, nil) tx, err := r.db.BeginTx(ctx, nil)
if err != nil { if err != nil {
@ -647,7 +668,7 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P
} }
defer tx.Rollback() defer tx.Rollback()
createdProduct, err := insertProduct(ctx, tx, product, attrs) createdProduct, err := insertProduct(ctx, tx, product, attrs, categoryProperties)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@ -741,6 +762,82 @@ func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category Cat
return createdCategory, nil 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 // UpdateCategoryTrees applies all requested root and direct-child patches in a
// single transaction. Callers must supply already-validated patch fields. // single transaction. Callers must supply already-validated patch fields.
func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []CategoryTreeUpdate, scope StoreScope) error { 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 { if err != nil {
return nil, err return nil, err
} }
if target.NodeType != 2 { if target.NodeType != 2 || (target.Level != 1 && target.Level != 2) {
return nil, ErrInvalidProductGroup return nil, ErrInvalidProductGroup
} }
if target.Version != expectedVersion { if target.Version != expectedVersion {
@ -977,20 +1074,72 @@ func (r *ProductRepository) DeleteGroup(ctx context.Context, groupID string, exp
if err != nil { if err != nil {
return nil, err 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} result := &GroupDeleteResult{DeletedGroupID: target.ID}
if err := tx.QueryRowContext(ctx, ` if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
SELECT COUNT(DISTINCT product_id), COUNT(*) SELECT COUNT(DISTINCT product_id), COUNT(*)
FROM product.product_catalog_bindings FROM product.product_catalog_bindings
WHERE category_id = $1 WHERE category_id IN (%s)
`, targetID).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil { `, whereIDs), args...).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil {
return nil, fmt.Errorf("count group bindings for delete: %w", err) 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 DELETE FROM product.product_catalog_bindings
WHERE category_id = $1 WHERE category_id IN (%s)
`, targetID); err != nil { `, whereIDs), args...); err != nil {
return nil, fmt.Errorf("delete group bindings: %w", err) 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, ` if _, err := tx.ExecContext(ctx, `
DELETE FROM product.catalog_category DELETE FROM product.catalog_category
WHERE id = $1 AND store_id = $2 AND node_type = 2 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 { if err != nil {
return nil, err return nil, err
} }
categoryProperties, err := productCategoryPropertiesJSON(input.Product)
if err != nil {
return nil, err
}
brandID, err := nullableID(input.Product.BrandID, "brand_id") brandID, err := nullableID(input.Product.BrandID, "brand_id")
if err != nil { if err != nil {
return nil, err return nil, err
@ -1403,17 +1556,18 @@ SET title = $2,
goods_type = $9, goods_type = $9,
service_guarantees = $10, service_guarantees = $10,
cross_border = $11::jsonb, cross_border = $11::jsonb,
freight_charge_type = $12, category_properties = $12::jsonb,
freight_fixed_amount = $13, freight_charge_type = $13,
freight_template_id = $14, freight_fixed_amount = $14,
sale_time_type = $15, freight_template_id = $15,
scheduled_sale_time = $16, sale_time_type = $16,
scheduled_sale_time = $17,
version = version + 1, version = version + 1,
updated_at = NOW() 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, `, productID, input.Product.Title, input.Product.SellingPoint, brandID, supplierID,
stringSliceOrEmpty(input.Product.ImageIDs), input.Product.DetailHTML, input.Product.MemberDiscountEnabled, 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.FreightChargeType), input.Product.FreightFixedAmount, freightTemplateID,
int16(input.Product.SaleTimeType), input.Product.ScheduledSaleTime, input.ExpectedVersion, input.Scope.StoreID); err != nil { 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) return nil, fmt.Errorf("update product %s: %w", input.Product.ID, err)
@ -3014,6 +3168,7 @@ SELECT p.updated_at,
p.spu_no, p.spu_no,
p.status, p.status,
COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(to_json(p.image_ids)::text, '[]'),
COALESCE(p.category_properties, '{}'::jsonb)::text,
COALESCE(sku_summary.price, 0), COALESCE(sku_summary.price, 0),
COALESCE(sku_summary.sold_quantity, 0), COALESCE(sku_summary.sold_quantity, 0),
COALESCE(sku_summary.stock_quantity, 0), COALESCE(sku_summary.stock_quantity, 0),
@ -3165,6 +3320,7 @@ SELECT p.updated_at,
p.spu_no, p.spu_no,
p.status, p.status,
COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(to_json(p.image_ids)::text, '[]'),
COALESCE(p.category_properties, '{}'::jsonb)::text,
COALESCE(sku_summary.price, 0), COALESCE(sku_summary.price, 0),
COALESCE(sku_summary.sold_quantity, 0), COALESCE(sku_summary.sold_quantity, 0),
COALESCE(sku_summary.stock_quantity, 0), COALESCE(sku_summary.stock_quantity, 0),
@ -3349,6 +3505,7 @@ SELECT p.updated_at,
p.spu_no, p.spu_no,
p.status, p.status,
COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(to_json(p.image_ids)::text, '[]'),
COALESCE(p.category_properties, '{}'::jsonb)::text,
COALESCE(sku_summary.price, 0), COALESCE(sku_summary.price, 0),
COALESCE(sku_summary.sold_quantity, 0), COALESCE(sku_summary.sold_quantity, 0),
COALESCE(sku_summary.stock_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. // 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 { if err := requireWriteScope(scope); err != nil {
return nil, err 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, ` rows, err := r.db.QueryContext(ctx, `
SELECT c.id, SELECT c.id,
c.node_type, c.node_type,
@ -3524,16 +3687,27 @@ SELECT c.id,
c.version, c.version,
COUNT(p.id) AS product_count COUNT(p.id) AS product_count
FROM product.catalog_category AS c 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.product_catalog_bindings AS b ON b.category_id = c.id
LEFT JOIN product.products AS p ON p.id = b.product_id LEFT JOIN product.products AS p ON p.id = b.product_id
AND p.store_id = c.store_id AND p.store_id = c.store_id
AND p.deleted_at IS NULL AND p.deleted_at IS NULL
WHERE c.node_type = 2 WHERE c.node_type = 2
AND c.store_id = $2 AND c.store_id = $1
AND ($1 = false OR c.status = 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 GROUP BY c.id
ORDER BY c.sort_num ASC, c.id ASC ORDER BY c.sort_num ASC, c.id ASC
`, onlyVisible, scope.StoreID) `, scope.StoreID, filter.OnlyVisible, firstLevelName, secondLevelName, filter.ExactMatch)
if err != nil { if err != nil {
return nil, fmt.Errorf("query group nodes: %w", err) return nil, fmt.Errorf("query group nodes: %w", err)
} }
@ -3598,6 +3772,7 @@ SELECT id,
COALESCE(to_json(service_guarantees)::text, '[]'), COALESCE(to_json(service_guarantees)::text, '[]'),
status, status,
cross_border, cross_border,
category_properties,
freight_charge_type, freight_charge_type,
freight_fixed_amount, freight_fixed_amount,
freight_template_id, freight_template_id,
@ -3637,7 +3812,7 @@ ORDER BY created_at ASC
return products, nil 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 { if err := requireWriteScope(product.Scope); err != nil {
return nil, err return nil, err
} }
@ -3674,13 +3849,14 @@ INSERT INTO product.products (
service_guarantees, service_guarantees,
status, status,
cross_border, cross_border,
category_properties,
freight_charge_type, freight_charge_type,
freight_fixed_amount, freight_fixed_amount,
freight_template_id, freight_template_id,
sale_time_type, sale_time_type,
scheduled_sale_time 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, RETURNING id,
spu_no, spu_no,
title, title,
@ -3694,6 +3870,7 @@ RETURNING id,
COALESCE(to_json(service_guarantees)::text, '[]'), COALESCE(to_json(service_guarantees)::text, '[]'),
status, status,
cross_border, cross_border,
category_properties,
freight_charge_type, freight_charge_type,
freight_fixed_amount, freight_fixed_amount,
freight_template_id, freight_template_id,
@ -3705,7 +3882,7 @@ RETURNING id,
updated_at updated_at
`, id, product.Scope.TenantID, product.Scope.StoreID, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs), `, 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), 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) int16(product.SaleTimeType), product.ScheduledSaleTime)
createdProduct, err := scanProduct(row) createdProduct, err := scanProduct(row)
@ -4085,10 +4262,11 @@ type rowScanner interface {
func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) {
var ( var (
rec CategoryProductRecord rec CategoryProductRecord
id int64 id int64
status int16 status int16
imageIDsJSON string imageIDsJSON string
categoryPropertiesJSON string
) )
if err := scanner.Scan( if err := scanner.Scan(
&rec.UpdatedAt, &rec.UpdatedAt,
@ -4098,6 +4276,7 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) {
&rec.SPUNo, &rec.SPUNo,
&status, &status,
&imageIDsJSON, &imageIDsJSON,
&categoryPropertiesJSON,
&rec.Price, &rec.Price,
&rec.SoldQuantity, &rec.SoldQuantity,
&rec.StockQuantity, &rec.StockQuantity,
@ -4113,26 +4292,31 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) {
return nil, fmt.Errorf("unmarshal category product image_ids: %w", err) return nil, fmt.Errorf("unmarshal category product image_ids: %w", err)
} }
rec.ImageIDs = imageIDs rec.ImageIDs = imageIDs
rec.CategoryPropertiesJSON = categoryPropertiesJSON
if rec.CategoryPropertiesJSON == "" {
rec.CategoryPropertiesJSON = "{}"
}
return &rec, nil return &rec, nil
} }
func scanProduct(scanner rowScanner) (*ProductRecord, error) { func scanProduct(scanner rowScanner) (*ProductRecord, error) {
var ( var (
rec ProductRecord rec ProductRecord
id int64 id int64
brandID sql.NullInt64 brandID sql.NullInt64
supplierID sql.NullInt64 supplierID sql.NullInt64
imageIDsJSON string imageIDsJSON string
serviceGuaranteesJSON string serviceGuaranteesJSON string
goodsType int16 goodsType int16
status int16 status int16
attrsJSON []byte attrsJSON []byte
freightChargeType int16 categoryPropertiesJSON []byte
freightTemplateID sql.NullInt64 freightChargeType int16
saleTimeType int16 freightTemplateID sql.NullInt64
scheduledSaleTime sql.NullTime saleTimeType int16
version int32 scheduledSaleTime sql.NullTime
deletedAt sql.NullTime version int32
deletedAt sql.NullTime
) )
if err := scanner.Scan( if err := scanner.Scan(
&id, &id,
@ -4148,6 +4332,7 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) {
&serviceGuaranteesJSON, &serviceGuaranteesJSON,
&status, &status,
&attrsJSON, &attrsJSON,
&categoryPropertiesJSON,
&freightChargeType, &freightChargeType,
&rec.FreightFixedAmount, &rec.FreightFixedAmount,
&freightTemplateID, &freightTemplateID,
@ -4185,6 +4370,10 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) {
if rec.CrossBorderJSON == "" { if rec.CrossBorderJSON == "" {
rec.CrossBorderJSON = "{}" rec.CrossBorderJSON = "{}"
} }
rec.CategoryPropertiesJSON = string(categoryPropertiesJSON)
if rec.CategoryPropertiesJSON == "" {
rec.CategoryPropertiesJSON = "{}"
}
if len(attrsJSON) > 0 { if len(attrsJSON) > 0 {
if err := json.Unmarshal(attrsJSON, &rec.Attrs); err != nil { if err := json.Unmarshal(attrsJSON, &rec.Attrs); err != nil {
return nil, fmt.Errorf("unmarshal product attrs: %w", err) return nil, fmt.Errorf("unmarshal product attrs: %w", err)
@ -4439,6 +4628,22 @@ func productCrossBorderJSON(product ProductRecord) ([]byte, error) {
return attrs, nil 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 { func applySKUAttributes(rec *SKURecord) error {
if rec == nil { if rec == nil {
return nil return nil

View File

@ -1,6 +1,10 @@
package server package server
import "testing" import (
"testing"
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
)
func TestNormalizeNodeNameCollapsesUnicodeWhitespace(t *testing.T) { func TestNormalizeNodeNameCollapsesUnicodeWhitespace(t *testing.T) {
name, err := normalizeNodeName("  Summer\t\n Sale ", "name") 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") 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")
}
}

View File

@ -20,6 +20,7 @@ import (
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/fieldmaskpb" "google.golang.org/protobuf/types/known/fieldmaskpb"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/timestamppb"
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" 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 }, 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) { func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGroupRequest) (*productv1.CreateGroupResponse, error) {
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") 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") return nil, status.Error(codes.Internal, "id generator is not configured")
} }
group, err := groupFromCreateRequest(req) group, children, err := groupTreeFromCreateRequest(req)
if err != nil { if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error()) return nil, status.Error(codes.InvalidArgument, err.Error())
} }
group.ID = s.idgen.NextString() 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( dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_group", trace.WithAttributes(
attribute.String("group.name", group.Name), attribute.String("group.name", group.Name),
attribute.Int("group.child_count", len(children)),
)) ))
defer dbSpan.End() defer dbSpan.End()
createdGroup, err := s.repo.CreateCategoryNode(dbCtx, group, scope) createdGroup, createdChildren, err := s.repo.CreateCategoryTree(dbCtx, group, children, scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) 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 nil, status.Errorf(codes.Internal, "create group: %v", err)
} }
return &productv1.CreateGroupResponse{ protoGroup := toProtoGroupNode(createdGroup)
Group: toProtoGroupNode(createdGroup), for _, child := range createdChildren {
}, nil 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. // 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 return nil, err
} }
onlyVisible := false onlyVisible := false
filter := repository.GroupListFilter{}
if req != nil { if req != nil {
onlyVisible = req.GetOnlyVisible() 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( dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_groups", trace.WithAttributes(
attribute.Bool("group.only_visible", onlyVisible), attribute.Bool("group.only_visible", onlyVisible),
)) ))
defer dbSpan.End() defer dbSpan.End()
groups, err := s.repo.ListGroupNodes(dbCtx, onlyVisible, scope) groups, err := s.repo.ListGroupNodes(dbCtx, filter, scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -1815,29 +1868,63 @@ func normalizeCategoryID(value, field string) (string, error) {
return trimmed, nil 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") name, err := normalizeNodeName(req.GetName(), "name")
if err != nil { if err != nil {
return repository.CategoryRecord{}, err return repository.CategoryRecord{}, nil, err
} }
imageIDs, err := normalizeNodeImageIDs(req.GetImageJson()) imageIDs, err := normalizeNodeImageIDs(req.GetImageJson())
if err != nil { if err != nil {
return repository.CategoryRecord{}, err return repository.CategoryRecord{}, nil, err
} }
statusValue, err := normalizeNodeStatus(req.Status) statusValue, err := normalizeNodeStatus(req.Status)
if err != nil { if err != nil {
return repository.CategoryRecord{}, err return repository.CategoryRecord{}, nil, err
} }
parent := repository.CategoryRecord{
NodeType: groupNodeType,
Name: name,
Level: 1,
ImageIDs: imageIDs,
SortNum: req.GetSortNum(),
Status: statusValue,
}
children, err := groupChildrenFromProto(req.GetChildren())
if err != nil {
return repository.CategoryRecord{}, nil, err
}
return parent, children, nil
}
return repository.CategoryRecord{ func groupChildrenFromProto(items []*productv1.CreateChildGroup) ([]repository.CategoryRecord, error) {
NodeType: groupNodeType, if len(items) > 100 {
Name: name, return nil, errors.New("children must contain at most 100 items")
Level: 1, }
ImageIDs: imageIDs, children := make([]repository.CategoryRecord, 0, len(items))
SortNum: req.GetSortNum(), names := make(map[string]struct{}, len(items))
Status: statusValue, for _, item := range items {
CampaignID: req.GetCampaignId(), if item == nil {
}, 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) { 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") return nil, errors.New("status must be 0 or 1")
} }
update.Status = req.Status 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: default:
return nil, fmt.Errorf("unsupported update path %q", path) 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 nil, errors.New("at least one mutable field is required")
} }
return update, nil return update, nil
@ -1970,25 +2046,30 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P
if err != nil { if err != nil {
return repository.ProductRecord{}, nil, err return repository.ProductRecord{}, nil, err
} }
categoryPropertiesJSON, err := categoryPropertiesJSONFromProto(req.GetCategoryProperties())
if err != nil {
return repository.ProductRecord{}, nil, err
}
record := repository.ProductRecord{ record := repository.ProductRecord{
SPUNo: spuNo, SPUNo: spuNo,
Title: title, Title: title,
SellingPoint: strings.TrimSpace(req.GetSellingPoint()), SellingPoint: strings.TrimSpace(req.GetSellingPoint()),
BrandID: strings.TrimSpace(req.GetBrandId()), BrandID: strings.TrimSpace(req.GetBrandId()),
SupplierID: strings.TrimSpace(req.GetSupplierId()), SupplierID: strings.TrimSpace(req.GetSupplierId()),
ImageIDs: normalizeStringList(req.GetImageIds()), ImageIDs: normalizeStringList(req.GetImageIds()),
DetailHTML: "", DetailHTML: "",
MemberDiscountEnabled: req.GetMemberDiscountEnabled(), MemberDiscountEnabled: req.GetMemberDiscountEnabled(),
GoodsType: defaultInt32(req.GetGoodsType(), 1), GoodsType: defaultInt32(req.GetGoodsType(), 1),
ServiceGuarantees: normalizeStringList(req.GetServiceGuarantees()), ServiceGuarantees: normalizeStringList(req.GetServiceGuarantees()),
Status: statusValue, Status: statusValue,
CrossBorderJSON: crossBorderJSON, CrossBorderJSON: crossBorderJSON,
FreightChargeType: defaultInt32(req.GetFreightChargeType(), 1), CategoryPropertiesJSON: categoryPropertiesJSON,
FreightFixedAmount: req.GetFreightFixedAmount(), FreightChargeType: defaultInt32(req.GetFreightChargeType(), 1),
FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()), FreightFixedAmount: req.GetFreightFixedAmount(),
SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1), FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()),
ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()), SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1),
ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()),
} }
detailHTML, err := sanitizeDetailHTML(req.GetDetailHtml()) detailHTML, err := sanitizeDetailHTML(req.GetDetailHtml())
if err != nil { if err != nil {
@ -2083,6 +2164,12 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro
return repository.ProductRecord{}, err return repository.ProductRecord{}, err
} }
merged.CrossBorderJSON = crossBorderJSON 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": case "freight_charge_type":
merged.FreightChargeType = update.GetFreightChargeType() merged.FreightChargeType = update.GetFreightChargeType()
case "freight_fixed_amount": case "freight_fixed_amount":
@ -2403,6 +2490,31 @@ func toProtoCrossBorderInfo(raw string) *productv1.CrossBorderInfo {
return info 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 { func normalizeStringList(values []string) []string {
if len(values) == 0 { if len(values) == 0 {
return []string{} return []string{}
@ -2612,6 +2724,7 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
ServiceGuarantees: product.ServiceGuarantees, ServiceGuarantees: product.ServiceGuarantees,
CrossBorderJson: product.CrossBorderJSON, CrossBorderJson: product.CrossBorderJSON,
CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON), CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON),
CategoryProperties: categoryPropertiesProto(product.CategoryPropertiesJSON),
FreightChargeType: product.FreightChargeType, FreightChargeType: product.FreightChargeType,
FreightFixedAmount: product.FreightFixedAmount, FreightFixedAmount: product.FreightFixedAmount,
FreightTemplateId: product.FreightTemplateID, FreightTemplateId: product.FreightTemplateID,
@ -2659,17 +2772,18 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv
return nil return nil
} }
return &productv1.CategoryProduct{ return &productv1.CategoryProduct{
UpdatedAt: timeToMillisString(product.UpdatedAt), UpdatedAt: timeToMillisString(product.UpdatedAt),
CreatedAt: timeToMillisString(product.CreatedAt), CreatedAt: timeToMillisString(product.CreatedAt),
Title: product.Title, Title: product.Title,
ProductId: product.ID, ProductId: product.ID,
SpuNo: product.SPUNo, SpuNo: product.SPUNo,
Status: product.Status, Status: product.Status,
ImageIds: product.ImageIDs, ImageIds: product.ImageIDs,
Price: product.Price, Price: product.Price,
SoldQuantity: product.SoldQuantity, SoldQuantity: product.SoldQuantity,
StockQuantity: product.StockQuantity, StockQuantity: product.StockQuantity,
LockedQuantity: product.LockedQuantity, LockedQuantity: product.LockedQuantity,
CategoryProperties: categoryPropertiesProto(product.CategoryPropertiesJSON),
} }
} }
@ -2766,7 +2880,6 @@ func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode {
SortNum: group.SortNum, SortNum: group.SortNum,
Status: group.Status, Status: group.Status,
ProductCount: group.ProductCount, ProductCount: group.ProductCount,
CampaignId: group.CampaignID,
Version: group.Version, Version: group.Version,
} }
} }

View File

@ -29,6 +29,7 @@ CREATE TABLE IF NOT EXISTS product.products (
service_guarantees VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], service_guarantees VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
status SMALLINT NOT NULL DEFAULT 1, status SMALLINT NOT NULL DEFAULT 1,
cross_border JSONB NOT NULL DEFAULT '{}'::JSONB, cross_border JSONB NOT NULL DEFAULT '{}'::JSONB,
category_properties JSONB NOT NULL DEFAULT '{}'::JSONB,
freight_charge_type SMALLINT NOT NULL DEFAULT 1, freight_charge_type SMALLINT NOT NULL DEFAULT 1,
freight_fixed_amount BIGINT NOT NULL DEFAULT 0, freight_fixed_amount BIGINT NOT NULL DEFAULT 0,
freight_template_id BIGINT, 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 CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name
ON product.catalog_category ( ON product.catalog_category (
store_id, store_id,
COALESCE(parent_id, 0),
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g'))) lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
) WHERE node_type = 2; ) WHERE node_type = 2;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_sibling_normalized_name CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_sibling_normalized_name

View File

@ -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;

View File

@ -52,6 +52,7 @@ CREATE TABLE IF NOT EXISTS product.products (
service_guarantees VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], service_guarantees VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
status SMALLINT NOT NULL DEFAULT 1, status SMALLINT NOT NULL DEFAULT 1,
cross_border JSONB NOT NULL DEFAULT '{}'::JSONB, cross_border JSONB NOT NULL DEFAULT '{}'::JSONB,
category_properties JSONB NOT NULL DEFAULT '{}'::JSONB,
freight_charge_type SMALLINT NOT NULL DEFAULT 1, freight_charge_type SMALLINT NOT NULL DEFAULT 1,
freight_fixed_amount BIGINT NOT NULL DEFAULT 0, freight_fixed_amount BIGINT NOT NULL DEFAULT 0,
freight_template_id BIGINT, freight_template_id BIGINT,