From aa3ee1d236f43d78dca86475b916431adaca0229 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Thu, 16 Jul 2026 12:51:40 +0800 Subject: [PATCH] feat(product): implement LockInventory method to reserve stock for pending orders --- internal/repository/product_repository.go | 52 ++++++++++++++++ internal/server/product_server.go | 73 ++++++++++++++++++----- 2 files changed, 111 insertions(+), 14 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 3fcfd67..184b871 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -21,6 +21,9 @@ var ErrProductNotFound = errors.New("product not found") // ErrSKUNotFound is returned when a SKU does not exist. 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. var ErrDuplicateSPUNo = errors.New("spu_no already exists") @@ -448,6 +451,55 @@ WHERE id = $1 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. func (r *ProductRepository) DeleteSKU(ctx context.Context, skuID string) error { id, err := parseID(skuID, "sku id") diff --git a/internal/server/product_server.go b/internal/server/product_server.go index b0756bd..5fb1d93 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -334,6 +334,47 @@ func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroup }, 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 { if total <= 0 || pageSize <= 0 { return 0 @@ -765,23 +806,27 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord, skus []re if product == nil { return nil } - protoSKUs := make([]*productv1.CategoryProductSKU, 0, len(skus)) + var ( + minPrice int64 + soldQuantity int64 + hasPrice bool + ) for _, sku := range skus { - protoSKUs = append(protoSKUs, &productv1.CategoryProductSKU{ - SkuId: sku.ID, - AvailableQuantity: sku.AvailableQuantity, - Price: sku.Price, - }) + if !hasPrice || sku.Price < minPrice { + minPrice = sku.Price + hasPrice = true + } } return &productv1.CategoryProduct{ - UpdatedAt: timeToMillisString(product.UpdatedAt), - CreatedAt: timeToMillisString(product.CreatedAt), - Title: product.Title, - ProductId: product.ID, - SpuNo: product.SPUNo, - Status: product.Status, - ImageIds: product.ImageIDs, - Skus: protoSKUs, + UpdatedAt: timeToMillisString(product.UpdatedAt), + CreatedAt: timeToMillisString(product.CreatedAt), + Title: product.Title, + ProductId: product.ID, + SpuNo: product.SPUNo, + Status: product.Status, + ImageIds: product.ImageIDs, + Price: minPrice, + SoldQuantity: soldQuantity, } }