mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
feat: add storefront category visibility check and related error handling
This commit is contained in:
parent
a67703d55c
commit
91f307ce19
@ -21,6 +21,11 @@ var ErrProductNotFound = errors.New("product not found")
|
|||||||
|
|
||||||
// ErrCategoryNodeNotFound is returned when a category or product group node does not exist.
|
// ErrCategoryNodeNotFound is returned when a category or product group node does not exist.
|
||||||
var ErrCategoryNodeNotFound = errors.New("category or group node not found")
|
var ErrCategoryNodeNotFound = errors.New("category or group node not found")
|
||||||
|
|
||||||
|
// ErrStorefrontCategoryNotFound deliberately also covers a hidden category or
|
||||||
|
// a category below a hidden/missing ancestor. Storefront callers must not be
|
||||||
|
// able to distinguish those states from a category that does not exist.
|
||||||
|
var ErrStorefrontCategoryNotFound = errors.New("storefront category 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 ErrCategoryNameExists = errors.New("category name already exists")
|
var ErrCategoryNameExists = errors.New("category name already exists")
|
||||||
@ -2760,6 +2765,14 @@ FROM product.products p
|
|||||||
WHERE p.deleted_at IS NULL
|
WHERE p.deleted_at IS NULL
|
||||||
AND p.store_id = $4
|
AND p.store_id = $4
|
||||||
AND p.status IN ($2, $3)
|
AND p.status IN ($2, $3)
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM product.product_items pi
|
||||||
|
WHERE pi.product_id = p.id
|
||||||
|
AND pi.deleted_at IS NULL
|
||||||
|
AND pi.is_archived = FALSE
|
||||||
|
AND pi.status = 1
|
||||||
|
)
|
||||||
AND p.title ILIKE $1 ESCAPE '\'
|
AND p.title ILIKE $1 ESCAPE '\'
|
||||||
`, containsPattern, onSaleStatus, offSaleStatus, scope.StoreID).Scan(&total); err != nil {
|
`, containsPattern, onSaleStatus, offSaleStatus, scope.StoreID).Scan(&total); err != nil {
|
||||||
return nil, 0, fmt.Errorf("count searched products: %w", err)
|
return nil, 0, fmt.Errorf("count searched products: %w", err)
|
||||||
@ -2792,10 +2805,19 @@ LEFT JOIN LATERAL (
|
|||||||
WHERE pi.product_id = p.id
|
WHERE pi.product_id = p.id
|
||||||
AND pi.deleted_at IS NULL
|
AND pi.deleted_at IS NULL
|
||||||
AND pi.is_archived = FALSE
|
AND pi.is_archived = FALSE
|
||||||
|
AND pi.status = 1
|
||||||
) sku_summary ON TRUE
|
) sku_summary ON TRUE
|
||||||
WHERE p.deleted_at IS NULL
|
WHERE p.deleted_at IS NULL
|
||||||
AND p.store_id = $8
|
AND p.store_id = $8
|
||||||
AND p.status IN ($2, $3)
|
AND p.status IN ($2, $3)
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM product.product_items pi
|
||||||
|
WHERE pi.product_id = p.id
|
||||||
|
AND pi.deleted_at IS NULL
|
||||||
|
AND pi.is_archived = FALSE
|
||||||
|
AND pi.status = 1
|
||||||
|
)
|
||||||
AND p.title ILIKE $1 ESCAPE '\'
|
AND p.title ILIKE $1 ESCAPE '\'
|
||||||
ORDER BY CASE
|
ORDER BY CASE
|
||||||
WHEN LOWER(p.title) = LOWER($4) THEN 0
|
WHEN LOWER(p.title) = LOWER($4) THEN 0
|
||||||
@ -2869,6 +2891,15 @@ func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID
|
|||||||
if pageSize < 1 {
|
if pageSize < 1 {
|
||||||
pageSize = 20
|
pageSize = 20
|
||||||
}
|
}
|
||||||
|
if onlyVisible && targetNodeType == 1 {
|
||||||
|
visible, err := r.isStorefrontCategoryVisible(ctx, parsedCategoryID, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, 0, err
|
||||||
|
}
|
||||||
|
if !visible {
|
||||||
|
return nil, nil, 0, ErrStorefrontCategoryNotFound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var total int64
|
var total int64
|
||||||
if err := r.db.QueryRowContext(ctx, `
|
if err := r.db.QueryRowContext(ctx, `
|
||||||
@ -2882,6 +2913,14 @@ WHERE b.category_id = $1
|
|||||||
AND c.store_id = $5
|
AND c.store_id = $5
|
||||||
AND c.node_type = $6
|
AND c.node_type = $6
|
||||||
AND ($2 = FALSE OR p.status IN ($3, $4))
|
AND ($2 = FALSE OR p.status IN ($3, $4))
|
||||||
|
AND ($2 = FALSE OR EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM product.product_items pi
|
||||||
|
WHERE pi.product_id = p.id
|
||||||
|
AND pi.deleted_at IS NULL
|
||||||
|
AND pi.is_archived = FALSE
|
||||||
|
AND pi.status = 1
|
||||||
|
))
|
||||||
`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID, targetNodeType).Scan(&total); err != nil {
|
`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID, targetNodeType).Scan(&total); err != nil {
|
||||||
return nil, nil, 0, fmt.Errorf("count category products: %w", err)
|
return nil, nil, 0, fmt.Errorf("count category products: %w", err)
|
||||||
}
|
}
|
||||||
@ -2900,6 +2939,14 @@ WHERE b.category_id = $1
|
|||||||
AND c.store_id = $5
|
AND c.store_id = $5
|
||||||
AND c.node_type = $6
|
AND c.node_type = $6
|
||||||
AND ($2 = FALSE OR p.status IN ($3, $4))
|
AND ($2 = FALSE OR p.status IN ($3, $4))
|
||||||
|
AND ($2 = FALSE OR EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM product.product_items pi
|
||||||
|
WHERE pi.product_id = p.id
|
||||||
|
AND pi.deleted_at IS NULL
|
||||||
|
AND pi.is_archived = FALSE
|
||||||
|
AND pi.status = 1
|
||||||
|
))
|
||||||
ORDER BY p.created_at DESC, p.id DESC
|
ORDER BY p.created_at DESC, p.id DESC
|
||||||
`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID, targetNodeType)
|
`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID, targetNodeType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -2944,6 +2991,7 @@ LEFT JOIN LATERAL (
|
|||||||
WHERE pi.product_id = p.id
|
WHERE pi.product_id = p.id
|
||||||
AND pi.deleted_at IS NULL
|
AND pi.deleted_at IS NULL
|
||||||
AND pi.is_archived = FALSE
|
AND pi.is_archived = FALSE
|
||||||
|
AND ($2 = FALSE OR pi.status = 1)
|
||||||
) sku_summary ON TRUE
|
) sku_summary ON TRUE
|
||||||
WHERE b.category_id = $1
|
WHERE b.category_id = $1
|
||||||
AND p.deleted_at IS NULL
|
AND p.deleted_at IS NULL
|
||||||
@ -2951,6 +2999,14 @@ WHERE b.category_id = $1
|
|||||||
AND c.store_id = $7
|
AND c.store_id = $7
|
||||||
AND c.node_type = $8
|
AND c.node_type = $8
|
||||||
AND ($2 = FALSE OR p.status IN ($5, $6))
|
AND ($2 = FALSE OR p.status IN ($5, $6))
|
||||||
|
AND ($2 = FALSE OR EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM product.product_items pi
|
||||||
|
WHERE pi.product_id = p.id
|
||||||
|
AND pi.deleted_at IS NULL
|
||||||
|
AND pi.is_archived = FALSE
|
||||||
|
AND pi.status = 1
|
||||||
|
))
|
||||||
ORDER BY p.created_at DESC, p.id DESC
|
ORDER BY p.created_at DESC, p.id DESC
|
||||||
LIMIT $3 OFFSET $4
|
LIMIT $3 OFFSET $4
|
||||||
`, parsedCategoryID, onlyVisible, pageSize, offset, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID, targetNodeType)
|
`, parsedCategoryID, onlyVisible, pageSize, offset, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID, targetNodeType)
|
||||||
@ -2973,6 +3029,50 @@ LIMIT $3 OFFSET $4
|
|||||||
return products, productIDs, total, nil
|
return products, productIDs, total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// isStorefrontCategoryVisible verifies the requested category and every
|
||||||
|
// ancestor in one store. A broken parent link or cycle is not storefront
|
||||||
|
// visible: exposing it would either leak a hidden branch or promote a child to
|
||||||
|
// a false root in the miniapp category tree.
|
||||||
|
func (r *ProductRepository) isStorefrontCategoryVisible(ctx context.Context, categoryID int64, scope StoreScope) (bool, error) {
|
||||||
|
var visible bool
|
||||||
|
err := r.db.QueryRowContext(ctx, `
|
||||||
|
WITH RECURSIVE ancestry AS (
|
||||||
|
SELECT id, parent_id, status, ARRAY[id] AS path
|
||||||
|
FROM product.catalog_category
|
||||||
|
WHERE id = $1
|
||||||
|
AND store_id = $2
|
||||||
|
AND node_type = 1
|
||||||
|
|
||||||
|
UNION ALL
|
||||||
|
|
||||||
|
SELECT parent.id, parent.parent_id, parent.status, ancestry.path || parent.id
|
||||||
|
FROM product.catalog_category parent
|
||||||
|
JOIN ancestry ON ancestry.parent_id = parent.id
|
||||||
|
WHERE parent.store_id = $2
|
||||||
|
AND parent.node_type = 1
|
||||||
|
AND NOT parent.id = ANY(ancestry.path)
|
||||||
|
)
|
||||||
|
SELECT EXISTS (SELECT 1 FROM ancestry WHERE parent_id IS NULL)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM ancestry WHERE status <> 1)
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM ancestry child
|
||||||
|
WHERE child.parent_id IS NOT NULL
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM product.catalog_category parent
|
||||||
|
WHERE parent.id = child.parent_id
|
||||||
|
AND parent.store_id = $2
|
||||||
|
AND parent.node_type = 1
|
||||||
|
)
|
||||||
|
)
|
||||||
|
`, categoryID, scope.StoreID).Scan(&visible)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("check storefront category visibility: %w", err)
|
||||||
|
}
|
||||||
|
return visible, nil
|
||||||
|
}
|
||||||
|
|
||||||
// ListCategoryTreeNodes loads product category nodes for storefront category trees.
|
// ListCategoryTreeNodes loads product category nodes for storefront category trees.
|
||||||
func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool, scope StoreScope) ([]*CategoryRecord, error) {
|
func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool, scope StoreScope) ([]*CategoryRecord, error) {
|
||||||
if err := requireWriteScope(scope); err != nil {
|
if err := requireWriteScope(scope); err != nil {
|
||||||
@ -2989,10 +3089,26 @@ SELECT id,
|
|||||||
status,
|
status,
|
||||||
campaign_id,
|
campaign_id,
|
||||||
version
|
version
|
||||||
FROM product.catalog_category
|
FROM (
|
||||||
WHERE node_type = 1
|
WITH RECURSIVE category_tree AS (
|
||||||
|
SELECT id, node_type, name, parent_id, level, image_ids, sort_num, status, campaign_id, version
|
||||||
|
FROM product.catalog_category
|
||||||
|
WHERE node_type = 1
|
||||||
AND store_id = $2
|
AND store_id = $2
|
||||||
AND ($1 = false OR status = 1)
|
AND parent_id IS NULL
|
||||||
|
AND ($1 = FALSE OR status = 1)
|
||||||
|
|
||||||
|
UNION ALL
|
||||||
|
|
||||||
|
SELECT child.id, child.node_type, child.name, child.parent_id, child.level, child.image_ids, child.sort_num, child.status, child.campaign_id, child.version
|
||||||
|
FROM product.catalog_category child
|
||||||
|
JOIN category_tree parent ON child.parent_id = parent.id
|
||||||
|
WHERE child.node_type = 1
|
||||||
|
AND child.store_id = $2
|
||||||
|
AND ($1 = FALSE OR child.status = 1)
|
||||||
|
)
|
||||||
|
SELECT * FROM category_tree
|
||||||
|
) category_tree
|
||||||
ORDER BY level ASC, sort_num ASC, id ASC
|
ORDER BY level ASC, sort_num ASC, id ASC
|
||||||
`, onlyVisible, scope.StoreID)
|
`, onlyVisible, scope.StoreID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@ -855,6 +855,9 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
dbSpan.RecordError(err)
|
dbSpan.RecordError(err)
|
||||||
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||||
|
if errors.Is(err, repository.ErrStorefrontCategoryNotFound) {
|
||||||
|
return nil, status.Error(codes.NotFound, "catalog category not found")
|
||||||
|
}
|
||||||
s.observer.Logger(ctx).Error("list category products failed", zap.String("category_id", req.GetCategoryId()), zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err))
|
s.observer.Logger(ctx).Error("list category products failed", zap.String("category_id", req.GetCategoryId()), zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err))
|
||||||
return nil, status.Errorf(codes.Internal, "list category products: %v", err)
|
return nil, status.Errorf(codes.Internal, "list category products: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
377
scripts/sql/02-product-schema.sql
Normal file
377
scripts/sql/02-product-schema.sql
Normal file
@ -0,0 +1,377 @@
|
|||||||
|
-- Product service complete schema.
|
||||||
|
-- Source of truth: the current ids-svc-product repository schema and its SQL migrations.
|
||||||
|
-- This script initializes an empty PostgreSQL database; it does not migrate legacy tables.
|
||||||
|
|
||||||
|
CREATE EXTENSION IF NOT EXISTS "pg_trgm";
|
||||||
|
|
||||||
|
CREATE SCHEMA IF NOT EXISTS product;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION public.set_updated_at()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
NEW.updated_at = NOW();
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- Product catalog tables.
|
||||||
|
CREATE TABLE IF NOT EXISTS product.products (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
spu_no VARCHAR(100) NOT NULL,
|
||||||
|
title VARCHAR(200) NOT NULL,
|
||||||
|
selling_point VARCHAR(300),
|
||||||
|
brand_id BIGINT,
|
||||||
|
supplier_id BIGINT,
|
||||||
|
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||||
|
detail_html TEXT,
|
||||||
|
member_discount_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
goods_type SMALLINT NOT NULL DEFAULT 1,
|
||||||
|
service_guarantees VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1,
|
||||||
|
cross_border 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,
|
||||||
|
sale_time_type SMALLINT NOT NULL DEFAULT 1,
|
||||||
|
scheduled_sale_time TIMESTAMPTZ,
|
||||||
|
version INTEGER NOT NULL DEFAULT 0,
|
||||||
|
tenant_id BIGINT,
|
||||||
|
store_id BIGINT,
|
||||||
|
deleted_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CONSTRAINT chk_products_goods_type
|
||||||
|
CHECK (goods_type IN (1, 2, 3, 4)),
|
||||||
|
CONSTRAINT chk_products_status
|
||||||
|
CHECK (status IN (1, 2, 3)),
|
||||||
|
CONSTRAINT chk_products_freight_charge_type
|
||||||
|
CHECK (freight_charge_type IN (1, 2)),
|
||||||
|
CONSTRAINT chk_products_freight_fixed_amount
|
||||||
|
CHECK (freight_fixed_amount >= 0),
|
||||||
|
CONSTRAINT chk_products_freight_template_required
|
||||||
|
CHECK (freight_charge_type <> 2 OR freight_template_id IS NOT NULL),
|
||||||
|
CONSTRAINT chk_products_sale_time_type
|
||||||
|
CHECK (sale_time_type IN (1, 2)),
|
||||||
|
CONSTRAINT chk_products_scheduled_sale_time_required
|
||||||
|
CHECK (sale_time_type <> 2 OR scheduled_sale_time IS NOT NULL),
|
||||||
|
CONSTRAINT chk_products_version
|
||||||
|
CHECK (version >= 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.products IS '商品 SPU 主表:存储商品公共信息、品牌、供应商、图片、商品类型、运费、开售配置和软删除状态';
|
||||||
|
COMMENT ON COLUMN product.products.brand_id IS '品牌 ID,对应 product.brands.id;由应用层校验所属店铺及可用状态';
|
||||||
|
COMMENT ON COLUMN product.products.supplier_id IS '供应商 ID,对应 product.suppliers.id;由应用层校验所属店铺及可用状态';
|
||||||
|
COMMENT ON COLUMN product.products.service_guarantees IS '服务保障展示快照;服务保障主数据变更时需通过业务流程刷新';
|
||||||
|
COMMENT ON COLUMN product.products.detail_html IS '商品详情 HTML;写入或渲染前必须做 HTML Sanitization,列表接口不得读取该字段';
|
||||||
|
COMMENT ON COLUMN product.products.version IS '乐观锁版本号,用于后台并发编辑冲突检测';
|
||||||
|
COMMENT ON COLUMN product.products.deleted_at IS '软删除时间;NULL 表示未删除,商品禁止物理删除以保护订单和财务引用';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_products_title_trgm
|
||||||
|
ON product.products USING GIN (title gin_trgm_ops);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_products_brand_status
|
||||||
|
ON product.products (brand_id, status);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_products_status_goods_type
|
||||||
|
ON product.products (status, goods_type) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_products_supplier_id
|
||||||
|
ON product.products (supplier_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_products_goods_type
|
||||||
|
ON product.products (goods_type);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_products_deleted_at
|
||||||
|
ON product.products (deleted_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_products_store_id
|
||||||
|
ON product.products (store_id) 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;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_products_store_active_created_id
|
||||||
|
ON product.products (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_products_store_spu_no
|
||||||
|
ON product.products (store_id, spu_no) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
-- Storefront catalog classification and product group tables.
|
||||||
|
CREATE TABLE IF NOT EXISTS product.catalog_category (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
node_type SMALLINT NOT NULL DEFAULT 1,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
parent_id BIGINT REFERENCES product.catalog_category(id),
|
||||||
|
level SMALLINT NOT NULL,
|
||||||
|
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||||
|
sort_num INTEGER NOT NULL DEFAULT 0,
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1,
|
||||||
|
version INTEGER NOT NULL DEFAULT 0,
|
||||||
|
tenant_id BIGINT,
|
||||||
|
store_id BIGINT,
|
||||||
|
campaign_id BIGINT,
|
||||||
|
CONSTRAINT chk_catalog_category_node_type
|
||||||
|
CHECK (node_type IN (1, 2)),
|
||||||
|
CONSTRAINT chk_catalog_category_level
|
||||||
|
CHECK (level > 0),
|
||||||
|
CONSTRAINT chk_catalog_category_status
|
||||||
|
CHECK (status IN (0, 1)),
|
||||||
|
CONSTRAINT chk_catalog_category_version
|
||||||
|
CHECK (version >= 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.catalog_category IS '商品目录分类及商品分组表,通过 node_type 区分分类或分组';
|
||||||
|
COMMENT ON COLUMN product.catalog_category.node_type IS '节点类型:1 分类,2 分组';
|
||||||
|
COMMENT ON COLUMN product.catalog_category.parent_id IS '上级节点 ID;顶级节点为空,分组通常为顶级节点';
|
||||||
|
COMMENT ON COLUMN product.catalog_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示';
|
||||||
|
COMMENT ON COLUMN product.catalog_category.campaign_id IS '活动 ID;仅用于关联活动展示的分类或分组';
|
||||||
|
COMMENT ON COLUMN product.catalog_category.version IS '乐观锁版本号,更新时递增';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_parent_id
|
||||||
|
ON product.catalog_category (parent_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_node_status_sort
|
||||||
|
ON product.catalog_category (node_type, status, sort_num);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_id
|
||||||
|
ON product.catalog_category (store_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_campaign_id
|
||||||
|
ON product.catalog_category (campaign_id) WHERE campaign_id IS NOT NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name
|
||||||
|
ON product.catalog_category (
|
||||||
|
store_id,
|
||||||
|
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
|
||||||
|
) WHERE node_type = 2;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_sibling_normalized_name
|
||||||
|
ON product.catalog_category (
|
||||||
|
store_id,
|
||||||
|
COALESCE(parent_id, 0),
|
||||||
|
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
|
||||||
|
) WHERE node_type = 1;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS product.product_catalog_bindings (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
|
||||||
|
category_id BIGINT NOT NULL REFERENCES product.catalog_category(id) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT uq_product_catalog_bindings_product_category UNIQUE (product_id, category_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.product_catalog_bindings IS '商品目录分类/分组绑定表:存储 SPU 与目录分类或分组节点的多对多关系';
|
||||||
|
COMMENT ON COLUMN product.product_catalog_bindings.product_id IS '商品 SPU ID,对应 product.products.id';
|
||||||
|
COMMENT ON COLUMN product.product_catalog_bindings.category_id IS '目录分类或分组节点 ID,对应 product.catalog_category.id';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_catalog_bindings_category_id
|
||||||
|
ON product.product_catalog_bindings (category_id);
|
||||||
|
|
||||||
|
-- Store-managed product taxonomy tables. This taxonomy is distinct from catalog_category.
|
||||||
|
CREATE TABLE IF NOT EXISTS product.product_category (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
category_code VARCHAR(64) NOT NULL,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
parent_id BIGINT REFERENCES product.product_category(id) ON DELETE RESTRICT,
|
||||||
|
level SMALLINT NOT NULL CHECK (level BETWEEN 1 AND 4),
|
||||||
|
is_leaf BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
sort_num INTEGER NOT NULL DEFAULT 0,
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
|
remark VARCHAR(500) NOT NULL DEFAULT '',
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.product_category IS '店铺商品分类表:最多四级的业务商品分类树,与目录分类/分组表独立';
|
||||||
|
COMMENT ON COLUMN product.product_category.category_code IS '店铺内商品分类编码';
|
||||||
|
COMMENT ON COLUMN product.product_category.is_leaf IS '是否叶子分类;仅启用的叶子分类允许绑定商品';
|
||||||
|
COMMENT ON COLUMN product.product_category.status IS '分类状态:0 停用,1 启用';
|
||||||
|
COMMENT ON COLUMN product.product_category.deleted_at IS '软删除时间;NULL 表示未删除';
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_store_code_active
|
||||||
|
ON product.product_category (store_id, category_code) WHERE deleted_at IS NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_store_parent_name_active
|
||||||
|
ON product.product_category (store_id, COALESCE(parent_id, 0), lower(btrim(name))) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_store_parent_sort
|
||||||
|
ON product.product_category (store_id, parent_id, sort_num, id) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS product.product_category_bindings (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
|
||||||
|
product_category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE RESTRICT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.product_category_bindings IS '店铺商品分类绑定表:存储 SPU 与叶子商品分类的多对多关系';
|
||||||
|
COMMENT ON COLUMN product.product_category_bindings.deleted_at IS '软删除时间,便于恢复历史绑定';
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_bindings_active
|
||||||
|
ON product.product_category_bindings (product_id, product_category_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category
|
||||||
|
ON product.product_category_bindings (store_id, product_category_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_product
|
||||||
|
ON product.product_category_bindings (store_id, product_id) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS product.product_items (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
|
||||||
|
sku_no VARCHAR(100),
|
||||||
|
name VARCHAR(256) NOT NULL,
|
||||||
|
price BIGINT NOT NULL CHECK (price >= 0),
|
||||||
|
supply_price BIGINT CONSTRAINT chk_product_items_supply_price CHECK (supply_price >= 0),
|
||||||
|
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||||
|
attributes JSONB NOT NULL DEFAULT '{}'::JSONB,
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
|
is_archived BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
archived_at TIMESTAMPTZ,
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
deleted_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
tenant_id BIGINT,
|
||||||
|
store_id BIGINT,
|
||||||
|
CONSTRAINT chk_product_items_archived
|
||||||
|
CHECK ((is_archived = FALSE AND archived_at IS NULL) OR (is_archived = TRUE AND archived_at IS NOT NULL))
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.product_items IS '商品 SKU 明细表:存储具体可售规格、价格和规格属性;库存统一存储在 product.product_item_inventory';
|
||||||
|
COMMENT ON COLUMN product.product_items.price IS 'SKU 售价,单位:分';
|
||||||
|
COMMENT ON COLUMN product.product_items.supply_price IS 'SKU 供货价,单位:分;NULL 表示未维护';
|
||||||
|
COMMENT ON COLUMN product.product_items.image_ids IS 'SKU 图片 ID 列表';
|
||||||
|
COMMENT ON COLUMN product.product_items.attributes IS 'SKU 规格属性 JSONB,如颜色、尺寸等';
|
||||||
|
COMMENT ON COLUMN product.product_items.status IS 'SKU 状态:0 停用,1 启用';
|
||||||
|
COMMENT ON COLUMN product.product_items.is_archived IS 'SKU 是否归档;归档 SKU 不参与当前运营、展示和新订单销售';
|
||||||
|
COMMENT ON COLUMN product.product_items.archived_at IS 'SKU 归档时间;归档后仅保留供历史订单结算与展示';
|
||||||
|
COMMENT ON COLUMN product.product_items.version IS 'SKU 乐观锁版本号';
|
||||||
|
COMMENT ON COLUMN product.product_items.deleted_at IS 'SKU 软删除时间;NULL 表示未删除';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_items_product_id
|
||||||
|
ON product.product_items (product_id) WHERE deleted_at IS NULL AND is_archived = FALSE;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_items_price
|
||||||
|
ON product.product_items (price) WHERE deleted_at IS NULL AND is_archived = FALSE;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_items_store_id
|
||||||
|
ON product.product_items (store_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_store_sku_no_active
|
||||||
|
ON product.product_items (store_id, sku_no)
|
||||||
|
WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS product.product_item_inventory (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
|
||||||
|
spu_no VARCHAR(100),
|
||||||
|
sku_no VARCHAR(100),
|
||||||
|
stock_quantity INTEGER NOT NULL DEFAULT 0 CHECK (stock_quantity >= 0),
|
||||||
|
locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0),
|
||||||
|
sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0),
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.product_item_inventory IS '商品 SKU 库存销量表:存储库存池、锁定库存和已售数量';
|
||||||
|
COMMENT ON COLUMN product.product_item_inventory.id IS '库存记录主键,由商品服务应用层生成雪花 ID';
|
||||||
|
COMMENT ON COLUMN product.product_item_inventory.spu_no IS '商品 SPU 编码冗余字段,用于库存查询和对账';
|
||||||
|
COMMENT ON COLUMN product.product_item_inventory.sku_no IS '商品 SKU 编码冗余字段,用于库存查询和对账';
|
||||||
|
COMMENT ON COLUMN product.product_item_inventory.stock_quantity IS 'SKU 当前库存池数量,净可售=stock_quantity-locked_quantity';
|
||||||
|
COMMENT ON COLUMN product.product_item_inventory.locked_quantity IS '待支付订单锁定库存';
|
||||||
|
COMMENT ON COLUMN product.product_item_inventory.sold_quantity IS '支付成功后的累计销量';
|
||||||
|
COMMENT ON COLUMN product.product_item_inventory.version IS '库存乐观锁版本号';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS product.inventory_adjustments (
|
||||||
|
order_id BIGINT NOT NULL,
|
||||||
|
action VARCHAR(20) NOT NULL,
|
||||||
|
sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
|
||||||
|
quantity INTEGER NOT NULL CHECK (quantity > 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
PRIMARY KEY (order_id, action, sku_id),
|
||||||
|
CONSTRAINT chk_inventory_adjustments_action CHECK (action IN ('confirm', 'release'))
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.inventory_adjustments IS '订单库存动作幂等表:记录确认成交和释放锁定库存';
|
||||||
|
COMMENT ON COLUMN product.inventory_adjustments.action IS '库存动作:confirm 支付成功确认成交;release 待支付取消/超时释放锁定';
|
||||||
|
|
||||||
|
-- Supplier and brand master-data tables.
|
||||||
|
CREATE TABLE IF NOT EXISTS product.suppliers (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
alias VARCHAR(100) NOT NULL DEFAULT '',
|
||||||
|
supplier_code VARCHAR(64) NOT NULL,
|
||||||
|
attachments JSONB NOT NULL DEFAULT '[]'::JSONB,
|
||||||
|
contact_name VARCHAR(100) NOT NULL DEFAULT '',
|
||||||
|
contact_phone VARCHAR(32) NOT NULL DEFAULT '',
|
||||||
|
remark VARCHAR(1000) NOT NULL DEFAULT '',
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.suppliers IS '店铺供应商主数据表';
|
||||||
|
COMMENT ON COLUMN product.suppliers.attachments IS '供应商附件 JSON 数组,元素包含 file_id、file_name 和 file_type';
|
||||||
|
COMMENT ON COLUMN product.suppliers.status IS '供应商状态:0 停用,1 启用';
|
||||||
|
COMMENT ON COLUMN product.suppliers.deleted_at IS '软删除时间;NULL 表示未删除';
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_suppliers_store_code_active
|
||||||
|
ON product.suppliers (store_id, supplier_code) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_suppliers_store_list
|
||||||
|
ON product.suppliers (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS product.brands (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
alias VARCHAR(100) NOT NULL DEFAULT '',
|
||||||
|
brand_code VARCHAR(64) NOT NULL,
|
||||||
|
supplier_id BIGINT NOT NULL,
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.brands IS '店铺品牌主数据表;supplier_id 由应用层约束到同店铺供应商,避免软删除外键限制';
|
||||||
|
COMMENT ON COLUMN product.brands.status IS '品牌状态:0 停用,1 启用';
|
||||||
|
COMMENT ON COLUMN product.brands.deleted_at IS '软删除时间;NULL 表示未删除';
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_brands_store_code_active
|
||||||
|
ON product.brands (store_id, brand_code) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_brands_store_list
|
||||||
|
ON product.brands (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_brands_supplier
|
||||||
|
ON product.brands (store_id, supplier_id) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_products_updated_at ON product.products;
|
||||||
|
CREATE TRIGGER set_products_updated_at
|
||||||
|
BEFORE UPDATE ON product.products
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_product_category_updated_at ON product.product_category;
|
||||||
|
CREATE TRIGGER set_product_category_updated_at
|
||||||
|
BEFORE UPDATE ON product.product_category
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_product_category_bindings_updated_at ON product.product_category_bindings;
|
||||||
|
CREATE TRIGGER set_product_category_bindings_updated_at
|
||||||
|
BEFORE UPDATE ON product.product_category_bindings
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_product_items_updated_at ON product.product_items;
|
||||||
|
CREATE TRIGGER set_product_items_updated_at
|
||||||
|
BEFORE UPDATE ON product.product_items
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_product_item_inventory_updated_at ON product.product_item_inventory;
|
||||||
|
CREATE TRIGGER set_product_item_inventory_updated_at
|
||||||
|
BEFORE UPDATE ON product.product_item_inventory
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_suppliers_updated_at ON product.suppliers;
|
||||||
|
CREATE TRIGGER set_suppliers_updated_at
|
||||||
|
BEFORE UPDATE ON product.suppliers
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_brands_updated_at ON product.brands;
|
||||||
|
CREATE TRIGGER set_brands_updated_at
|
||||||
|
BEFORE UPDATE ON product.brands
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
|
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA product TO svc_product;
|
||||||
Loading…
Reference in New Issue
Block a user