feat(product): implement LockInventory method to reserve stock for pending orders

This commit is contained in:
robinj0726 2026-07-16 12:51:40 +08:00
parent bbe9ee0be2
commit aa3ee1d236
2 changed files with 111 additions and 14 deletions

View File

@ -21,6 +21,9 @@ var ErrProductNotFound = errors.New("product not found")
// ErrSKUNotFound is returned when a SKU does not exist. // ErrSKUNotFound is returned when a SKU does not exist.
var ErrSKUNotFound = errors.New("sku not found") var ErrSKUNotFound = errors.New("sku not found")
// ErrInsufficientStock is returned when available - locked is less than the requested quantity.
var ErrInsufficientStock = errors.New("insufficient stock")
// ErrDuplicateSPUNo is returned when a non-deleted product already uses the SPU number. // ErrDuplicateSPUNo is returned when a non-deleted product already uses the SPU number.
var ErrDuplicateSPUNo = errors.New("spu_no already exists") var ErrDuplicateSPUNo = errors.New("spu_no already exists")
@ -448,6 +451,55 @@ WHERE id = $1
return nil return nil
} }
// LockInventory atomically reserves quantity when available_quantity - locked_quantity >= quantity.
func (r *ProductRepository) LockInventory(ctx context.Context, skuID string, quantity int32) (*InventoryRecord, error) {
if quantity <= 0 {
return nil, fmt.Errorf("quantity must be positive")
}
id, err := parseID(skuID, "sku id")
if err != nil {
return nil, err
}
row := r.db.QueryRowContext(ctx, `
UPDATE product.product_item_inventory
SET locked_quantity = locked_quantity + $2,
version = version + 1,
updated_at = NOW()
WHERE sku_id = $1
AND available_quantity - locked_quantity >= $2
RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at
`, id, quantity)
inventory, err := scanInventory(row)
if errors.Is(err, sql.ErrNoRows) {
exists, existsErr := r.skuInventoryExists(ctx, id)
if existsErr != nil {
return nil, existsErr
}
if !exists {
return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrSKUNotFound)
}
return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrInsufficientStock)
}
if err != nil {
return nil, fmt.Errorf("lock inventory %s: %w", skuID, err)
}
return inventory, nil
}
func (r *ProductRepository) skuInventoryExists(ctx context.Context, skuID int64) (bool, error) {
var exists bool
err := r.db.QueryRowContext(ctx, `
SELECT EXISTS(
SELECT 1 FROM product.product_item_inventory WHERE sku_id = $1
)
`, skuID).Scan(&exists)
if err != nil {
return false, fmt.Errorf("check inventory exists %s: %w", formatID(skuID), err)
}
return exists, nil
}
// DeleteSKU soft-deletes a SKU row. // DeleteSKU soft-deletes a SKU row.
func (r *ProductRepository) DeleteSKU(ctx context.Context, skuID string) error { func (r *ProductRepository) DeleteSKU(ctx context.Context, skuID string) error {
id, err := parseID(skuID, "sku id") id, err := parseID(skuID, "sku id")

View File

@ -334,6 +334,47 @@ func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroup
}, nil }, nil
} }
// LockInventory reserves sellable stock for a pending order.
func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockInventoryRequest) (*productv1.LockInventoryResponse, error) {
if req == nil || req.GetSkuId() == "" {
return nil, status.Error(codes.InvalidArgument, "sku_id is required")
}
if req.GetQuantity() <= 0 {
return nil, status.Error(codes.InvalidArgument, "quantity must be positive")
}
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.lock_inventory", trace.WithAttributes(
attribute.String("sku.id", req.GetSkuId()),
attribute.Int("inventory.quantity", int(req.GetQuantity())),
attribute.String("order.id", req.GetOrderId()),
))
defer dbSpan.End()
inventory, err := s.repo.LockInventory(dbCtx, req.GetSkuId(), req.GetQuantity())
if err != nil {
dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error())
switch {
case errors.Is(err, repository.ErrSKUNotFound):
return nil, status.Error(codes.NotFound, "sku inventory not found")
case errors.Is(err, repository.ErrInsufficientStock):
return nil, status.Error(codes.FailedPrecondition, "insufficient stock")
default:
s.observer.Logger(ctx).Error("lock inventory failed",
zap.String("sku_id", req.GetSkuId()),
zap.Int32("quantity", req.GetQuantity()),
zap.String("order_id", req.GetOrderId()),
zap.Error(err),
)
return nil, status.Errorf(codes.Internal, "lock inventory: %v", err)
}
}
return &productv1.LockInventoryResponse{
Inventory: toProtoInventory(inventory),
}, nil
}
func totalPages(total int64, pageSize int32) int32 { func totalPages(total int64, pageSize int32) int32 {
if total <= 0 || pageSize <= 0 { if total <= 0 || pageSize <= 0 {
return 0 return 0
@ -765,13 +806,16 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord, skus []re
if product == nil { if product == nil {
return nil return nil
} }
protoSKUs := make([]*productv1.CategoryProductSKU, 0, len(skus)) var (
minPrice int64
soldQuantity int64
hasPrice bool
)
for _, sku := range skus { for _, sku := range skus {
protoSKUs = append(protoSKUs, &productv1.CategoryProductSKU{ if !hasPrice || sku.Price < minPrice {
SkuId: sku.ID, minPrice = sku.Price
AvailableQuantity: sku.AvailableQuantity, hasPrice = true
Price: sku.Price, }
})
} }
return &productv1.CategoryProduct{ return &productv1.CategoryProduct{
UpdatedAt: timeToMillisString(product.UpdatedAt), UpdatedAt: timeToMillisString(product.UpdatedAt),
@ -781,7 +825,8 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord, skus []re
SpuNo: product.SPUNo, SpuNo: product.SPUNo,
Status: product.Status, Status: product.Status,
ImageIds: product.ImageIDs, ImageIds: product.ImageIDs,
Skus: protoSKUs, Price: minPrice,
SoldQuantity: soldQuantity,
} }
} }