Merge branch 'phase1' into dev2

This commit is contained in:
robinj0726 2026-07-16 16:54:52 +08:00
commit f09dcffe02
2 changed files with 101 additions and 2 deletions

View File

@ -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")
@ -472,6 +475,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")

View File

@ -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
@ -657,11 +698,17 @@ func normalizeStringList(values []string) []string {
return []string{}
}
out := make([]string, 0, len(values))
seen := make(map[string]struct{}, len(values))
for _, value := range values {
trimmed := strings.TrimSpace(value)
if trimmed != "" {
out = append(out, trimmed)
if trimmed == "" {
continue
}
if _, ok := seen[trimmed]; ok {
continue
}
seen[trimmed] = struct{}{}
out = append(out, trimmed)
}
return out
}