feat: implement store scope validation and enforce it in product repository

- Added StoreScope struct with TenantID and StoreID fields.
- Introduced ErrStoreScopeRequired to handle missing store scope.
- Implemented Valid method to check if both TenantID and StoreID are present.
- Created requireWriteScope function to validate store scope before write operations.
- Updated product repository methods to require store scope for various operations.
- Added tests for StoreScope validation and requirement enforcement.
This commit is contained in:
robinj0726 2026-09-13 00:12:44 +08:00
parent a8a3464484
commit 604dfeb06c
4 changed files with 275 additions and 97 deletions

View File

@ -82,8 +82,7 @@ type ProductRecord struct {
DeletedAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
// Scope is accepted for Create/Get/List plumbing. Not persisted until store columns exist.
Scope StoreScope
Scope StoreScope
}
// ProductCountRecord contains aggregate counts for product.products.
@ -383,8 +382,23 @@ ALTER TABLE product.product_items
ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;
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 UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no_active ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE;
CREATE INDEX IF NOT EXISTS idx_products_active_created_id ON product.products(created_at DESC, id DESC) WHERE deleted_at IS NULL;
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS tenant_id BIGINT;
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS store_id BIGINT;
ALTER TABLE product.product_category ADD COLUMN IF NOT EXISTS tenant_id BIGINT;
ALTER TABLE product.product_category ADD COLUMN IF NOT EXISTS store_id BIGINT;
ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS tenant_id BIGINT;
ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS store_id BIGINT;
DROP INDEX IF EXISTS product.uq_products_spu_no;
CREATE UNIQUE INDEX IF NOT EXISTS uq_products_store_spu_no ON product.products (store_id, spu_no) WHERE deleted_at IS NULL;
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_product_category_store_id ON product.product_category (store_id);
DROP INDEX IF EXISTS product.uq_product_items_sku_no;
DROP INDEX IF EXISTS product.uq_product_items_sku_no_active;
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 INDEX IF NOT EXISTS idx_product_items_store_id ON product.product_items (store_id) WHERE deleted_at IS NULL;
`
if _, err := r.db.ExecContext(ctx, ddl); err != nil {
return fmt.Errorf("ensure product tables: %w", err)
@ -416,7 +430,9 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe
// CreateProductWithSKUs inserts an SPU and its optional SKU list in one transaction.
func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product ProductRecord, skus []SKURecord) (*ProductRecord, []SKURecord, error) {
_ = product.Scope
if err := requireWriteScope(product.Scope); err != nil {
return nil, nil, err
}
attrs, err := productCrossBorderJSON(product)
if err != nil {
return nil, nil, err
@ -443,7 +459,7 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P
}
if len(product.LeafCategoryIDs) > 0 {
if err := replaceProductLeafCategoryBindings(ctx, tx, createdProduct.ID, product.LeafCategoryIDs, product.CategoryBindingIDs); err != nil {
if err := replaceProductLeafCategoryBindings(ctx, tx, createdProduct.ID, product.LeafCategoryIDs, product.CategoryBindingIDs, product.Scope); err != nil {
return nil, nil, err
}
}
@ -457,14 +473,16 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P
// CreateCategoryTree inserts a top-level category and its optional child categories in one transaction.
func (r *ProductRepository) CreateCategoryTree(ctx context.Context, parent CategoryRecord, children []CategoryRecord, scope StoreScope) (*CategoryRecord, []*CategoryRecord, error) {
_ = scope
if err := requireWriteScope(scope); err != nil {
return nil, nil, err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, nil, fmt.Errorf("begin create category tree: %w", err)
}
defer tx.Rollback()
createdParent, err := insertCategoryNode(ctx, tx, parent)
createdParent, err := insertCategoryNode(ctx, tx, parent, scope)
if err != nil {
return nil, nil, err
}
@ -475,7 +493,7 @@ func (r *ProductRepository) CreateCategoryTree(ctx context.Context, parent Categ
child.ParentID = createdParent.ID
child.Level = createdParent.Level + 1
createdChild, err := insertCategoryNode(ctx, tx, child)
createdChild, err := insertCategoryNode(ctx, tx, child, scope)
if err != nil {
return nil, nil, err
}
@ -491,14 +509,16 @@ func (r *ProductRepository) CreateCategoryTree(ctx context.Context, parent Categ
// CreateCategoryNode inserts a single product category/group node.
func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category CategoryRecord, scope StoreScope) (*CategoryRecord, error) {
_ = scope
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 category node: %w", err)
}
defer tx.Rollback()
createdCategory, err := insertCategoryNode(ctx, tx, category)
createdCategory, err := insertCategoryNode(ctx, tx, category, scope)
if err != nil {
return nil, err
}
@ -511,7 +531,9 @@ func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category Cat
// UpdateCategoryTrees applies all requested root and direct-child patches in a
// single transaction. Callers must supply already-validated patch fields.
func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []CategoryTreeUpdate, scope StoreScope) error {
_ = scope
if err := requireWriteScope(scope); err != nil {
return err
}
if len(updates) == 0 {
return errors.New("category_trees is required")
}
@ -522,7 +544,7 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C
defer tx.Rollback()
for _, tree := range updates {
root, err := loadCategoryForUpdate(ctx, tx, tree.CategoryID)
root, err := loadCategoryForUpdate(ctx, tx, tree.CategoryID, scope)
if err != nil {
return err
}
@ -538,7 +560,7 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C
}
}
for _, child := range tree.Children {
current, err := loadCategoryForUpdate(ctx, tx, child.ID)
current, err := loadCategoryForUpdate(ctx, tx, child.ID, scope)
if err != nil {
return err
}
@ -553,7 +575,7 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C
child.NodeType = 1
child.ParentID = tree.CategoryID
child.Level = 2
if _, err := insertCategoryNode(ctx, tx, child); err != nil {
if _, err := insertCategoryNode(ctx, tx, child, scope); err != nil {
return err
}
}
@ -568,7 +590,9 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C
// and all affected product bindings in one transaction. Product rows and group
// bindings are deliberately retained.
func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID string, expectedVersion int32, scope StoreScope) (*CategoryDeleteResult, error) {
_ = scope
if err := requireWriteScope(scope); err != nil {
return nil, err
}
if expectedVersion < 0 {
return nil, errors.New("expected_version must be non-negative")
}
@ -578,7 +602,7 @@ func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID strin
}
defer tx.Rollback()
target, err := loadCategoryForUpdate(ctx, tx, categoryID)
target, err := loadCategoryForUpdate(ctx, tx, categoryID, scope)
if err != nil {
return nil, err
}
@ -599,9 +623,9 @@ func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID strin
SELECT id, node_type, name, parent_id, level,
COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, version
FROM product.product_category
WHERE parent_id = $1
WHERE parent_id = $1 AND store_id = $2
FOR UPDATE
`, targetID)
`, targetID, scope.StoreID)
if err != nil {
return nil, fmt.Errorf("load category children for delete: %w", err)
}
@ -658,11 +682,11 @@ WHERE category_id IN (%s)
return nil, fmt.Errorf("delete category bindings: %w", err)
}
if target.Level == 1 {
if _, err := tx.ExecContext(ctx, `DELETE FROM product.product_category WHERE parent_id = $1`, targetID); err != nil {
if _, err := tx.ExecContext(ctx, `DELETE FROM product.product_category WHERE parent_id = $1 AND store_id = $2`, targetID, scope.StoreID); err != nil {
return nil, fmt.Errorf("delete child categories: %w", err)
}
}
if _, err := tx.ExecContext(ctx, `DELETE FROM product.product_category WHERE id = $1`, targetID); err != nil {
if _, err := tx.ExecContext(ctx, `DELETE FROM product.product_category WHERE id = $1 AND store_id = $2`, targetID, scope.StoreID); err != nil {
return nil, fmt.Errorf("delete category: %w", err)
}
if err := tx.Commit(); err != nil {
@ -671,17 +695,20 @@ WHERE category_id IN (%s)
return result, nil
}
func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string) (*CategoryRecord, error) {
func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string, scope StoreScope) (*CategoryRecord, error) {
id, err := parseID(categoryID, "category_id")
if err != nil {
return nil, err
}
if err := requireWriteScope(scope); err != nil {
return nil, err
}
row := tx.QueryRowContext(ctx, `
SELECT id, node_type, name, parent_id, level,
COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, version
FROM product.product_category
WHERE id = $1
FOR UPDATE`, id)
WHERE id = $1 AND store_id = $2
FOR UPDATE`, id, scope.StoreID)
category, err := scanCategory(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrCategoryNodeNotFound
@ -750,7 +777,9 @@ func pointerStringSlice(value *[]string) []string {
// AddProductsToGroup binds every product to the requested category or product group in one transaction.
// Existing bindings are retained and duplicate bindings are ignored.
func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID string, bindingIDs, productIDs []string, scope StoreScope) error {
_ = scope
if err := requireWriteScope(scope); err != nil {
return err
}
if len(productIDs) == 0 {
return errors.New("product_ids is required")
}
@ -784,8 +813,8 @@ func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID stri
err = tx.QueryRowContext(ctx, `
SELECT id
FROM product.product_category
WHERE id = $1
`, parsedGroupID).Scan(&parsedGroupID)
WHERE id = $1 AND store_id = $2
`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID)
if errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID)
}
@ -799,12 +828,14 @@ WHERE id = $1
productPlaceholders[i] = fmt.Sprintf("$%d", i+1)
productArgs[i] = productID
}
productArgs = append(productArgs, scope.StoreID)
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
SELECT id
FROM product.products
WHERE deleted_at IS NULL
AND store_id = $%d
AND id IN (%s)
`, strings.Join(productPlaceholders, ", ")), productArgs...)
`, len(productArgs), strings.Join(productPlaceholders, ", ")), productArgs...)
if err != nil {
return fmt.Errorf("query products for category or group binding: %w", err)
}
@ -854,7 +885,9 @@ ON CONFLICT (product_id, category_id) DO NOTHING
// RemoveProductsFromGroup removes product bindings from the requested category or product group in one transaction.
// Missing bindings are ignored so callers can safely retry the same request.
func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID string, productIDs []string, scope StoreScope) error {
_ = scope
if err := requireWriteScope(scope); err != nil {
return err
}
if len(productIDs) == 0 {
return errors.New("product_ids is required")
}
@ -880,8 +913,8 @@ func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID
err = tx.QueryRowContext(ctx, `
SELECT id
FROM product.product_category
WHERE id = $1
`, parsedGroupID).Scan(&parsedGroupID)
WHERE id = $1 AND store_id = $2
`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID)
if errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID)
}
@ -947,7 +980,9 @@ WHERE id = $1
// UpdateProductWithSKUChange atomically persists a merged SPU update and an optional SKU operation.
func (r *ProductRepository) UpdateProductWithSKUChange(ctx context.Context, input ProductUpdateInput) (*SKUChangeResult, error) {
_ = input.Scope
if err := requireWriteScope(input.Scope); err != nil {
return nil, err
}
if input.ExpectedVersion < 0 {
return nil, fmt.Errorf("expected product version must be non-negative")
}
@ -983,9 +1018,9 @@ func (r *ProductRepository) UpdateProductWithSKUChange(ctx context.Context, inpu
err = tx.QueryRowContext(ctx, `
SELECT status, version
FROM product.products
WHERE id = $1 AND deleted_at IS NULL
WHERE id = $1 AND deleted_at IS NULL AND store_id = $2
FOR UPDATE
`, productID).Scan(&currentStatus, &currentVersion)
`, productID, input.Scope.StoreID).Scan(&currentStatus, &currentVersion)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrProductNotFound
}
@ -996,7 +1031,7 @@ FOR UPDATE
return nil, ErrProductVersionConflict
}
if input.LeafCategoryIDs != nil {
if err := replaceProductLeafCategoryBindings(ctx, tx, input.Product.ID, *input.LeafCategoryIDs, input.CategoryBindingIDs); err != nil {
if err := replaceProductLeafCategoryBindings(ctx, tx, input.Product.ID, *input.LeafCategoryIDs, input.CategoryBindingIDs, input.Scope); err != nil {
return nil, err
}
}
@ -1024,12 +1059,12 @@ SET title = $2,
scheduled_sale_time = $16,
version = version + 1,
updated_at = NOW()
WHERE id = $1 AND version = $17 AND deleted_at IS NULL
WHERE id = $1 AND version = $17 AND deleted_at IS NULL AND store_id = $18
`, productID, input.Product.Title, input.Product.SellingPoint, brandID, supplierID,
stringSliceOrEmpty(input.Product.ImageIDs), input.Product.DetailHTML, input.Product.MemberDiscountEnabled,
int16(input.Product.GoodsType), stringSliceOrEmpty(input.Product.ServiceGuarantees), attrs,
int16(input.Product.FreightChargeType), input.Product.FreightFixedAmount, freightTemplateID,
int16(input.Product.SaleTimeType), input.Product.ScheduledSaleTime, input.ExpectedVersion); 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)
}
@ -1074,7 +1109,10 @@ WHERE id = $1 AND version = $17 AND deleted_at IS NULL
return result, nil
}
func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, productID string, leafCategoryIDs []string, bindingIDs []string) error {
func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, productID string, leafCategoryIDs []string, bindingIDs []string, scope StoreScope) error {
if err := requireWriteScope(scope); err != nil {
return err
}
if len(leafCategoryIDs) != len(bindingIDs) {
return errors.New("leaf category ids and category binding ids must have the same length")
}
@ -1110,9 +1148,10 @@ SELECT id
FROM product.product_category
WHERE node_type = 1
AND level = 2
AND store_id = $%d
AND id IN (%s)
FOR KEY SHARE
`, strings.Join(placeholders, ", ")), args...)
`, len(args)+1, strings.Join(placeholders, ", ")), append(args, scope.StoreID)...)
if err != nil {
return fmt.Errorf("validate leaf categories: %w", err)
}
@ -1144,7 +1183,8 @@ WHERE b.product_id = $1
AND b.category_id = c.id
AND c.node_type = 1
AND c.level = 2
`, parsedProductID); err != nil {
AND c.store_id = $2
`, parsedProductID, scope.StoreID); err != nil {
return fmt.Errorf("delete product leaf category bindings: %w", err)
}
for index, categoryID := range leafCategoryIDs {
@ -1157,7 +1197,9 @@ WHERE b.product_id = $1
// UpdateProductStatus changes the product lifecycle state using optimistic locking.
func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID string, next productv1.ProductStatus, expectedVersion int32, scope StoreScope) (*ProductStatusUpdate, error) {
_ = scope
if err := requireWriteScope(scope); err != nil {
return nil, err
}
if expectedVersion < 0 {
return nil, fmt.Errorf("expected product version must be non-negative")
}
@ -1179,9 +1221,9 @@ func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID s
err = tx.QueryRowContext(ctx, `
SELECT status, version
FROM product.products
WHERE id = $1 AND deleted_at IS NULL
WHERE id = $1 AND deleted_at IS NULL AND store_id = $2
FOR UPDATE
`, id).Scan(&previousDBStatus, &currentVersion)
`, id, scope.StoreID).Scan(&previousDBStatus, &currentVersion)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrProductNotFound
}
@ -1212,9 +1254,9 @@ FOR UPDATE
if err := tx.QueryRowContext(ctx, `
UPDATE product.products
SET status = $2, version = version + 1, updated_at = NOW()
WHERE id = $1 AND version = $3 AND deleted_at IS NULL
WHERE id = $1 AND version = $3 AND deleted_at IS NULL AND store_id = $4
RETURNING version, updated_at
`, id, statusToDB(next), expectedVersion).Scan(&result.Version, &result.UpdatedAt); err != nil {
`, id, statusToDB(next), expectedVersion, scope.StoreID).Scan(&result.Version, &result.UpdatedAt); err != nil {
return nil, fmt.Errorf("update product status %s: %w", productID, err)
}
if err := tx.Commit(); err != nil {
@ -1466,8 +1508,10 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error
defer tx.Rollback()
err = tx.QueryRowContext(ctx, `
INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status)
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8)
INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status, tenant_id, store_id)
SELECT $1, $2, $3, $4, $5, $6, $7::jsonb, $8, p.tenant_id, p.store_id
FROM product.products p
WHERE p.id = $2
RETURNING id
`, skuID, productID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&skuID)
if err != nil {
@ -1530,7 +1574,9 @@ WHERE id = $1 AND is_archived = FALSE
// LockInventory atomically reserves quantity when stock_quantity - locked_quantity >= quantity.
func (r *ProductRepository) LockInventory(ctx context.Context, skuID string, quantity int32, scope StoreScope) (*InventoryRecord, error) {
_ = scope
if err := requireWriteScope(scope); err != nil {
return nil, err
}
if quantity <= 0 {
return nil, fmt.Errorf("quantity must be positive")
}
@ -1556,8 +1602,9 @@ WHERE pi.id = $1
AND pi.is_archived = FALSE
AND pi.status = 1
AND p.deleted_at IS NULL
AND p.store_id = $2
FOR UPDATE OF p
`, id).Scan(&productID, &productStatus)
`, id, scope.StoreID).Scan(&productID, &productStatus)
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrSKUNotFound)
}
@ -1609,17 +1656,21 @@ RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, c
// ConfirmInventory converts locked stock to sold stock after payment succeeds.
func (r *ProductRepository) ConfirmInventory(ctx context.Context, orderID string, items []InventoryAdjustment, scope StoreScope) ([]*InventoryRecord, error) {
_ = scope
return r.applyInventoryAdjustments(ctx, orderID, "confirm", items)
if err := requireWriteScope(scope); err != nil {
return nil, err
}
return r.applyInventoryAdjustments(ctx, orderID, "confirm", items, scope)
}
// ReleaseInventory releases locked stock when a pending order is cancelled or expires.
func (r *ProductRepository) ReleaseInventory(ctx context.Context, orderID string, items []InventoryAdjustment, scope StoreScope) ([]*InventoryRecord, error) {
_ = scope
return r.applyInventoryAdjustments(ctx, orderID, "release", items)
if err := requireWriteScope(scope); err != nil {
return nil, err
}
return r.applyInventoryAdjustments(ctx, orderID, "release", items, scope)
}
func (r *ProductRepository) applyInventoryAdjustments(ctx context.Context, orderID, action string, items []InventoryAdjustment) ([]*InventoryRecord, error) {
func (r *ProductRepository) applyInventoryAdjustments(ctx context.Context, orderID, action string, items []InventoryAdjustment, scope StoreScope) ([]*InventoryRecord, error) {
parsedOrderID, err := parseID(orderID, "order id")
if err != nil {
return nil, err
@ -1641,6 +1692,19 @@ func (r *ProductRepository) applyInventoryAdjustments(ctx context.Context, order
if err != nil {
return nil, err
}
var owned int
err = tx.QueryRowContext(ctx, `
SELECT 1
FROM product.product_items pi
JOIN product.products p ON p.id = pi.product_id
WHERE pi.id = $1 AND p.store_id = $2 AND p.deleted_at IS NULL
`, skuID, scope.StoreID).Scan(&owned)
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("%s inventory %s: %w", action, formatID(skuID), ErrSKUNotFound)
}
if err != nil {
return nil, fmt.Errorf("verify %s inventory store %s: %w", action, formatID(skuID), err)
}
var inserted bool
err = tx.QueryRowContext(ctx, `
@ -1857,8 +1921,10 @@ WHERE id = $1 AND deleted_at IS NULL
// GetProduct loads an SPU and its SKU list by product ID.
func (r *ProductRepository) GetProduct(ctx context.Context, productID string, scope StoreScope) (*ProductRecord, []SKURecord, error) {
_ = scope
product, err := r.loadProductByID(ctx, productID)
if err := requireWriteScope(scope); err != nil {
return nil, nil, err
}
product, err := r.loadProductByID(ctx, productID, scope)
if err != nil {
return nil, nil, err
}
@ -1867,7 +1933,7 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string, sc
if err != nil {
return nil, nil, err
}
leafCategoryIDs, err := r.listProductLeafCategoryIDs(ctx, productID)
leafCategoryIDs, err := r.listProductLeafCategoryIDs(ctx, productID, scope)
if err != nil {
return nil, nil, err
}
@ -1878,17 +1944,21 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string, sc
// GetProductBySKU loads the SPU that owns skuID (product_items.id is the SKU PK).
func (r *ProductRepository) GetProductBySKU(ctx context.Context, skuID string, scope StoreScope) (*ProductRecord, []SKURecord, error) {
_ = scope
if err := requireWriteScope(scope); err != nil {
return nil, nil, err
}
parsedSKU, err := parseID(skuID, "sku_id")
if err != nil {
return nil, nil, err
}
var productID int64
err = r.db.QueryRowContext(ctx, `
SELECT product_id
FROM product.product_items
WHERE id = $1 AND deleted_at IS NULL AND is_archived = FALSE
`, parsedSKU).Scan(&productID)
SELECT pi.product_id
FROM product.product_items pi
JOIN product.products p ON p.id = pi.product_id
WHERE pi.id = $1 AND pi.deleted_at IS NULL AND pi.is_archived = FALSE
AND p.deleted_at IS NULL AND p.store_id = $2
`, parsedSKU, scope.StoreID).Scan(&productID)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil, ErrSKUNotFound
}
@ -1898,7 +1968,10 @@ WHERE id = $1 AND deleted_at IS NULL AND is_archived = FALSE
return r.GetProduct(ctx, formatID(productID), scope)
}
func (r *ProductRepository) listProductLeafCategoryIDs(ctx context.Context, productID string) ([]string, error) {
func (r *ProductRepository) listProductLeafCategoryIDs(ctx context.Context, productID string, scope StoreScope) ([]string, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
parsedProductID, err := parseID(productID, "product_id")
if err != nil {
return nil, err
@ -1910,8 +1983,9 @@ JOIN product.product_category AS c ON c.id = b.category_id
WHERE b.product_id = $1
AND c.node_type = 1
AND c.level = 2
AND c.store_id = $2
ORDER BY c.sort_num, c.id
`, parsedProductID)
`, parsedProductID, scope.StoreID)
if err != nil {
return nil, fmt.Errorf("list product leaf category ids: %w", err)
}
@ -1933,7 +2007,9 @@ ORDER BY c.sort_num, c.id
// BatchGetCartItemProducts loads current catalog facts for cart lines in request order.
// It includes archived SKUs, but treats soft-deleted SPUs and SKUs as unavailable.
func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookups []CartItemProductLookup, scope StoreScope) ([]CartItemProductRecord, error) {
_ = scope
if err := requireWriteScope(scope); err != nil {
return nil, err
}
if len(lookups) == 0 {
return []CartItemProductRecord{}, nil
}
@ -1959,7 +2035,7 @@ func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookup
}
}
products, err := r.loadProductsByIDs(ctx, productIDs)
products, err := r.loadProductsByIDs(ctx, productIDs, scope)
if err != nil {
return nil, err
}
@ -1993,7 +2069,9 @@ func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookup
// ListProducts loads paginated summaries for all non-deleted products.
func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int32, scope StoreScope) ([]*CategoryProductRecord, int64, error) {
_ = scope
if err := requireWriteScope(scope); err != nil {
return nil, 0, err
}
if page < 1 {
page = 1
}
@ -2005,8 +2083,8 @@ func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int
if err := r.db.QueryRowContext(ctx, `
SELECT COUNT(*)
FROM product.products
WHERE deleted_at IS NULL
`).Scan(&total); err != nil {
WHERE deleted_at IS NULL AND store_id = $1
`, scope.StoreID).Scan(&total); err != nil {
return nil, 0, fmt.Errorf("count products: %w", err)
}
if total == 0 {
@ -2038,10 +2116,10 @@ LEFT JOIN LATERAL (
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
) sku_summary ON TRUE
WHERE p.deleted_at IS NULL
WHERE p.deleted_at IS NULL AND p.store_id = $3
ORDER BY p.created_at DESC, p.id DESC
LIMIT $1 OFFSET $2
`, pageSize, offset)
`, pageSize, offset, scope.StoreID)
if err != nil {
return nil, 0, fmt.Errorf("query products: %w", err)
}
@ -2065,7 +2143,9 @@ LIMIT $1 OFFSET $2
// keyword. Callers cannot opt out of the visibility predicate: soft-deleted and
// inventory-only products must never be exposed by keyword search.
func (r *ProductRepository) SearchProducts(ctx context.Context, keyword string, page, pageSize int32, scope StoreScope) ([]*CategoryProductRecord, int64, error) {
_ = scope
if err := requireWriteScope(scope); err != nil {
return nil, 0, err
}
if page < 1 {
page = 1
}
@ -2084,9 +2164,10 @@ func (r *ProductRepository) SearchProducts(ctx context.Context, keyword string,
SELECT COUNT(*)
FROM product.products p
WHERE p.deleted_at IS NULL
AND p.store_id = $4
AND p.status IN ($2, $3)
AND p.title ILIKE $1 ESCAPE '\'
`, containsPattern, onSaleStatus, offSaleStatus).Scan(&total); err != nil {
`, containsPattern, onSaleStatus, offSaleStatus, scope.StoreID).Scan(&total); err != nil {
return nil, 0, fmt.Errorf("count searched products: %w", err)
}
if total == 0 {
@ -2119,6 +2200,7 @@ LEFT JOIN LATERAL (
AND pi.is_archived = FALSE
) sku_summary ON TRUE
WHERE p.deleted_at IS NULL
AND p.store_id = $8
AND p.status IN ($2, $3)
AND p.title ILIKE $1 ESCAPE '\'
ORDER BY CASE
@ -2129,7 +2211,7 @@ ORDER BY CASE
p.updated_at DESC,
p.id DESC
LIMIT $6 OFFSET $7
`, containsPattern, onSaleStatus, offSaleStatus, keyword, prefixPattern, pageSize, offset)
`, containsPattern, onSaleStatus, offSaleStatus, keyword, prefixPattern, pageSize, offset, scope.StoreID)
if err != nil {
return nil, 0, fmt.Errorf("query searched products: %w", err)
}
@ -2151,7 +2233,9 @@ LIMIT $6 OFFSET $7
// CountProducts returns aggregate product counts grouped by lifecycle status.
func (r *ProductRepository) CountProducts(ctx context.Context, scope StoreScope) (*ProductCountRecord, error) {
_ = scope
if err := requireWriteScope(scope); err != nil {
return nil, err
}
var counts ProductCountRecord
if err := r.db.QueryRowContext(ctx, `
SELECT COUNT(*) AS total,
@ -2161,7 +2245,8 @@ SELECT COUNT(*) AS total,
COUNT(*) FILTER (WHERE deleted_at IS NULL AND status = 3) AS off_sale,
COUNT(*) FILTER (WHERE deleted_at IS NOT NULL) AS deleted
FROM product.products
`).Scan(
WHERE store_id = $1
`, scope.StoreID).Scan(
&counts.Total,
&counts.Active,
&counts.Draft,
@ -2176,7 +2261,9 @@ FROM product.products
// ListCategoryProducts loads paginated product summaries for a category ID.
func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32, onlyVisible bool, scope StoreScope) ([]*CategoryProductRecord, int64, error) {
_ = scope
if err := requireWriteScope(scope); err != nil {
return nil, 0, err
}
parsedCategoryID, err := parseID(categoryID, "category id")
if err != nil {
return nil, 0, err
@ -2194,10 +2281,13 @@ func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID
SELECT COUNT(*)
FROM product.products p
JOIN product.product_category_bindings b ON b.product_id = p.id
JOIN product.product_category c ON c.id = b.category_id
WHERE b.category_id = $1
AND p.deleted_at IS NULL
AND p.store_id = $5
AND c.store_id = $5
AND ($2 = FALSE OR p.status IN ($3, $4))
`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE)).Scan(&total); err != nil {
`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID).Scan(&total); err != nil {
return nil, 0, fmt.Errorf("count category products: %w", err)
}
if total == 0 {
@ -2219,6 +2309,7 @@ SELECT p.updated_at,
COALESCE(sku_summary.locked_quantity, 0)
FROM product.products p
JOIN product.product_category_bindings b ON b.product_id = p.id
JOIN product.product_category c ON c.id = b.category_id
LEFT JOIN LATERAL (
SELECT MIN(pi.price) AS price,
SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity,
@ -2232,10 +2323,12 @@ LEFT JOIN LATERAL (
) sku_summary ON TRUE
WHERE b.category_id = $1
AND p.deleted_at IS NULL
AND p.store_id = $7
AND c.store_id = $7
AND ($2 = FALSE OR p.status IN ($5, $6))
ORDER BY p.created_at DESC, p.id DESC
LIMIT $3 OFFSET $4
`, parsedCategoryID, onlyVisible, pageSize, offset, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE))
`, parsedCategoryID, onlyVisible, pageSize, offset, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), scope.StoreID)
if err != nil {
return nil, 0, fmt.Errorf("query category products: %w", err)
}
@ -2257,7 +2350,9 @@ LIMIT $3 OFFSET $4
// ListCategoryTreeNodes loads product category nodes for storefront category trees.
func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool, scope StoreScope) ([]*CategoryRecord, error) {
_ = scope
if err := requireWriteScope(scope); err != nil {
return nil, err
}
rows, err := r.db.QueryContext(ctx, `
SELECT id,
node_type,
@ -2270,9 +2365,10 @@ SELECT id,
version
FROM product.product_category
WHERE node_type = 1
AND store_id = $2
AND ($1 = false OR status = 1)
ORDER BY level ASC, sort_num ASC, id ASC
`, onlyVisible)
`, onlyVisible, scope.StoreID)
if err != nil {
return nil, fmt.Errorf("query category tree nodes: %w", err)
}
@ -2295,7 +2391,9 @@ ORDER BY level ASC, sort_num ASC, id ASC
// ListGroupNodes loads product group nodes.
func (r *ProductRepository) ListGroupNodes(ctx context.Context, onlyVisible bool, scope StoreScope) ([]*CategoryRecord, error) {
_ = scope
if err := requireWriteScope(scope); err != nil {
return nil, err
}
rows, err := r.db.QueryContext(ctx, `
SELECT id,
node_type,
@ -2308,9 +2406,10 @@ SELECT id,
version
FROM product.product_category
WHERE node_type = 2
AND store_id = $2
AND ($1 = false OR status = 1)
ORDER BY sort_num ASC, id ASC
`, onlyVisible)
`, onlyVisible, scope.StoreID)
if err != nil {
return nil, fmt.Errorf("query group nodes: %w", err)
}
@ -2331,18 +2430,20 @@ ORDER BY sort_num ASC, id ASC
return groups, nil
}
func (r *ProductRepository) loadProductByID(ctx context.Context, productID string) (*ProductRecord, error) {
products, err := r.loadProductsByIDs(ctx, []string{productID})
func (r *ProductRepository) loadProductByID(ctx context.Context, productID string, scope StoreScope) (*ProductRecord, error) {
products, err := r.loadProductsByIDs(ctx, []string{productID}, scope)
if err != nil {
return nil, err
}
if len(products) == 0 {
return nil, ErrProductNotFound
}
return products[0], nil
product := products[0]
product.Scope = scope
return product, nil
}
func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs []string) ([]*ProductRecord, error) {
func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs []string, scope StoreScope) ([]*ProductRecord, error) {
placeholders := make([]string, len(productIDs))
args := make([]any, len(productIDs))
for i, id := range productIDs {
@ -2353,6 +2454,11 @@ func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs []
placeholders[i] = fmt.Sprintf("$%d", i+1)
args[i] = parsed
}
storeFilter := ""
if scope.Valid() {
args = append(args, scope.StoreID)
storeFilter = fmt.Sprintf(" AND store_id = $%d", len(args))
}
query := fmt.Sprintf(`
SELECT id,
@ -2379,9 +2485,9 @@ SELECT id,
updated_at
FROM product.products
WHERE id IN (%s)
AND deleted_at IS NULL
AND deleted_at IS NULL%s
ORDER BY created_at ASC
`, strings.Join(placeholders, ", "))
`, strings.Join(placeholders, ", "), storeFilter)
rows, err := r.db.QueryContext(ctx, query, args...)
if err != nil {
@ -2395,6 +2501,9 @@ ORDER BY created_at ASC
if err != nil {
return nil, err
}
if scope.Valid() {
product.Scope = scope
}
products = append(products, product)
}
if err := rows.Err(); err != nil {
@ -2405,6 +2514,9 @@ ORDER BY created_at ASC
}
func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs []byte) (*ProductRecord, error) {
if err := requireWriteScope(product.Scope); err != nil {
return nil, err
}
id, err := parseID(product.ID, "product id")
if err != nil {
return nil, err
@ -2424,6 +2536,8 @@ func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs
row := tx.QueryRowContext(ctx, `
INSERT INTO product.products (
id,
tenant_id,
store_id,
spu_no,
title,
selling_point,
@ -2442,7 +2556,7 @@ INSERT INTO product.products (
sale_time_type,
scheduled_sale_time
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13::jsonb, $14, $15, $16, $17, $18)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15::jsonb, $16, $17, $18, $19, $20)
RETURNING id,
spu_no,
title,
@ -2465,18 +2579,19 @@ RETURNING id,
deleted_at,
created_at,
updated_at
`, id, 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),
statusToDB(product.Status), attrs, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID,
int16(product.SaleTimeType), product.ScheduledSaleTime)
createdProduct, err := scanProduct(row)
if err != nil {
if isPostgresConstraintError(err, "23505", "uq_products_spu_no") {
if isPostgresConstraintError(err, "23505", "uq_products_store_spu_no") || isPostgresConstraintError(err, "23505", "uq_products_spu_no") {
return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, product.SPUNo)
}
return nil, fmt.Errorf("insert product: %w", err)
}
createdProduct.Scope = product.Scope
return createdProduct, nil
}
@ -2504,8 +2619,10 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord)
}
row := tx.QueryRowContext(ctx, `
INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status)
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8)
INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status, tenant_id, store_id)
SELECT $1, $2, $3, $4, $5, $6, $7::jsonb, $8, p.tenant_id, p.store_id
FROM product.products p
WHERE p.id = $2
RETURNING id,
product_id,
sku_no,
@ -2623,7 +2740,10 @@ ON CONFLICT (product_id, category_id) DO NOTHING
return nil
}
func insertCategoryNode(ctx context.Context, tx *sql.Tx, category CategoryRecord) (*CategoryRecord, error) {
func insertCategoryNode(ctx context.Context, tx *sql.Tx, category CategoryRecord, scope StoreScope) (*CategoryRecord, error) {
if err := requireWriteScope(scope); err != nil {
return nil, err
}
id, err := parseID(category.ID, "category id")
if err != nil {
return nil, err
@ -2641,6 +2761,8 @@ func insertCategoryNode(ctx context.Context, tx *sql.Tx, category CategoryRecord
row := tx.QueryRowContext(ctx, `
INSERT INTO product.product_category (
id,
tenant_id,
store_id,
node_type,
name,
parent_id,
@ -2649,7 +2771,7 @@ INSERT INTO product.product_category (
sort_num,
status
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING id,
node_type,
name,
@ -2659,7 +2781,7 @@ RETURNING id,
sort_num,
status,
version
`, id, int16(category.NodeType), category.Name, parentID, int16(category.Level), stringSliceOrEmpty(category.ImageIDs), category.SortNum, int16(category.Status))
`, id, scope.TenantID, scope.StoreID, int16(category.NodeType), category.Name, parentID, int16(category.Level), stringSliceOrEmpty(category.ImageIDs), category.SortNum, int16(category.Status))
createdCategory, err := scanCategory(row)
if err != nil {

View File

@ -37,3 +37,10 @@ func TestAggregateInventoryAdjustmentsRejectsInvalidSKUID(t *testing.T) {
t.Fatal("expected invalid sku id error")
}
}
func TestReplaceProductLeafCategoryBindingsRequiresStoreScope(t *testing.T) {
err := replaceProductLeafCategoryBindings(nil, nil, "1001", []string{"2001"}, []string{"3001"}, StoreScope{})
if err != ErrStoreScopeRequired {
t.Fatalf("err = %v, want %v", err, ErrStoreScopeRequired)
}
}

View File

@ -1,8 +1,24 @@
package repository
import "errors"
// ErrStoreScopeRequired is returned when a store-scoped write or list has no shop.
var ErrStoreScopeRequired = errors.New("store scope is required")
// StoreScope identifies the shop for a repository call.
// Batch 2 accepts it on Create/Get/List inputs without filtering or persisting store columns.
type StoreScope struct {
TenantID int64
StoreID int64
}
// Valid reports whether both tenant and store identifiers are present.
func (s StoreScope) Valid() bool {
return s.TenantID > 0 && s.StoreID > 0
}
func requireWriteScope(scope StoreScope) error {
if !scope.Valid() {
return ErrStoreScopeRequired
}
return nil
}

View File

@ -0,0 +1,33 @@
package repository
import (
"testing"
"github.com/jackc/pgx/v5/pgconn"
)
func TestStoreScopeValid(t *testing.T) {
if (StoreScope{}).Valid() {
t.Fatal("empty scope must be invalid")
}
if !(StoreScope{TenantID: 1, StoreID: 2}).Valid() {
t.Fatal("complete scope must be valid")
}
}
func TestRequireWriteScope(t *testing.T) {
if err := requireWriteScope(StoreScope{}); err != ErrStoreScopeRequired {
t.Fatalf("empty scope err = %v", err)
}
}
func TestDuplicateSPUNoConstraintNames(t *testing.T) {
old := &pgconn.PgError{Code: "23505", ConstraintName: "uq_products_spu_no"}
if !isPostgresConstraintError(old, "23505", "uq_products_spu_no") {
t.Fatal("old spu unique name must match")
}
next := &pgconn.PgError{Code: "23505", ConstraintName: "uq_products_store_spu_no"}
if !isPostgresConstraintError(next, "23505", "uq_products_store_spu_no") {
t.Fatal("store-scoped spu unique name must match")
}
}