feat: implement soft-delete and audit fields for catalog categories and bindings

This commit is contained in:
BXY 2026-10-28 17:36:23 +08:00
parent 7ee9497cfa
commit 5934f1b5cf
7 changed files with 229 additions and 56 deletions

View File

@ -31,7 +31,7 @@ func (r *ProductRepository) ValidateCatalogCategory(ctx context.Context, categor
err = r.db.QueryRowContext(ctx, `
SELECT node_type
FROM product.catalog_category
WHERE id = $1 AND store_id = $2
WHERE id = $1 AND store_id = $2 AND deleted_at IS NULL
`, id, scope.StoreID).Scan(&nodeType)
if errors.Is(err, sql.ErrNoRows) {
return ErrInvalidCatalogCategory
@ -359,12 +359,14 @@ FROM product.catalog_category AS c
WHERE c.id = $1
AND c.node_type = 2
AND c.store_id = $2
AND c.deleted_at IS NULL
AND NOT EXISTS (
SELECT 1
FROM product.catalog_category child
WHERE child.parent_id = c.id
AND child.store_id = $2
AND child.node_type = 2
AND child.deleted_at IS NULL
)
`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID)
if errors.Is(err, sql.ErrNoRows) {
@ -381,12 +383,15 @@ WHERE c.id = $1
ph, args := productIDPlaceholders(parsed, 2)
queryArgs := append([]any{scope.StoreID}, args...)
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`
DELETE FROM product.product_catalog_bindings pcb
UPDATE product.product_catalog_bindings pcb
SET deleted_at = NOW(), updated_at = NOW()
USING product.catalog_category pc
WHERE pcb.category_id = pc.id
AND pc.node_type = 2
AND pc.store_id = $1
AND pcb.product_id IN (%s)
AND pcb.deleted_at IS NULL
AND pc.deleted_at IS NULL
`, ph), queryArgs...); err != nil {
return 0, fmt.Errorf("clear group bindings: %w", err)
}
@ -401,7 +406,7 @@ WHERE pcb.category_id = pc.id
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO product.product_catalog_bindings (id, product_id, category_id)
VALUES %s
ON CONFLICT (product_id, category_id) DO NOTHING
ON CONFLICT (product_id, category_id) WHERE deleted_at IS NULL DO NOTHING
`, strings.Join(valuePlaceholders, ", ")), insertArgs...); err != nil {
return 0, fmt.Errorf("insert group bindings: %w", err)
}

View File

@ -525,6 +525,34 @@ ALTER TABLE product.products
ALTER TABLE product.product_catalog_bindings
ALTER COLUMN id DROP DEFAULT;
ALTER TABLE product.catalog_category
ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
ALTER TABLE product.product_catalog_bindings
ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
ALTER TABLE product.product_catalog_bindings
DROP CONSTRAINT IF EXISTS uq_product_catalog_bindings_product_category;
ALTER TABLE product.product_catalog_bindings
DROP CONSTRAINT IF EXISTS uq_product_category_bindings_product_category;
DROP INDEX IF EXISTS product.uq_product_catalog_bindings_product_category;
DROP INDEX IF EXISTS product.uq_product_category_bindings_product_category;
DROP INDEX IF EXISTS product.idx_product_catalog_bindings_category_id;
DROP INDEX IF EXISTS product.idx_catalog_category_store_type_created_id;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_catalog_bindings_active_product_category
ON product.product_catalog_bindings (product_id, category_id)
WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_product_catalog_bindings_category_id
ON product.product_catalog_bindings (category_id)
WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_created_id
ON product.catalog_category (store_id, node_type, created_at DESC, id DESC)
WHERE deleted_at IS NULL;
ALTER TABLE product.catalog_category
ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[];
@ -721,11 +749,12 @@ CREATE INDEX IF NOT EXISTS idx_products_store_presale_created_id
ON product.products (store_id, presale_type, created_at DESC, id DESC) WHERE deleted_at IS NULL;
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_type_parent_status_sort
ON product.catalog_category (store_id, node_type, parent_id, status, sort_num, id);
ON product.catalog_category (store_id, node_type, parent_id, status, sort_num, id)
WHERE deleted_at IS NULL;
COMMENT ON COLUMN product.catalog_category.level IS
'Server-maintained hierarchy level: root is 1 and each child is parent level plus 1.';
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 AND deleted_at IS 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 (
@ -733,14 +762,14 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name
COALESCE(parent_id, 0),
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
)
WHERE node_type = 2;
WHERE node_type = 2 AND deleted_at IS NULL;
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;
WHERE node_type = 1 AND deleted_at IS NULL;
DROP INDEX IF EXISTS product.uq_product_items_sku_no;
DROP INDEX IF EXISTS product.uq_product_items_sku_no_active;
DROP INDEX IF EXISTS product.uq_product_items_store_sku_no_active;
@ -1103,11 +1132,11 @@ func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID strin
}
rows, err := tx.QueryContext(ctx, `
WITH RECURSIVE descendants(id, path) AS (
SELECT id, ARRAY[id] FROM product.catalog_category WHERE id = $1 AND store_id = $2 AND node_type = 1
SELECT id, ARRAY[id] FROM product.catalog_category WHERE id = $1 AND store_id = $2 AND node_type = 1 AND deleted_at IS NULL
UNION ALL
SELECT child.id, parent.path || child.id
FROM product.catalog_category child JOIN descendants parent ON child.parent_id = parent.id
WHERE child.store_id = $2 AND child.node_type = 1 AND NOT child.id = ANY(parent.path)
WHERE child.store_id = $2 AND child.node_type = 1 AND child.deleted_at IS NULL AND NOT child.id = ANY(parent.path)
)
SELECT id FROM descendants
`, targetID, scope.StoreID)
@ -1146,17 +1175,18 @@ SELECT id FROM descendants
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
SELECT COUNT(DISTINCT product_id), COUNT(*)
FROM product.product_catalog_bindings
WHERE category_id IN (%s)
WHERE category_id IN (%s) AND deleted_at IS NULL
`, whereIDs), args...).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil {
return nil, fmt.Errorf("count category bindings for delete: %w", err)
}
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`
DELETE FROM product.product_catalog_bindings
WHERE category_id IN (%s)
UPDATE product.product_catalog_bindings
SET deleted_at = NOW(), updated_at = NOW()
WHERE category_id IN (%s) AND deleted_at IS NULL
`, whereIDs), args...); err != nil {
return nil, fmt.Errorf("delete category bindings: %w", err)
}
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM product.catalog_category WHERE id IN (%s) AND store_id = $%d`, whereIDs, len(args)+1), append(args, scope.StoreID)...); err != nil {
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE product.catalog_category SET deleted_at = NOW(), updated_at = NOW(), version = version + 1 WHERE id IN (%s) AND store_id = $%d AND deleted_at IS NULL`, whereIDs, len(args)+1), append(args, scope.StoreID)...); err != nil {
return nil, fmt.Errorf("delete category tree: %w", err)
}
if err := tx.Commit(); err != nil {
@ -1165,7 +1195,7 @@ WHERE category_id IN (%s)
return result, nil
}
// GroupDeleteResult summarizes a destructive product-group deletion.
// GroupDeleteResult summarizes a soft-deleted product-group deletion.
type GroupDeleteResult struct {
DeletedGroupID string
UnboundProductCount int64
@ -1206,7 +1236,7 @@ func (r *ProductRepository) UpdateGroup(ctx context.Context, update CategoryFiel
return updated, nil
}
// DeleteGroup hard-deletes one product group and its bindings. Products are retained.
// DeleteGroup soft-deletes one product group and its bindings. Products are retained.
func (r *ProductRepository) DeleteGroup(ctx context.Context, groupID string, expectedVersion int32, scope StoreScope) (*GroupDeleteResult, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
@ -1240,7 +1270,7 @@ func (r *ProductRepository) DeleteGroup(ctx context.Context, groupID string, exp
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
WHERE parent_id = $1 AND store_id = $2 AND deleted_at IS NULL
FOR UPDATE
`, targetID, scope.StoreID)
if err != nil {
@ -1282,27 +1312,30 @@ FOR UPDATE
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
SELECT COUNT(DISTINCT product_id), COUNT(*)
FROM product.product_catalog_bindings
WHERE category_id IN (%s)
WHERE category_id IN (%s) AND deleted_at IS NULL
`, 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, fmt.Sprintf(`
DELETE FROM product.product_catalog_bindings
WHERE category_id IN (%s)
UPDATE product.product_catalog_bindings
SET deleted_at = NOW(), updated_at = NOW()
WHERE category_id IN (%s) AND deleted_at IS NULL
`, 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
UPDATE product.catalog_category
SET deleted_at = NOW(), updated_at = NOW(), version = version + 1
WHERE parent_id = $1 AND store_id = $2 AND node_type = 2 AND deleted_at IS NULL
`, 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
UPDATE product.catalog_category
SET deleted_at = NOW(), updated_at = NOW(), version = version + 1
WHERE id = $1 AND store_id = $2 AND node_type = 2 AND deleted_at IS NULL
`, targetID, scope.StoreID); err != nil {
return nil, fmt.Errorf("delete group: %w", err)
}
@ -1324,7 +1357,7 @@ func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string, s
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 id = $1 AND store_id = $2
WHERE id = $1 AND store_id = $2 AND deleted_at IS NULL
FOR UPDATE`, id, scope.StoreID)
category, err := scanCategory(row)
if errors.Is(err, sql.ErrNoRows) {
@ -1355,8 +1388,9 @@ SET name = CASE WHEN $3 THEN $4 ELSE name END,
sort_num = CASE WHEN $7 THEN $8 ELSE sort_num END,
status = CASE WHEN $9 THEN $10 ELSE status END,
campaign_id = CASE WHEN $11 THEN $12 ELSE campaign_id END,
version = version + 1
WHERE id = $1 AND version = $2
version = version + 1,
updated_at = NOW()
WHERE id = $1 AND version = $2 AND deleted_at IS NULL
RETURNING id, node_type, name, parent_id, level,
COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, campaign_id, version`,
id, update.ExpectedVersion,
@ -1463,11 +1497,13 @@ FROM product.catalog_category c
WHERE c.id = $1
AND c.node_type = $2
AND c.store_id = $3
AND c.deleted_at IS NULL
AND ($4 = 0 OR ($4 > 0 AND c.level = $4) OR ($4 = -1 AND NOT EXISTS (
SELECT 1 FROM product.catalog_category child
WHERE child.parent_id = c.id
AND child.store_id = $3
AND child.node_type = $2
AND child.deleted_at IS NULL
)))
`, parsedNodeID, nodeType, scope.StoreID, level).Scan(&parsedNodeID)
if errors.Is(err, sql.ErrNoRows) {
@ -1525,7 +1561,7 @@ WHERE deleted_at IS NULL
_, err = tx.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO product.product_catalog_bindings (id, product_id, category_id)
VALUES %s
ON CONFLICT (product_id, category_id) DO NOTHING
ON CONFLICT (product_id, category_id) WHERE deleted_at IS NULL DO NOTHING
`, strings.Join(valuePlaceholders, ", ")), args...)
if err != nil {
return fmt.Errorf("insert product %s bindings: %w", nodeLabel, err)
@ -1571,12 +1607,14 @@ FROM product.catalog_category AS c
WHERE c.id = $1
AND c.node_type = 2
AND c.store_id = $2
AND c.deleted_at IS NULL
AND NOT EXISTS (
SELECT 1
FROM product.catalog_category child
WHERE child.parent_id = c.id
AND child.store_id = $2
AND child.node_type = 2
AND child.deleted_at IS NULL
)
`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID)
if errors.Is(err, sql.ErrNoRows) {
@ -1594,9 +1632,11 @@ WHERE c.id = $1
args = append(args, productID)
}
_, err = tx.ExecContext(ctx, fmt.Sprintf(`
DELETE FROM product.product_catalog_bindings
UPDATE product.product_catalog_bindings
SET deleted_at = NOW(), updated_at = NOW()
WHERE category_id = $1
AND product_id IN (%s)
AND deleted_at IS NULL
`, strings.Join(placeholders, ", ")), args...)
if err != nil {
return fmt.Errorf("delete product category or group bindings: %w", err)
@ -1911,11 +1951,13 @@ FROM product.catalog_category c
WHERE c.node_type = 1
AND c.store_id = $%d
AND c.id IN (%s)
AND c.deleted_at IS NULL
AND NOT EXISTS (
SELECT 1 FROM product.catalog_category child
WHERE child.parent_id = c.id
AND child.store_id = c.store_id
AND child.node_type = 1
AND child.deleted_at IS NULL
)
FOR KEY SHARE
`, len(args)+1, strings.Join(placeholders, ", ")), append(args, scope.StoreID)...)
@ -1944,12 +1986,15 @@ FOR KEY SHARE
}
if _, err := tx.ExecContext(ctx, `
DELETE FROM product.product_catalog_bindings AS b
UPDATE product.product_catalog_bindings AS b
SET deleted_at = NOW(), updated_at = NOW()
USING product.catalog_category AS c
WHERE b.product_id = $1
AND b.category_id = c.id
AND c.node_type = 1
AND c.store_id = $2
AND b.deleted_at IS NULL
AND c.deleted_at IS NULL
`, parsedProductID, scope.StoreID); err != nil {
return fmt.Errorf("delete product leaf category bindings: %w", err)
}
@ -2003,12 +2048,14 @@ FROM product.catalog_category AS c
WHERE c.node_type = 2
AND c.store_id = $%d
AND c.id IN (%s)
AND c.deleted_at IS NULL
AND NOT EXISTS (
SELECT 1
FROM product.catalog_category child
WHERE child.parent_id = c.id
AND child.store_id = $%d
AND child.node_type = 2
AND child.deleted_at IS NULL
)
FOR KEY SHARE
`, len(args)+1, strings.Join(placeholders, ", "), len(args)+1), append(args, scope.StoreID)...)
@ -2037,12 +2084,15 @@ FOR KEY SHARE
}
if _, err := tx.ExecContext(ctx, `
DELETE FROM product.product_catalog_bindings AS b
UPDATE product.product_catalog_bindings AS b
SET deleted_at = NOW(), updated_at = NOW()
USING product.catalog_category AS c
WHERE b.product_id = $1
AND b.category_id = c.id
AND c.node_type = 2
AND c.store_id = $2
AND b.deleted_at IS NULL
AND c.deleted_at IS NULL
`, parsedProductID, scope.StoreID); err != nil {
return fmt.Errorf("delete product group bindings: %w", err)
}
@ -2353,8 +2403,9 @@ WHERE product_id = $1 AND store_id = $3
return nil, fmt.Errorf("update sku store: %w", err)
}
if _, err := tx.ExecContext(ctx, `
DELETE FROM product.product_catalog_bindings
WHERE product_id = $1
UPDATE product.product_catalog_bindings
SET deleted_at = NOW(), updated_at = NOW()
WHERE product_id = $1 AND deleted_at IS NULL
`, id); err != nil {
return nil, fmt.Errorf("detach product categories: %w", err)
}
@ -3220,8 +3271,9 @@ func (r *ProductRepository) listProductLeafCategoryIDs(ctx context.Context, prod
rows, err := r.db.QueryContext(ctx, `
SELECT c.id
FROM product.product_catalog_bindings AS b
JOIN product.catalog_category AS c ON c.id = b.category_id
JOIN product.catalog_category AS c ON c.id = b.category_id AND c.deleted_at IS NULL
WHERE b.product_id = $1
AND b.deleted_at IS NULL
AND c.node_type = 1
AND c.store_id = $2
AND NOT EXISTS (
@ -3229,6 +3281,7 @@ WHERE b.product_id = $1
WHERE child.parent_id = c.id
AND child.store_id = c.store_id
AND child.node_type = 1
AND child.deleted_at IS NULL
)
ORDER BY c.sort_num, c.id
`, parsedProductID, scope.StoreID)
@ -3261,8 +3314,9 @@ func (r *ProductRepository) listProductGroupIDs(ctx context.Context, productID s
rows, err := r.db.QueryContext(ctx, `
SELECT c.id
FROM product.product_catalog_bindings AS b
JOIN product.catalog_category AS c ON c.id = b.category_id
JOIN product.catalog_category AS c ON c.id = b.category_id AND c.deleted_at IS NULL
WHERE b.product_id = $1
AND b.deleted_at IS NULL
AND c.node_type = 2
AND c.store_id = $2
ORDER BY c.sort_num, c.id
@ -3472,12 +3526,14 @@ FROM product.catalog_category AS c
WHERE c.id = $1
AND c.node_type = 2
AND c.store_id = $2
AND c.deleted_at IS NULL
AND NOT EXISTS (
SELECT 1
FROM product.catalog_category child
WHERE child.parent_id = c.id
AND child.store_id = $2
AND child.node_type = 2
AND child.deleted_at IS NULL
)
`, parsedGroupID, scope.StoreID).Scan(&found)
if errors.Is(err, sql.ErrNoRows) {
@ -3737,9 +3793,10 @@ func (r *ProductRepository) populateProductGroupSummaries(ctx context.Context, p
rows, err := r.db.QueryContext(ctx, `
SELECT b.product_id, c.id, c.name
FROM product.product_catalog_bindings b
JOIN product.catalog_category c ON c.id = b.category_id
JOIN product.catalog_category c ON c.id = b.category_id AND c.deleted_at IS NULL
WHERE c.store_id = $1
AND c.node_type = 2
AND b.deleted_at IS NULL
AND b.product_id IN (`+placeholders+`)
ORDER BY b.product_id, c.sort_num, c.id`, args...)
if err != nil {
@ -3819,9 +3876,10 @@ func productListWhere(filter ProductListFilter, scope StoreScope) (string, []any
add(`EXISTS (
SELECT 1
FROM product.product_catalog_bindings pcb
JOIN product.catalog_category pc ON pc.id = pcb.category_id
JOIN product.catalog_category pc ON pc.id = pcb.category_id AND pc.deleted_at IS NULL
WHERE pcb.product_id = p.id
AND pcb.category_id = $%d
AND pcb.deleted_at IS NULL
AND pc.node_type = 2
AND pc.store_id = p.store_id
)`, filter.GroupID)
@ -4044,16 +4102,17 @@ func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID
SELECT COUNT(*)
FROM product.products p
JOIN product.product_catalog_bindings b ON b.product_id = p.id
JOIN product.catalog_category c ON c.id = b.category_id
JOIN product.catalog_category c ON c.id = b.category_id AND c.deleted_at IS NULL
WHERE (($6 = 2 AND b.category_id = $1) OR ($6 = 1 AND b.category_id IN (
WITH RECURSIVE descendants(id) AS (
SELECT id FROM product.catalog_category WHERE id = $1 AND store_id = $5 AND node_type = 1
SELECT id FROM product.catalog_category WHERE id = $1 AND store_id = $5 AND node_type = 1 AND deleted_at IS NULL
UNION ALL
SELECT child.id FROM product.catalog_category child JOIN descendants parent ON child.parent_id = parent.id
WHERE child.store_id = $5 AND child.node_type = 1
WHERE child.store_id = $5 AND child.node_type = 1 AND child.deleted_at IS NULL
) SELECT id FROM descendants
)))
AND p.deleted_at IS NULL
AND b.deleted_at IS NULL
AND p.store_id = $5
AND c.store_id = $5
AND c.node_type = $6
@ -4077,16 +4136,17 @@ WHERE (($6 = 2 AND b.category_id = $1) OR ($6 = 1 AND b.category_id IN (
SELECT p.id
FROM product.products p
JOIN product.product_catalog_bindings b ON b.product_id = p.id
JOIN product.catalog_category c ON c.id = b.category_id
JOIN product.catalog_category c ON c.id = b.category_id AND c.deleted_at IS NULL
WHERE (($6 = 2 AND b.category_id = $1) OR ($6 = 1 AND b.category_id IN (
WITH RECURSIVE descendants(id) AS (
SELECT id FROM product.catalog_category WHERE id = $1 AND store_id = $5 AND node_type = 1
SELECT id FROM product.catalog_category WHERE id = $1 AND store_id = $5 AND node_type = 1 AND deleted_at IS NULL
UNION ALL
SELECT child.id FROM product.catalog_category child JOIN descendants parent ON child.parent_id = parent.id
WHERE child.store_id = $5 AND child.node_type = 1
WHERE child.store_id = $5 AND child.node_type = 1 AND child.deleted_at IS NULL
) SELECT id FROM descendants
)))
AND p.deleted_at IS NULL
AND b.deleted_at IS NULL
AND p.store_id = $5
AND c.store_id = $5
AND c.node_type = $6
@ -4135,7 +4195,7 @@ SELECT DISTINCT p.updated_at,
COALESCE(sku_summary.locked_quantity, 0)
FROM product.products p
JOIN product.product_catalog_bindings b ON b.product_id = p.id
JOIN product.catalog_category c ON c.id = b.category_id
JOIN product.catalog_category c ON c.id = b.category_id AND c.deleted_at IS NULL
LEFT JOIN LATERAL (
SELECT MIN(pi.price) AS price,
SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity,
@ -4150,13 +4210,14 @@ LEFT JOIN LATERAL (
) sku_summary ON TRUE
WHERE (($8 = 2 AND b.category_id = $1) OR ($8 = 1 AND b.category_id IN (
WITH RECURSIVE descendants(id) AS (
SELECT id FROM product.catalog_category WHERE id = $1 AND store_id = $7 AND node_type = 1
SELECT id FROM product.catalog_category WHERE id = $1 AND store_id = $7 AND node_type = 1 AND deleted_at IS NULL
UNION ALL
SELECT child.id FROM product.catalog_category child JOIN descendants parent ON child.parent_id = parent.id
WHERE child.store_id = $7 AND child.node_type = 1
WHERE child.store_id = $7 AND child.node_type = 1 AND child.deleted_at IS NULL
) SELECT id FROM descendants
)))
AND p.deleted_at IS NULL
AND b.deleted_at IS NULL
AND p.store_id = $7
AND c.store_id = $7
AND c.node_type = $8
@ -4204,6 +4265,7 @@ WITH RECURSIVE ancestry AS (
WHERE id = $1
AND store_id = $2
AND node_type = 1
AND deleted_at IS NULL
UNION ALL
@ -4212,6 +4274,7 @@ WITH RECURSIVE ancestry AS (
JOIN ancestry ON ancestry.parent_id = parent.id
WHERE parent.store_id = $2
AND parent.node_type = 1
AND parent.deleted_at IS NULL
AND NOT parent.id = ANY(ancestry.path)
)
SELECT EXISTS (SELECT 1 FROM ancestry WHERE parent_id IS NULL)
@ -4226,6 +4289,7 @@ SELECT EXISTS (SELECT 1 FROM ancestry WHERE parent_id IS NULL)
WHERE parent.id = child.parent_id
AND parent.store_id = $2
AND parent.node_type = 1
AND parent.deleted_at IS NULL
)
)
`, categoryID, scope.StoreID).Scan(&visible)
@ -4275,6 +4339,7 @@ FROM (
FROM product.catalog_category
WHERE node_type = 1
AND store_id = $2
AND deleted_at IS NULL
AND (($3::BIGINT IS NULL AND parent_id IS NULL) OR id = $3)
AND ($1 = FALSE OR status = 1)
@ -4285,6 +4350,7 @@ FROM (
JOIN category_tree parent ON child.parent_id = parent.id
WHERE child.node_type = 1
AND child.store_id = $2
AND child.deleted_at IS NULL
AND ($1 = FALSE OR child.status = 1)
AND ($4 = 0 OR parent.depth < $4)
AND NOT child.id = ANY(parent.path)
@ -4347,8 +4413,10 @@ 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
AND parent.deleted_at IS NULL
WHERE c.node_type = 2
AND c.store_id = $1
AND c.deleted_at IS NULL
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)
@ -4384,17 +4452,20 @@ SELECT c.id,
WHERE child.parent_id = c.id
AND child.store_id = c.store_id
AND child.node_type = 2
AND child.deleted_at IS NULL
) AS is_leaf
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
AND parent.deleted_at IS NULL
LEFT JOIN product.product_catalog_bindings AS b ON b.category_id = c.id AND b.deleted_at IS NULL
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 = $1
AND c.deleted_at IS NULL
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)
@ -4405,7 +4476,7 @@ WHERE c.node_type = 2
ELSE c.name ILIKE ('%' || $4 || '%') ESCAPE '\'
END))
GROUP BY c.id
ORDER BY c.id DESC
ORDER BY c.created_at DESC, c.id DESC
LIMIT $6 OFFSET $7
`
args := []any{scope.StoreID, filter.OnlyVisible, firstLevelName, secondLevelName, filter.ExactMatch, pageSize, offset}
@ -4465,6 +4536,7 @@ SELECT c.id,
COALESCE(p.spu_no, '') AS spu_no
FROM product.catalog_category AS c
JOIN product.product_catalog_bindings AS binding ON binding.category_id = c.id
AND binding.deleted_at IS NULL
JOIN product.products AS p ON p.id = binding.product_id
AND p.tenant_id = $1
AND p.store_id = $2
@ -4476,12 +4548,14 @@ LEFT JOIN product.brands AS b ON b.id = p.brand_id
WHERE c.id IN (`+placeholders+`)
AND c.node_type = 2
AND c.store_id = $2
AND c.deleted_at IS NULL
AND NOT EXISTS (
SELECT 1
FROM product.catalog_category child
WHERE child.parent_id = c.id
AND child.store_id = $2
AND child.node_type = 2
AND child.deleted_at IS NULL
)
ORDER BY c.id ASC,
CASE WHEN p.brand_id IS NULL THEN 1 ELSE 0 END ASC,
@ -4870,7 +4944,7 @@ func insertCategoryBinding(ctx context.Context, tx *sql.Tx, bindingID, productID
_, err = tx.ExecContext(ctx, `
INSERT INTO product.product_catalog_bindings (id, product_id, category_id)
VALUES ($1, $2, $3)
ON CONFLICT (product_id, category_id) DO NOTHING
ON CONFLICT (product_id, category_id) WHERE deleted_at IS NULL DO NOTHING
`, parsedBindingID, parsedProductID, parsedCategoryID)
if err != nil {
return fmt.Errorf("insert category binding: %w", err)

View File

@ -87,3 +87,15 @@ func TestProductListWhereFiltersStatus(t *testing.T) {
t.Fatalf("args = %#v, want [1001 1]", args)
}
}
func TestProductListWhereIgnoresSoftDeletedGroupBindings(t *testing.T) {
where, _ := productListWhere(ProductListFilter{GroupID: "2001"}, StoreScope{StoreID: 1001})
for _, expected := range []string{
"pcb.deleted_at IS NULL",
"pc.deleted_at IS NULL",
} {
if !strings.Contains(where, expected) {
t.Fatalf("group predicate missing %q:\n%s", expected, where)
}
}
}

View File

@ -0,0 +1,10 @@
-- Adds audit timestamps required by the product-group list's
-- created_at-descending pagination. This migration is idempotent and the
-- product service also executes the same statements in EnsureSchema.
ALTER TABLE product.catalog_category
ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_created_id
ON product.catalog_category (store_id, node_type, created_at DESC, id DESC);

View File

@ -0,0 +1,49 @@
-- Adds audit timestamps and soft-delete support to storefront catalog nodes
-- and their product bindings. The statements are idempotent and mirror the
-- product service's EnsureSchema upgrade path.
ALTER TABLE product.catalog_category
ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
ALTER TABLE product.product_catalog_bindings
ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
ALTER TABLE product.product_catalog_bindings
DROP CONSTRAINT IF EXISTS uq_product_catalog_bindings_product_category;
ALTER TABLE product.product_catalog_bindings
DROP CONSTRAINT IF EXISTS uq_product_category_bindings_product_category;
DROP INDEX IF EXISTS product.uq_product_catalog_bindings_product_category;
DROP INDEX IF EXISTS product.uq_product_category_bindings_product_category;
DROP INDEX IF EXISTS product.idx_product_catalog_bindings_category_id;
DROP INDEX IF EXISTS product.idx_catalog_category_store_type_created_id;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_catalog_bindings_active_product_category
ON product.product_catalog_bindings (product_id, category_id)
WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_product_catalog_bindings_category_id
ON product.product_catalog_bindings (category_id)
WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_created_id
ON product.catalog_category (store_id, node_type, created_at DESC, id DESC)
WHERE deleted_at IS 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 AND deleted_at IS NULL;
DROP INDEX IF EXISTS product.uq_product_category_sibling_normalized_name;
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 AND deleted_at IS NULL;

View File

@ -118,6 +118,9 @@ CREATE TABLE IF NOT EXISTS product.catalog_category (
tenant_id BIGINT,
store_id BIGINT,
campaign_id BIGINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
deleted_at TIMESTAMPTZ,
CONSTRAINT chk_catalog_category_node_type
CHECK (node_type IN (1, 2)),
CONSTRAINT chk_catalog_category_level
@ -142,25 +145,30 @@ CREATE INDEX IF NOT EXISTS idx_catalog_category_node_status_sort
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;
ON product.catalog_category (campaign_id) WHERE campaign_id IS NOT NULL AND deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_created_id
ON product.catalog_category (store_id, node_type, created_at DESC, id DESC)
WHERE deleted_at IS NULL;
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;
) WHERE node_type = 2 AND deleted_at IS NULL;
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;
) WHERE node_type = 1 AND deleted_at IS NULL;
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)
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
deleted_at TIMESTAMPTZ
);
COMMENT ON TABLE product.product_catalog_bindings IS '商品目录分类/分组绑定表:存储 SPU 与目录分类或分组节点的多对多关系';
@ -168,7 +176,9 @@ COMMENT ON COLUMN product.product_catalog_bindings.product_id IS '商品 SPU 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);
ON product.product_catalog_bindings (category_id) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_catalog_bindings_active_product_category
ON product.product_catalog_bindings (product_id, category_id) WHERE deleted_at IS NULL;
-- Global standard product taxonomy. This taxonomy is distinct from catalog_category.
CREATE TABLE IF NOT EXISTS product.product_category (

View File

@ -138,6 +138,12 @@ CREATE TABLE IF NOT EXISTS product.catalog_category (
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,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
deleted_at TIMESTAMPTZ,
CONSTRAINT chk_product_category_node_type
CHECK (node_type IN (1, 2)),
CONSTRAINT chk_product_category_level
@ -163,13 +169,18 @@ 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);
ON product.catalog_category (node_type, status, sort_num) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_created_id
ON product.catalog_category (store_id, node_type, created_at DESC, id DESC)
WHERE deleted_at IS NULL;
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_category_bindings_product_category UNIQUE (product_id, category_id)
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
deleted_at TIMESTAMPTZ
);
COMMENT ON TABLE product.product_catalog_bindings IS '商品目录分类/分组绑定表:存储商品 SPU 与分类/分组节点的多对多绑定关系';
@ -178,7 +189,9 @@ COMMENT ON COLUMN product.product_catalog_bindings.product_id IS '绑定商品 S
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);
ON product.product_catalog_bindings (category_id) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_catalog_bindings_active_product_category
ON product.product_catalog_bindings (product_id, category_id) WHERE deleted_at IS NULL;
CREATE TABLE IF NOT EXISTS product.product_category (
id BIGINT PRIMARY KEY,