feat(store): implement StoreScope for multi-tenant support and update product methods to require store context

This commit is contained in:
robinj0726 2026-09-12 19:02:07 +08:00
parent ec0184c377
commit a8a3464484
6 changed files with 252 additions and 53 deletions

View File

@ -82,6 +82,8 @@ type ProductRecord struct {
DeletedAt *time.Time DeletedAt *time.Time
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
// Scope is accepted for Create/Get/List plumbing. Not persisted until store columns exist.
Scope StoreScope
} }
// ProductCountRecord contains aggregate counts for product.products. // ProductCountRecord contains aggregate counts for product.products.
@ -192,6 +194,7 @@ type ProductUpdateInput struct {
// non-nil empty slice clears all leaf-category bindings. // non-nil empty slice clears all leaf-category bindings.
LeafCategoryIDs *[]string LeafCategoryIDs *[]string
CategoryBindingIDs []string CategoryBindingIDs []string
Scope StoreScope
} }
// CategoryDeleteResult summarizes a destructive category deletion. // CategoryDeleteResult summarizes a destructive category deletion.
@ -413,6 +416,7 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe
// CreateProductWithSKUs inserts an SPU and its optional SKU list in one transaction. // 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) { func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product ProductRecord, skus []SKURecord) (*ProductRecord, []SKURecord, error) {
_ = product.Scope
attrs, err := productCrossBorderJSON(product) attrs, err := productCrossBorderJSON(product)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@ -452,7 +456,8 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P
} }
// CreateCategoryTree inserts a top-level category and its optional child categories in one transaction. // 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) (*CategoryRecord, []*CategoryRecord, error) { func (r *ProductRepository) CreateCategoryTree(ctx context.Context, parent CategoryRecord, children []CategoryRecord, scope StoreScope) (*CategoryRecord, []*CategoryRecord, error) {
_ = scope
tx, err := r.db.BeginTx(ctx, nil) tx, err := r.db.BeginTx(ctx, nil)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("begin create category tree: %w", err) return nil, nil, fmt.Errorf("begin create category tree: %w", err)
@ -485,7 +490,8 @@ func (r *ProductRepository) CreateCategoryTree(ctx context.Context, parent Categ
} }
// CreateCategoryNode inserts a single product category/group node. // CreateCategoryNode inserts a single product category/group node.
func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category CategoryRecord) (*CategoryRecord, error) { func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category CategoryRecord, scope StoreScope) (*CategoryRecord, error) {
_ = scope
tx, err := r.db.BeginTx(ctx, nil) tx, err := r.db.BeginTx(ctx, nil)
if err != nil { if err != nil {
return nil, fmt.Errorf("begin create category node: %w", err) return nil, fmt.Errorf("begin create category node: %w", err)
@ -504,7 +510,8 @@ func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category Cat
// UpdateCategoryTrees applies all requested root and direct-child patches in a // UpdateCategoryTrees applies all requested root and direct-child patches in a
// single transaction. Callers must supply already-validated patch fields. // single transaction. Callers must supply already-validated patch fields.
func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []CategoryTreeUpdate) error { func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []CategoryTreeUpdate, scope StoreScope) error {
_ = scope
if len(updates) == 0 { if len(updates) == 0 {
return errors.New("category_trees is required") return errors.New("category_trees is required")
} }
@ -560,7 +567,8 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C
// DeleteCategory removes a leaf category or a complete top-level category tree // DeleteCategory removes a leaf category or a complete top-level category tree
// and all affected product bindings in one transaction. Product rows and group // and all affected product bindings in one transaction. Product rows and group
// bindings are deliberately retained. // bindings are deliberately retained.
func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID string, expectedVersion int32) (*CategoryDeleteResult, error) { func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID string, expectedVersion int32, scope StoreScope) (*CategoryDeleteResult, error) {
_ = scope
if expectedVersion < 0 { if expectedVersion < 0 {
return nil, errors.New("expected_version must be non-negative") return nil, errors.New("expected_version must be non-negative")
} }
@ -741,7 +749,8 @@ func pointerStringSlice(value *[]string) []string {
// AddProductsToGroup binds every product to the requested category or product group in one transaction. // AddProductsToGroup binds every product to the requested category or product group in one transaction.
// Existing bindings are retained and duplicate bindings are ignored. // Existing bindings are retained and duplicate bindings are ignored.
func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID string, bindingIDs, productIDs []string) error { func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID string, bindingIDs, productIDs []string, scope StoreScope) error {
_ = scope
if len(productIDs) == 0 { if len(productIDs) == 0 {
return errors.New("product_ids is required") return errors.New("product_ids is required")
} }
@ -844,7 +853,8 @@ ON CONFLICT (product_id, category_id) DO NOTHING
// RemoveProductsFromGroup removes product bindings from the requested category or product group in one transaction. // 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. // Missing bindings are ignored so callers can safely retry the same request.
func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID string, productIDs []string) error { func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID string, productIDs []string, scope StoreScope) error {
_ = scope
if len(productIDs) == 0 { if len(productIDs) == 0 {
return errors.New("product_ids is required") return errors.New("product_ids is required")
} }
@ -937,6 +947,7 @@ WHERE id = $1
// UpdateProductWithSKUChange atomically persists a merged SPU update and an optional SKU operation. // UpdateProductWithSKUChange atomically persists a merged SPU update and an optional SKU operation.
func (r *ProductRepository) UpdateProductWithSKUChange(ctx context.Context, input ProductUpdateInput) (*SKUChangeResult, error) { func (r *ProductRepository) UpdateProductWithSKUChange(ctx context.Context, input ProductUpdateInput) (*SKUChangeResult, error) {
_ = input.Scope
if input.ExpectedVersion < 0 { if input.ExpectedVersion < 0 {
return nil, fmt.Errorf("expected product version must be non-negative") return nil, fmt.Errorf("expected product version must be non-negative")
} }
@ -1145,7 +1156,8 @@ WHERE b.product_id = $1
} }
// UpdateProductStatus changes the product lifecycle state using optimistic locking. // UpdateProductStatus changes the product lifecycle state using optimistic locking.
func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID string, next productv1.ProductStatus, expectedVersion int32) (*ProductStatusUpdate, error) { func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID string, next productv1.ProductStatus, expectedVersion int32, scope StoreScope) (*ProductStatusUpdate, error) {
_ = scope
if expectedVersion < 0 { if expectedVersion < 0 {
return nil, fmt.Errorf("expected product version must be non-negative") return nil, fmt.Errorf("expected product version must be non-negative")
} }
@ -1517,7 +1529,8 @@ WHERE id = $1 AND is_archived = FALSE
} }
// LockInventory atomically reserves quantity when stock_quantity - locked_quantity >= quantity. // LockInventory atomically reserves quantity when stock_quantity - locked_quantity >= quantity.
func (r *ProductRepository) LockInventory(ctx context.Context, skuID string, quantity int32) (*InventoryRecord, error) { func (r *ProductRepository) LockInventory(ctx context.Context, skuID string, quantity int32, scope StoreScope) (*InventoryRecord, error) {
_ = scope
if quantity <= 0 { if quantity <= 0 {
return nil, fmt.Errorf("quantity must be positive") return nil, fmt.Errorf("quantity must be positive")
} }
@ -1595,12 +1608,14 @@ RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, c
} }
// ConfirmInventory converts locked stock to sold stock after payment succeeds. // ConfirmInventory converts locked stock to sold stock after payment succeeds.
func (r *ProductRepository) ConfirmInventory(ctx context.Context, orderID string, items []InventoryAdjustment) ([]*InventoryRecord, error) { func (r *ProductRepository) ConfirmInventory(ctx context.Context, orderID string, items []InventoryAdjustment, scope StoreScope) ([]*InventoryRecord, error) {
_ = scope
return r.applyInventoryAdjustments(ctx, orderID, "confirm", items) return r.applyInventoryAdjustments(ctx, orderID, "confirm", items)
} }
// ReleaseInventory releases locked stock when a pending order is cancelled or expires. // ReleaseInventory releases locked stock when a pending order is cancelled or expires.
func (r *ProductRepository) ReleaseInventory(ctx context.Context, orderID string, items []InventoryAdjustment) ([]*InventoryRecord, error) { func (r *ProductRepository) ReleaseInventory(ctx context.Context, orderID string, items []InventoryAdjustment, scope StoreScope) ([]*InventoryRecord, error) {
_ = scope
return r.applyInventoryAdjustments(ctx, orderID, "release", items) return r.applyInventoryAdjustments(ctx, orderID, "release", items)
} }
@ -1841,7 +1856,8 @@ WHERE id = $1 AND deleted_at IS NULL
} }
// GetProduct loads an SPU and its SKU list by product ID. // GetProduct loads an SPU and its SKU list by product ID.
func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (*ProductRecord, []SKURecord, error) { func (r *ProductRepository) GetProduct(ctx context.Context, productID string, scope StoreScope) (*ProductRecord, []SKURecord, error) {
_ = scope
product, err := r.loadProductByID(ctx, productID) product, err := r.loadProductByID(ctx, productID)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@ -1861,7 +1877,8 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (*
} }
// GetProductBySKU loads the SPU that owns skuID (product_items.id is the SKU PK). // GetProductBySKU loads the SPU that owns skuID (product_items.id is the SKU PK).
func (r *ProductRepository) GetProductBySKU(ctx context.Context, skuID string) (*ProductRecord, []SKURecord, error) { func (r *ProductRepository) GetProductBySKU(ctx context.Context, skuID string, scope StoreScope) (*ProductRecord, []SKURecord, error) {
_ = scope
parsedSKU, err := parseID(skuID, "sku_id") parsedSKU, err := parseID(skuID, "sku_id")
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@ -1878,7 +1895,7 @@ WHERE id = $1 AND deleted_at IS NULL AND is_archived = FALSE
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("lookup product by sku: %w", err) return nil, nil, fmt.Errorf("lookup product by sku: %w", err)
} }
return r.GetProduct(ctx, formatID(productID)) 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) ([]string, error) {
@ -1915,7 +1932,8 @@ ORDER BY c.sort_num, c.id
// BatchGetCartItemProducts loads current catalog facts for cart lines in request order. // BatchGetCartItemProducts loads current catalog facts for cart lines in request order.
// It includes archived SKUs, but treats soft-deleted SPUs and SKUs as unavailable. // It includes archived SKUs, but treats soft-deleted SPUs and SKUs as unavailable.
func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookups []CartItemProductLookup) ([]CartItemProductRecord, error) { func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookups []CartItemProductLookup, scope StoreScope) ([]CartItemProductRecord, error) {
_ = scope
if len(lookups) == 0 { if len(lookups) == 0 {
return []CartItemProductRecord{}, nil return []CartItemProductRecord{}, nil
} }
@ -1974,7 +1992,8 @@ func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookup
} }
// ListProducts loads paginated summaries for all non-deleted products. // ListProducts loads paginated summaries for all non-deleted products.
func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int32) ([]*CategoryProductRecord, int64, error) { func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int32, scope StoreScope) ([]*CategoryProductRecord, int64, error) {
_ = scope
if page < 1 { if page < 1 {
page = 1 page = 1
} }
@ -2045,7 +2064,8 @@ LIMIT $1 OFFSET $2
// SearchProducts loads storefront-visible product summaries whose titles contain // SearchProducts loads storefront-visible product summaries whose titles contain
// keyword. Callers cannot opt out of the visibility predicate: soft-deleted and // keyword. Callers cannot opt out of the visibility predicate: soft-deleted and
// inventory-only products must never be exposed by keyword search. // inventory-only products must never be exposed by keyword search.
func (r *ProductRepository) SearchProducts(ctx context.Context, keyword string, page, pageSize int32) ([]*CategoryProductRecord, int64, error) { func (r *ProductRepository) SearchProducts(ctx context.Context, keyword string, page, pageSize int32, scope StoreScope) ([]*CategoryProductRecord, int64, error) {
_ = scope
if page < 1 { if page < 1 {
page = 1 page = 1
} }
@ -2130,7 +2150,8 @@ LIMIT $6 OFFSET $7
} }
// CountProducts returns aggregate product counts grouped by lifecycle status. // CountProducts returns aggregate product counts grouped by lifecycle status.
func (r *ProductRepository) CountProducts(ctx context.Context) (*ProductCountRecord, error) { func (r *ProductRepository) CountProducts(ctx context.Context, scope StoreScope) (*ProductCountRecord, error) {
_ = scope
var counts ProductCountRecord var counts ProductCountRecord
if err := r.db.QueryRowContext(ctx, ` if err := r.db.QueryRowContext(ctx, `
SELECT COUNT(*) AS total, SELECT COUNT(*) AS total,
@ -2154,7 +2175,8 @@ FROM product.products
} }
// ListCategoryProducts loads paginated product summaries for a category ID. // ListCategoryProducts loads paginated product summaries for a category ID.
func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32, onlyVisible bool) ([]*CategoryProductRecord, int64, error) { func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32, onlyVisible bool, scope StoreScope) ([]*CategoryProductRecord, int64, error) {
_ = scope
parsedCategoryID, err := parseID(categoryID, "category id") parsedCategoryID, err := parseID(categoryID, "category id")
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
@ -2234,7 +2256,8 @@ LIMIT $3 OFFSET $4
} }
// 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) ([]*CategoryRecord, error) { func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool, scope StoreScope) ([]*CategoryRecord, error) {
_ = scope
rows, err := r.db.QueryContext(ctx, ` rows, err := r.db.QueryContext(ctx, `
SELECT id, SELECT id,
node_type, node_type,
@ -2271,7 +2294,8 @@ ORDER BY level ASC, sort_num ASC, id ASC
} }
// ListGroupNodes loads product group nodes. // ListGroupNodes loads product group nodes.
func (r *ProductRepository) ListGroupNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) { func (r *ProductRepository) ListGroupNodes(ctx context.Context, onlyVisible bool, scope StoreScope) ([]*CategoryRecord, error) {
_ = scope
rows, err := r.db.QueryContext(ctx, ` rows, err := r.db.QueryContext(ctx, `
SELECT id, SELECT id,
node_type, node_type,

View File

@ -0,0 +1,8 @@
package repository
// 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
}

View File

@ -10,10 +10,10 @@ import (
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
) )
func TestGetProductBySkuRequiresID(t *testing.T) { func TestGetProductBySkuRequiresIDWithoutStoreIsFailedPrecondition(t *testing.T) {
s := NewProductServer(nil, nil, nil, nil) s := NewProductServer(nil, nil, nil, nil)
_, err := s.GetProductBySku(context.Background(), &productv1.GetProductBySkuRequest{}) _, err := s.GetProductBySku(context.Background(), &productv1.GetProductBySkuRequest{})
if status.Code(err) != codes.InvalidArgument { if status.Code(err) != codes.FailedPrecondition {
t.Fatalf("err = %v", err) t.Fatalf("err = %v, want FailedPrecondition", err)
} }
} }

View File

@ -74,11 +74,16 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") return nil, status.Error(codes.InvalidArgument, "request is required")
} }
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
product, skus, err := productFromCreateRequest(req) product, skus, err := productFromCreateRequest(req)
if err != nil { if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error()) return nil, status.Error(codes.InvalidArgument, err.Error())
} }
product.Scope = scope
if s.idgen == nil { if s.idgen == nil {
return nil, status.Error(codes.Internal, "id generator is not configured") return nil, status.Error(codes.Internal, "id generator is not configured")
} }
@ -133,14 +138,18 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
// GetProduct returns a single SPU and its SKU list. // GetProduct returns a single SPU and its SKU list.
func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProductRequest) (*productv1.GetProductResponse, error) { func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProductRequest) (*productv1.GetProductResponse, error) {
if req == nil || req.GetProductId() == "" { scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if req.GetProductId() == "" {
return nil, status.Error(codes.InvalidArgument, "product_id is required") return nil, status.Error(codes.InvalidArgument, "product_id is required")
} }
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.load", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.load", trace.WithAttributes(attribute.String("product.id", req.GetProductId())))
defer dbSpan.End() defer dbSpan.End()
product, skus, err := s.repo.GetProduct(dbCtx, req.GetProductId()) product, skus, err := s.repo.GetProduct(dbCtx, req.GetProductId(), scope)
if errors.Is(err, repository.ErrProductNotFound) { if errors.Is(err, repository.ErrProductNotFound) {
dbSpan.SetStatus(otelcodes.Error, "product not found") dbSpan.SetStatus(otelcodes.Error, "product not found")
return nil, status.Error(codes.NotFound, "product not found") return nil, status.Error(codes.NotFound, "product not found")
@ -159,7 +168,11 @@ func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProduc
// GetProductBySku returns the SPU that owns the SKU. // GetProductBySku returns the SPU that owns the SKU.
func (s *ProductServer) GetProductBySku(ctx context.Context, req *productv1.GetProductBySkuRequest) (*productv1.GetProductResponse, error) { func (s *ProductServer) GetProductBySku(ctx context.Context, req *productv1.GetProductBySkuRequest) (*productv1.GetProductResponse, error) {
if req == nil || req.GetSkuId() == "" { scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if req.GetSkuId() == "" {
return nil, status.Error(codes.InvalidArgument, "sku_id is required") return nil, status.Error(codes.InvalidArgument, "sku_id is required")
} }
if err := validatePositiveID(req.GetSkuId(), "sku_id"); err != nil { if err := validatePositiveID(req.GetSkuId(), "sku_id"); err != nil {
@ -169,7 +182,7 @@ func (s *ProductServer) GetProductBySku(ctx context.Context, req *productv1.GetP
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.load_by_sku", trace.WithAttributes(attribute.String("sku.id", req.GetSkuId()))) dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.load_by_sku", trace.WithAttributes(attribute.String("sku.id", req.GetSkuId())))
defer dbSpan.End() defer dbSpan.End()
product, skus, err := s.repo.GetProductBySKU(dbCtx, req.GetSkuId()) product, skus, err := s.repo.GetProductBySKU(dbCtx, req.GetSkuId(), scope)
if errors.Is(err, repository.ErrSKUNotFound) { if errors.Is(err, repository.ErrSKUNotFound) {
dbSpan.SetStatus(otelcodes.Error, "sku not found") dbSpan.SetStatus(otelcodes.Error, "sku not found")
return nil, status.Error(codes.NotFound, "sku not found") return nil, status.Error(codes.NotFound, "sku not found")
@ -194,6 +207,10 @@ func (s *ProductServer) GetProductBySku(ctx context.Context, req *productv1.GetP
// Missing and soft-deleted records are represented by their default invalid state rather // Missing and soft-deleted records are represented by their default invalid state rather
// than failing the whole batch; malformed requests still return InvalidArgument. // than failing the whole batch; malformed requests still return InvalidArgument.
func (s *ProductServer) BatchGetCartItemProduct(ctx context.Context, req *productv1.BatchGetCartItemProductRequest) (*productv1.BatchGetCartItemProductResponse, error) { func (s *ProductServer) BatchGetCartItemProduct(ctx context.Context, req *productv1.BatchGetCartItemProductRequest) (*productv1.BatchGetCartItemProductResponse, error) {
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if req == nil || len(req.GetItems()) == 0 { if req == nil || len(req.GetItems()) == 0 {
return nil, status.Error(codes.InvalidArgument, "items is required") return nil, status.Error(codes.InvalidArgument, "items is required")
} }
@ -234,7 +251,7 @@ func (s *ProductServer) BatchGetCartItemProduct(ctx context.Context, req *produc
)) ))
defer dbSpan.End() defer dbSpan.End()
records, err := s.repo.BatchGetCartItemProducts(dbCtx, lookups) records, err := s.repo.BatchGetCartItemProducts(dbCtx, lookups, scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -258,14 +275,18 @@ func (s *ProductServer) BatchGetCartItemProduct(ctx context.Context, req *produc
// UpdateProduct updates mutable SPU fields and optionally patches or replaces its SKU set. // UpdateProduct updates mutable SPU fields and optionally patches or replaces its SKU set.
func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.UpdateProductRequest) (*productv1.UpdateProductResponse, error) { func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.UpdateProductRequest) (*productv1.UpdateProductResponse, error) {
if req == nil || req.GetProductId() == "" { scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if req.GetProductId() == "" {
return nil, status.Error(codes.InvalidArgument, "product_id is required") return nil, status.Error(codes.InvalidArgument, "product_id is required")
} }
if req.GetExpectedVersion() < 0 { if req.GetExpectedVersion() < 0 {
return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative") return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative")
} }
current, _, err := s.repo.GetProduct(ctx, req.GetProductId()) current, _, err := s.repo.GetProduct(ctx, req.GetProductId(), scope)
if errors.Is(err, repository.ErrProductNotFound) { if errors.Is(err, repository.ErrProductNotFound) {
return nil, status.Error(codes.NotFound, "product not found") return nil, status.Error(codes.NotFound, "product not found")
} }
@ -308,6 +329,7 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update
SKUChange: skuChange, SKUChange: skuChange,
LeafCategoryIDs: leafCategoryIDs, LeafCategoryIDs: leafCategoryIDs,
CategoryBindingIDs: categoryBindingIDs, CategoryBindingIDs: categoryBindingIDs,
Scope: scope,
}) })
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
@ -329,7 +351,7 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update
} }
} }
updated, skus, err := s.repo.GetProduct(ctx, req.GetProductId()) updated, skus, err := s.repo.GetProduct(ctx, req.GetProductId(), scope)
if err != nil { if err != nil {
return nil, status.Errorf(codes.Internal, "load updated product: %v", err) return nil, status.Errorf(codes.Internal, "load updated product: %v", err)
} }
@ -341,12 +363,16 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update
// UpdateProductStatus changes the product lifecycle status. // UpdateProductStatus changes the product lifecycle status.
func (s *ProductServer) UpdateProductStatus(ctx context.Context, req *productv1.UpdateProductStatusRequest) (*productv1.UpdateProductStatusResponse, error) { func (s *ProductServer) UpdateProductStatus(ctx context.Context, req *productv1.UpdateProductStatusRequest) (*productv1.UpdateProductStatusResponse, error) {
if req == nil || req.GetProductId() == "" { scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if req.GetProductId() == "" {
return nil, status.Error(codes.InvalidArgument, "product_id is required") return nil, status.Error(codes.InvalidArgument, "product_id is required")
} }
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.status.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.status.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId())))
defer dbSpan.End() defer dbSpan.End()
updated, err := s.repo.UpdateProductStatus(dbCtx, req.GetProductId(), req.GetStatus(), req.GetExpectedVersion()) updated, err := s.repo.UpdateProductStatus(dbCtx, req.GetProductId(), req.GetStatus(), req.GetExpectedVersion(), scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -370,6 +396,10 @@ func (s *ProductServer) UpdateProductStatus(ctx context.Context, req *productv1.
// ListProducts returns a paginated list of all non-deleted products. // ListProducts returns a paginated list of all non-deleted products.
func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListProductsRequest) (*productv1.ListProductsResponse, error) { func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListProductsRequest) (*productv1.ListProductsResponse, error) {
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize()) page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize())
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list", trace.WithAttributes( dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list", trace.WithAttributes(
@ -378,7 +408,7 @@ func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListPro
)) ))
defer dbSpan.End() defer dbSpan.End()
products, total, err := s.repo.ListProducts(dbCtx, page, pageSize) products, total, err := s.repo.ListProducts(dbCtx, page, pageSize, scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -409,6 +439,10 @@ func (s *ProductServer) SearchProducts(ctx context.Context, req *productv1.Searc
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") return nil, status.Error(codes.InvalidArgument, "request is required")
} }
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
keyword := strings.TrimSpace(req.GetKeyword()) keyword := strings.TrimSpace(req.GetKeyword())
keywordLength := utf8.RuneCountInString(keyword) keywordLength := utf8.RuneCountInString(keyword)
@ -424,7 +458,7 @@ func (s *ProductServer) SearchProducts(ctx context.Context, req *productv1.Searc
)) ))
defer dbSpan.End() defer dbSpan.End()
products, total, err := s.repo.SearchProducts(dbCtx, keyword, page, pageSize) products, total, err := s.repo.SearchProducts(dbCtx, keyword, page, pageSize, scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -450,7 +484,11 @@ func (s *ProductServer) SearchProducts(ctx context.Context, req *productv1.Searc
// ListCategoryProducts returns a paginated product list under a category. // ListCategoryProducts returns a paginated product list under a category.
func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1.ListCategoryProductsRequest) (*productv1.ListCategoryProductsResponse, error) { func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1.ListCategoryProductsRequest) (*productv1.ListCategoryProductsResponse, error) {
if req == nil || req.GetCategoryId() == "" { scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if req.GetCategoryId() == "" {
return nil, status.Error(codes.InvalidArgument, "category_id is required") return nil, status.Error(codes.InvalidArgument, "category_id is required")
} }
categoryID, err := strconv.ParseInt(req.GetCategoryId(), 10, 64) categoryID, err := strconv.ParseInt(req.GetCategoryId(), 10, 64)
@ -467,7 +505,7 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1
)) ))
defer dbSpan.End() defer dbSpan.End()
products, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize, req.GetOnlyVisible()) products, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize, req.GetOnlyVisible(), scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -506,10 +544,14 @@ func normalizedPage(page, pageSize int32) (int32, int32) {
// CountProducts returns product counts grouped by lifecycle status. // CountProducts returns product counts grouped by lifecycle status.
func (s *ProductServer) CountProducts(ctx context.Context, req *productv1.CountProductsRequest) (*productv1.CountProductsResponse, error) { func (s *ProductServer) CountProducts(ctx context.Context, req *productv1.CountProductsRequest) (*productv1.CountProductsResponse, error) {
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.count") dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.count")
defer dbSpan.End() defer dbSpan.End()
counts, err := s.repo.CountProducts(dbCtx) counts, err := s.repo.CountProducts(dbCtx, scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -529,6 +571,10 @@ func (s *ProductServer) CountProducts(ctx context.Context, req *productv1.CountP
// ListCategoryTree returns product category nodes as a parent-child hierarchy. // ListCategoryTree returns product category nodes as a parent-child hierarchy.
func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.ListCategoryTreeRequest) (*productv1.ListCategoryTreeResponse, error) { func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.ListCategoryTreeRequest) (*productv1.ListCategoryTreeResponse, error) {
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
onlyVisible := false onlyVisible := false
if req != nil { if req != nil {
onlyVisible = req.GetOnlyVisible() onlyVisible = req.GetOnlyVisible()
@ -539,7 +585,7 @@ func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.Lis
)) ))
defer dbSpan.End() defer dbSpan.End()
categories, err := s.repo.ListCategoryTreeNodes(dbCtx, onlyVisible) categories, err := s.repo.ListCategoryTreeNodes(dbCtx, onlyVisible, scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -566,6 +612,10 @@ func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.C
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") return nil, status.Error(codes.InvalidArgument, "request is required")
} }
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if s.idgen == nil { if s.idgen == nil {
return nil, status.Error(codes.Internal, "id generator is not configured") return nil, status.Error(codes.Internal, "id generator is not configured")
} }
@ -585,7 +635,7 @@ func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.C
)) ))
defer dbSpan.End() defer dbSpan.End()
createdParent, createdChildren, err := s.repo.CreateCategoryTree(dbCtx, parent, children) createdParent, createdChildren, err := s.repo.CreateCategoryTree(dbCtx, parent, children, scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -608,6 +658,10 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1.
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") return nil, status.Error(codes.InvalidArgument, "request is required")
} }
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
updates, rootIDs, err := categoryTreeUpdatesFromRequest(req) updates, rootIDs, err := categoryTreeUpdatesFromRequest(req)
if err != nil { if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error()) return nil, status.Error(codes.InvalidArgument, err.Error())
@ -622,7 +676,7 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1.
} }
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category_trees.update", trace.WithAttributes(attribute.Int("category.tree_count", len(updates)))) dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category_trees.update", trace.WithAttributes(attribute.Int("category.tree_count", len(updates))))
defer dbSpan.End() defer dbSpan.End()
if err := s.repo.UpdateCategoryTrees(dbCtx, updates); err != nil { if err := s.repo.UpdateCategoryTrees(dbCtx, updates, scope); err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
switch { switch {
@ -637,7 +691,7 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1.
return nil, status.Error(codes.Internal, "update category trees") return nil, status.Error(codes.Internal, "update category trees")
} }
} }
all, err := s.repo.ListCategoryTreeNodes(dbCtx, false) all, err := s.repo.ListCategoryTreeNodes(dbCtx, false, scope)
if err != nil { if err != nil {
return nil, status.Error(codes.Internal, "load updated category trees") return nil, status.Error(codes.Internal, "load updated category trees")
} }
@ -662,6 +716,10 @@ func (s *ProductServer) DeleteCategory(ctx context.Context, req *productv1.Delet
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") return nil, status.Error(codes.InvalidArgument, "request is required")
} }
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
categoryID, err := normalizeCategoryID(req.GetCategoryId(), "category_id") categoryID, err := normalizeCategoryID(req.GetCategoryId(), "category_id")
if err != nil { if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error()) return nil, status.Error(codes.InvalidArgument, err.Error())
@ -671,7 +729,7 @@ func (s *ProductServer) DeleteCategory(ctx context.Context, req *productv1.Delet
} }
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category.delete", trace.WithAttributes(attribute.String("category.id", categoryID))) dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category.delete", trace.WithAttributes(attribute.String("category.id", categoryID)))
defer dbSpan.End() defer dbSpan.End()
result, err := s.repo.DeleteCategory(dbCtx, categoryID, req.GetExpectedVersion()) result, err := s.repo.DeleteCategory(dbCtx, categoryID, req.GetExpectedVersion(), scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -701,6 +759,10 @@ func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGr
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") return nil, status.Error(codes.InvalidArgument, "request is required")
} }
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if s.idgen == nil { if s.idgen == nil {
return nil, status.Error(codes.Internal, "id generator is not configured") return nil, status.Error(codes.Internal, "id generator is not configured")
} }
@ -716,7 +778,7 @@ func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGr
)) ))
defer dbSpan.End() defer dbSpan.End()
createdGroup, err := s.repo.CreateCategoryNode(dbCtx, group) createdGroup, err := s.repo.CreateCategoryNode(dbCtx, group, scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -731,6 +793,10 @@ func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGr
// ListGroups returns product groups. // ListGroups returns product groups.
func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroupsRequest) (*productv1.ListGroupsResponse, error) { func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroupsRequest) (*productv1.ListGroupsResponse, error) {
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
onlyVisible := false onlyVisible := false
if req != nil { if req != nil {
onlyVisible = req.GetOnlyVisible() onlyVisible = req.GetOnlyVisible()
@ -741,7 +807,7 @@ func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroup
)) ))
defer dbSpan.End() defer dbSpan.End()
groups, err := s.repo.ListGroupNodes(dbCtx, onlyVisible) groups, err := s.repo.ListGroupNodes(dbCtx, onlyVisible, scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -765,6 +831,10 @@ func (s *ProductServer) AddProductsToGroup(ctx context.Context, req *productv1.A
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") return nil, status.Error(codes.InvalidArgument, "request is required")
} }
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if s.idgen == nil { if s.idgen == nil {
return nil, status.Error(codes.Internal, "id generator is not configured") return nil, status.Error(codes.Internal, "id generator is not configured")
} }
@ -789,7 +859,7 @@ func (s *ProductServer) AddProductsToGroup(ctx context.Context, req *productv1.A
)) ))
defer dbSpan.End() defer dbSpan.End()
if err := s.repo.AddProductsToGroup(dbCtx, groupID, bindingIDs, productIDs); err != nil { if err := s.repo.AddProductsToGroup(dbCtx, groupID, bindingIDs, productIDs, scope); err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
s.observer.Logger(ctx).Error("add products to group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err)) s.observer.Logger(ctx).Error("add products to group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err))
@ -809,6 +879,10 @@ func (s *ProductServer) RemoveProductsFromGroup(ctx context.Context, req *produc
if req == nil { if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required") return nil, status.Error(codes.InvalidArgument, "request is required")
} }
scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
groupID := strings.TrimSpace(req.GetGroupId()) groupID := strings.TrimSpace(req.GetGroupId())
if err := validatePositiveSnowflakeID(groupID, "group_id"); err != nil { if err := validatePositiveSnowflakeID(groupID, "group_id"); err != nil {
@ -825,7 +899,7 @@ func (s *ProductServer) RemoveProductsFromGroup(ctx context.Context, req *produc
)) ))
defer dbSpan.End() defer dbSpan.End()
if err := s.repo.RemoveProductsFromGroup(dbCtx, groupID, productIDs); err != nil { if err := s.repo.RemoveProductsFromGroup(dbCtx, groupID, productIDs, scope); err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
s.observer.Logger(ctx).Error("remove products from group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err)) s.observer.Logger(ctx).Error("remove products from group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err))
@ -840,7 +914,11 @@ func (s *ProductServer) RemoveProductsFromGroup(ctx context.Context, req *produc
// LockInventory reserves sellable stock for a pending order. // LockInventory reserves sellable stock for a pending order.
func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockInventoryRequest) (*productv1.LockInventoryResponse, error) { func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockInventoryRequest) (*productv1.LockInventoryResponse, error) {
if req == nil || req.GetSkuId() == "" { scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if req.GetSkuId() == "" {
return nil, status.Error(codes.InvalidArgument, "sku_id is required") return nil, status.Error(codes.InvalidArgument, "sku_id is required")
} }
if req.GetQuantity() <= 0 { if req.GetQuantity() <= 0 {
@ -854,7 +932,7 @@ func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockIn
)) ))
defer dbSpan.End() defer dbSpan.End()
inventory, err := s.repo.LockInventory(dbCtx, req.GetSkuId(), req.GetQuantity()) inventory, err := s.repo.LockInventory(dbCtx, req.GetSkuId(), req.GetQuantity(), scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -883,7 +961,11 @@ func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockIn
// ConfirmInventory converts locked stock into sold stock for a paid order. // ConfirmInventory converts locked stock into sold stock for a paid order.
func (s *ProductServer) ConfirmInventory(ctx context.Context, req *productv1.ConfirmInventoryRequest) (*productv1.ConfirmInventoryResponse, error) { func (s *ProductServer) ConfirmInventory(ctx context.Context, req *productv1.ConfirmInventoryRequest) (*productv1.ConfirmInventoryResponse, error) {
if req == nil || req.GetOrderId() == "" { scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if req.GetOrderId() == "" {
return nil, status.Error(codes.InvalidArgument, "order_id is required") return nil, status.Error(codes.InvalidArgument, "order_id is required")
} }
items, err := toRepositoryInventoryAdjustments(req.GetItems()) items, err := toRepositoryInventoryAdjustments(req.GetItems())
@ -897,7 +979,7 @@ func (s *ProductServer) ConfirmInventory(ctx context.Context, req *productv1.Con
)) ))
defer dbSpan.End() defer dbSpan.End()
inventories, err := s.repo.ConfirmInventory(dbCtx, req.GetOrderId(), items) inventories, err := s.repo.ConfirmInventory(dbCtx, req.GetOrderId(), items, scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -908,7 +990,11 @@ func (s *ProductServer) ConfirmInventory(ctx context.Context, req *productv1.Con
// ReleaseInventory releases locked stock for an unpaid closed order. // ReleaseInventory releases locked stock for an unpaid closed order.
func (s *ProductServer) ReleaseInventory(ctx context.Context, req *productv1.ReleaseInventoryRequest) (*productv1.ReleaseInventoryResponse, error) { func (s *ProductServer) ReleaseInventory(ctx context.Context, req *productv1.ReleaseInventoryRequest) (*productv1.ReleaseInventoryResponse, error) {
if req == nil || req.GetOrderId() == "" { scope, err := requireStoreScope(req)
if err != nil {
return nil, err
}
if req.GetOrderId() == "" {
return nil, status.Error(codes.InvalidArgument, "order_id is required") return nil, status.Error(codes.InvalidArgument, "order_id is required")
} }
items, err := toRepositoryInventoryAdjustments(req.GetItems()) items, err := toRepositoryInventoryAdjustments(req.GetItems())
@ -922,7 +1008,7 @@ func (s *ProductServer) ReleaseInventory(ctx context.Context, req *productv1.Rel
)) ))
defer dbSpan.End() defer dbSpan.End()
inventories, err := s.repo.ReleaseInventory(dbCtx, req.GetOrderId(), items) inventories, err := s.repo.ReleaseInventory(dbCtx, req.GetOrderId(), items, scope)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())

View File

@ -0,0 +1,44 @@
package server
import (
"fmt"
"strconv"
"strings"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
commonv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/common/v1"
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
)
type storeContextGetter interface {
GetStoreContext() *commonv1.StoreContext
}
func requireStoreScope(req storeContextGetter) (repository.StoreScope, error) {
if req == nil {
return repository.StoreScope{}, status.Error(codes.FailedPrecondition, "store_context is required")
}
sc := req.GetStoreContext()
if sc == nil || strings.TrimSpace(sc.GetStoreId()) == "" || strings.TrimSpace(sc.GetTenantId()) == "" {
return repository.StoreScope{}, status.Error(codes.FailedPrecondition, "store_context.store_id and tenant_id are required")
}
storeID, err := parsePositiveID(strings.TrimSpace(sc.GetStoreId()), "store_context.store_id")
if err != nil {
return repository.StoreScope{}, status.Error(codes.InvalidArgument, err.Error())
}
tenantID, err := parsePositiveID(strings.TrimSpace(sc.GetTenantId()), "store_context.tenant_id")
if err != nil {
return repository.StoreScope{}, status.Error(codes.InvalidArgument, err.Error())
}
return repository.StoreScope{TenantID: tenantID, StoreID: storeID}, nil
}
func parsePositiveID(raw, field string) (int64, error) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, fmt.Errorf("%s must be a positive snowflake id", field)
}
return id, nil
}

View File

@ -0,0 +1,37 @@
package server
import (
"context"
"testing"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
commonv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/common/v1"
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
)
func TestRequireStoreScopeMissing(t *testing.T) {
_, err := requireStoreScope(&productv1.GetProductRequest{ProductId: "1"})
if status.Code(err) != codes.FailedPrecondition {
t.Fatalf("code = %v, want FailedPrecondition", status.Code(err))
}
}
func TestGetProductBySkuRequiresStoreContext(t *testing.T) {
s := NewProductServer(nil, nil, nil, nil)
_, err := s.GetProductBySku(context.Background(), &productv1.GetProductBySkuRequest{})
if status.Code(err) != codes.FailedPrecondition {
t.Fatalf("err = %v, want FailedPrecondition", err)
}
}
func TestGetProductBySkuRequiresID(t *testing.T) {
s := NewProductServer(nil, nil, nil, nil)
_, err := s.GetProductBySku(context.Background(), &productv1.GetProductBySkuRequest{
StoreContext: &commonv1.StoreContext{TenantId: "10", StoreId: "20"},
})
if status.Code(err) != codes.InvalidArgument {
t.Fatalf("err = %v, want InvalidArgument", err)
}
}