feat(product): implement inventory adjustment functionality with confirm and release actions

This commit is contained in:
robinj0726 2026-09-05 15:22:16 +08:00
parent bfdbe0361d
commit cf068fe610
5 changed files with 376 additions and 1 deletions

View File

@ -6,6 +6,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"sort"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -30,6 +31,12 @@ var ErrSKUNotFound = errors.New("sku not found")
// ErrInsufficientStock is returned when stock - locked is less than the requested quantity. // ErrInsufficientStock is returned when stock - locked is less than the requested quantity.
var ErrInsufficientStock = errors.New("insufficient stock") var ErrInsufficientStock = errors.New("insufficient stock")
// ErrInsufficientLockedStock is returned when locked stock is less than the requested quantity.
var ErrInsufficientLockedStock = errors.New("insufficient locked stock")
// ErrInventoryAdjustmentConflict is returned when an idempotent inventory adjustment is replayed with different data.
var ErrInventoryAdjustmentConflict = errors.New("inventory adjustment conflict")
// ErrProductNotOnSale is returned when a new inventory reservation targets a product that is not on sale. // ErrProductNotOnSale is returned when a new inventory reservation targets a product that is not on sale.
var ErrProductNotOnSale = errors.New("product is not on sale") var ErrProductNotOnSale = errors.New("product is not on sale")
@ -127,6 +134,12 @@ type InventoryRecord struct {
UpdatedAt time.Time UpdatedAt time.Time
} }
// InventoryAdjustment is one order item quantity to confirm or release.
type InventoryAdjustment struct {
SKUID string
Quantity int32
}
// CartItemProductLookup identifies the SPU/SKU pair stored by one cart line. // CartItemProductLookup identifies the SPU/SKU pair stored by one cart line.
// Line IDs are intentionally kept outside the repository because they belong to trade.cart_items. // Line IDs are intentionally kept outside the repository because they belong to trade.cart_items.
type CartItemProductLookup struct { type CartItemProductLookup struct {
@ -348,6 +361,15 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory (
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id) CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id)
); );
CREATE TABLE IF NOT EXISTS product.inventory_adjustments (
order_id BIGINT NOT NULL,
action VARCHAR(20) NOT NULL,
sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
quantity INTEGER NOT NULL CHECK (quantity > 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (order_id, action, sku_id),
CONSTRAINT chk_inventory_adjustments_action CHECK (action IN ('confirm', 'release'))
);
ALTER TABLE product.product_items ALTER TABLE product.product_items
ALTER COLUMN id DROP DEFAULT; ALTER COLUMN id DROP DEFAULT;
ALTER TABLE product.product_items ALTER TABLE product.product_items
@ -1572,9 +1594,211 @@ RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, c
return inventory, nil return inventory, nil
} }
// ConfirmInventory converts locked stock to sold stock after payment succeeds.
func (r *ProductRepository) ConfirmInventory(ctx context.Context, orderID string, items []InventoryAdjustment) ([]*InventoryRecord, error) {
return r.applyInventoryAdjustments(ctx, orderID, "confirm", items)
}
// 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) {
return r.applyInventoryAdjustments(ctx, orderID, "release", items)
}
func (r *ProductRepository) applyInventoryAdjustments(ctx context.Context, orderID, action string, items []InventoryAdjustment) ([]*InventoryRecord, error) {
parsedOrderID, err := parseID(orderID, "order id")
if err != nil {
return nil, err
}
aggregated, err := aggregateInventoryAdjustments(items)
if err != nil {
return nil, err
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin %s inventory: %w", action, err)
}
defer tx.Rollback()
inventories := make([]*InventoryRecord, 0, len(aggregated))
for _, item := range aggregated {
skuID, err := parseID(item.SKUID, "sku id")
if err != nil {
return nil, err
}
var inserted bool
err = tx.QueryRowContext(ctx, `
INSERT INTO product.inventory_adjustments (order_id, action, sku_id, quantity)
VALUES ($1, $2, $3, $4)
ON CONFLICT (order_id, action, sku_id) DO NOTHING
RETURNING TRUE
`, parsedOrderID, action, skuID, item.Quantity).Scan(&inserted)
if errors.Is(err, sql.ErrNoRows) {
recordedQuantity, err := loadInventoryAdjustmentQuantity(ctx, tx, parsedOrderID, action, skuID)
if err != nil {
return nil, err
}
if recordedQuantity != item.Quantity {
return nil, fmt.Errorf("%s inventory %s: %w: recorded quantity %d, requested quantity %d", action, formatID(skuID), ErrInventoryAdjustmentConflict, recordedQuantity, item.Quantity)
}
inventory, err := loadInventoryForUpdate(ctx, tx, skuID)
if err != nil {
return nil, err
}
inventories = append(inventories, inventory)
continue
}
if err != nil {
return nil, fmt.Errorf("record %s inventory adjustment: %w", action, err)
}
inventory, err := applyInventoryAdjustment(ctx, tx, action, skuID, item.Quantity)
if err != nil {
return nil, err
}
inventories = append(inventories, inventory)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit %s inventory: %w", action, err)
}
return inventories, nil
}
func aggregateInventoryAdjustments(items []InventoryAdjustment) ([]InventoryAdjustment, error) {
if len(items) == 0 {
return nil, errors.New("items are required")
}
type aggregate struct {
skuID string
parsedID int64
quantity int32
}
quantities := make(map[string]int32, len(items))
parsedIDs := make(map[string]int64, len(items))
for i, item := range items {
if strings.TrimSpace(item.SKUID) == "" {
return nil, fmt.Errorf("items[%d].sku_id is required", i)
}
if item.Quantity <= 0 {
return nil, fmt.Errorf("items[%d].quantity must be positive", i)
}
skuID := strings.TrimSpace(item.SKUID)
parsedID, err := parseID(skuID, fmt.Sprintf("items[%d].sku_id", i))
if err != nil {
return nil, err
}
quantities[skuID] += item.Quantity
parsedIDs[skuID] = parsedID
}
aggregated := make([]aggregate, 0, len(quantities))
for skuID, quantity := range quantities {
aggregated = append(aggregated, aggregate{skuID: skuID, parsedID: parsedIDs[skuID], quantity: quantity})
}
sort.Slice(aggregated, func(i, j int) bool {
return aggregated[i].parsedID < aggregated[j].parsedID
})
out := make([]InventoryAdjustment, 0, len(aggregated))
for _, item := range aggregated {
out = append(out, InventoryAdjustment{SKUID: item.skuID, Quantity: item.quantity})
}
return out, nil
}
func applyInventoryAdjustment(ctx context.Context, tx *sql.Tx, action string, skuID int64, quantity int32) (*InventoryRecord, error) {
var query string
switch action {
case "confirm":
query = `
UPDATE product.product_item_inventory
SET stock_quantity = stock_quantity - $2,
locked_quantity = locked_quantity - $2,
sold_quantity = sold_quantity + $2,
version = version + 1,
updated_at = NOW()
WHERE sku_id = $1
AND locked_quantity >= $2
AND stock_quantity >= $2
RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at
`
case "release":
query = `
UPDATE product.product_item_inventory
SET locked_quantity = locked_quantity - $2,
version = version + 1,
updated_at = NOW()
WHERE sku_id = $1
AND locked_quantity >= $2
RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at
`
default:
return nil, fmt.Errorf("unsupported inventory action %q", action)
}
inventory, err := scanInventory(tx.QueryRowContext(ctx, query, skuID, quantity))
if errors.Is(err, sql.ErrNoRows) {
exists, existsErr := skuInventoryExistsInTx(ctx, tx, skuID)
if existsErr != nil {
return nil, existsErr
}
if !exists {
return nil, fmt.Errorf("%s inventory %s: %w", action, formatID(skuID), ErrSKUNotFound)
}
return nil, fmt.Errorf("%s inventory %s: %w", action, formatID(skuID), ErrInsufficientLockedStock)
}
if err != nil {
return nil, fmt.Errorf("%s inventory %s: %w", action, formatID(skuID), err)
}
return inventory, nil
}
func loadInventoryForUpdate(ctx context.Context, tx *sql.Tx, skuID int64) (*InventoryRecord, error) {
inventory, err := scanInventory(tx.QueryRowContext(ctx, `
SELECT id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at
FROM product.product_item_inventory
WHERE sku_id = $1
FOR UPDATE
`, skuID))
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("load inventory %s: %w", formatID(skuID), ErrSKUNotFound)
}
if err != nil {
return nil, fmt.Errorf("load inventory %s: %w", formatID(skuID), err)
}
return inventory, nil
}
func loadInventoryAdjustmentQuantity(ctx context.Context, tx *sql.Tx, orderID int64, action string, skuID int64) (int32, error) {
var quantity int32
err := tx.QueryRowContext(ctx, `
SELECT quantity
FROM product.inventory_adjustments
WHERE order_id = $1
AND action = $2
AND sku_id = $3
FOR UPDATE
`, orderID, action, skuID).Scan(&quantity)
if errors.Is(err, sql.ErrNoRows) {
return 0, fmt.Errorf("%s inventory %s: %w: missing recorded adjustment", action, formatID(skuID), ErrInventoryAdjustmentConflict)
}
if err != nil {
return 0, fmt.Errorf("load %s inventory adjustment %s: %w", action, formatID(skuID), err)
}
return quantity, nil
}
func (r *ProductRepository) skuInventoryExists(ctx context.Context, skuID int64) (bool, error) { func (r *ProductRepository) skuInventoryExists(ctx context.Context, skuID int64) (bool, error) {
return skuInventoryExistsInTx(ctx, r.db, skuID)
}
type queryRower interface {
QueryRowContext(context.Context, string, ...any) *sql.Row
}
func skuInventoryExistsInTx(ctx context.Context, q queryRower, skuID int64) (bool, error) {
var exists bool var exists bool
err := r.db.QueryRowContext(ctx, ` err := q.QueryRowContext(ctx, `
SELECT EXISTS( SELECT EXISTS(
SELECT 1 SELECT 1
FROM product.product_item_inventory inv FROM product.product_item_inventory inv

View File

@ -8,3 +8,32 @@ func TestEscapeLikeLiteral(t *testing.T) {
t.Fatalf("escapeLikeLiteral(%q) = %q, want %q", input, got, want) t.Fatalf("escapeLikeLiteral(%q) = %q, want %q", input, got, want)
} }
} }
func TestAggregateInventoryAdjustments(t *testing.T) {
got, err := aggregateInventoryAdjustments([]InventoryAdjustment{
{SKUID: "1002", Quantity: 3},
{SKUID: "1001", Quantity: 1},
{SKUID: "1001", Quantity: 2},
})
if err != nil {
t.Fatal(err)
}
if len(got) != 2 {
t.Fatalf("len = %d, want 2", len(got))
}
if got[0] != (InventoryAdjustment{SKUID: "1001", Quantity: 3}) {
t.Fatalf("first adjustment = %#v", got[0])
}
if got[1] != (InventoryAdjustment{SKUID: "1002", Quantity: 3}) {
t.Fatalf("second adjustment = %#v", got[1])
}
}
func TestAggregateInventoryAdjustmentsRejectsInvalidSKUID(t *testing.T) {
_, err := aggregateInventoryAdjustments([]InventoryAdjustment{
{SKUID: "bad-sku", Quantity: 1},
})
if err == nil {
t.Fatal("expected invalid sku id error")
}
}

View File

@ -881,6 +881,93 @@ func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockIn
}, nil }, nil
} }
// ConfirmInventory converts locked stock into sold stock for a paid order.
func (s *ProductServer) ConfirmInventory(ctx context.Context, req *productv1.ConfirmInventoryRequest) (*productv1.ConfirmInventoryResponse, error) {
if req == nil || req.GetOrderId() == "" {
return nil, status.Error(codes.InvalidArgument, "order_id is required")
}
items, err := toRepositoryInventoryAdjustments(req.GetItems())
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.confirm_inventory", trace.WithAttributes(
attribute.String("order.id", req.GetOrderId()),
attribute.Int("inventory.items", len(items)),
))
defer dbSpan.End()
inventories, err := s.repo.ConfirmInventory(dbCtx, req.GetOrderId(), items)
if err != nil {
dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error())
return nil, mapInventoryAdjustmentError(ctx, s, "confirm", err)
}
return &productv1.ConfirmInventoryResponse{Inventories: toProtoInventories(inventories)}, nil
}
// ReleaseInventory releases locked stock for an unpaid closed order.
func (s *ProductServer) ReleaseInventory(ctx context.Context, req *productv1.ReleaseInventoryRequest) (*productv1.ReleaseInventoryResponse, error) {
if req == nil || req.GetOrderId() == "" {
return nil, status.Error(codes.InvalidArgument, "order_id is required")
}
items, err := toRepositoryInventoryAdjustments(req.GetItems())
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.release_inventory", trace.WithAttributes(
attribute.String("order.id", req.GetOrderId()),
attribute.Int("inventory.items", len(items)),
))
defer dbSpan.End()
inventories, err := s.repo.ReleaseInventory(dbCtx, req.GetOrderId(), items)
if err != nil {
dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error())
return nil, mapInventoryAdjustmentError(ctx, s, "release", err)
}
return &productv1.ReleaseInventoryResponse{Inventories: toProtoInventories(inventories)}, nil
}
func toRepositoryInventoryAdjustments(items []*productv1.InventoryAdjustmentItem) ([]repository.InventoryAdjustment, error) {
if len(items) == 0 {
return nil, errors.New("items are required")
}
out := make([]repository.InventoryAdjustment, 0, len(items))
for i, item := range items {
if item == nil {
return nil, fmt.Errorf("items[%d] is required", i)
}
if item.GetSkuId() == "" {
return nil, fmt.Errorf("items[%d].sku_id is required", i)
}
if item.GetQuantity() <= 0 {
return nil, fmt.Errorf("items[%d].quantity must be positive", i)
}
out = append(out, repository.InventoryAdjustment{
SKUID: item.GetSkuId(),
Quantity: item.GetQuantity(),
})
}
return out, nil
}
func mapInventoryAdjustmentError(ctx context.Context, s *ProductServer, action string, err error) error {
switch {
case errors.Is(err, repository.ErrSKUNotFound):
return status.Error(codes.NotFound, "sku inventory not found")
case errors.Is(err, repository.ErrInsufficientLockedStock):
return status.Error(codes.FailedPrecondition, "insufficient locked stock")
case errors.Is(err, repository.ErrInventoryAdjustmentConflict):
return status.Error(codes.FailedPrecondition, "inventory adjustment conflict")
default:
s.observer.Logger(ctx).Error(action+" inventory failed", zap.Error(err))
return status.Errorf(codes.Internal, "%s inventory: %v", action, err)
}
}
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
@ -1810,6 +1897,14 @@ func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductI
} }
} }
func toProtoInventories(inventories []*repository.InventoryRecord) []*productv1.ProductItemInventory {
out := make([]*productv1.ProductItemInventory, 0, len(inventories))
for _, inventory := range inventories {
out = append(out, toProtoInventory(inventory))
}
return out
}
func buildCategoryTree(categories []*repository.CategoryRecord) []*productv1.CategoryNode { func buildCategoryTree(categories []*repository.CategoryRecord) []*productv1.CategoryNode {
nodes := make(map[string]*productv1.CategoryNode, len(categories)) nodes := make(map[string]*productv1.CategoryNode, len(categories))
records := make(map[string]*repository.CategoryRecord, len(categories)) records := make(map[string]*repository.CategoryRecord, len(categories))

View File

@ -0,0 +1,14 @@
CREATE TABLE IF NOT EXISTS product.inventory_adjustments (
order_id BIGINT NOT NULL,
action VARCHAR(20) NOT NULL,
sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
quantity INTEGER NOT NULL CHECK (quantity > 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (order_id, action, sku_id),
CONSTRAINT chk_inventory_adjustments_action CHECK (action IN ('confirm', 'release'))
);
COMMENT ON TABLE product.inventory_adjustments IS '订单库存动作幂等表:记录确认成交和释放锁定库存';
COMMENT ON COLUMN product.inventory_adjustments.action IS '库存动作:confirm 支付成功确认成交;release 待支付取消/超时释放锁定';
GRANT SELECT, INSERT, UPDATE, DELETE ON product.inventory_adjustments TO svc_product;

View File

@ -216,6 +216,16 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory (
CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id) CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id)
); );
CREATE TABLE IF NOT EXISTS product.inventory_adjustments (
order_id BIGINT NOT NULL,
action VARCHAR(20) NOT NULL,
sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
quantity INTEGER NOT NULL CHECK (quantity > 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (order_id, action, sku_id),
CONSTRAINT chk_inventory_adjustments_action CHECK (action IN ('confirm', 'release'))
);
COMMENT ON TABLE product.product_item_inventory IS '商品 SKU 库存销量表:存储库存池、锁定库存和已售数量'; COMMENT ON TABLE product.product_item_inventory IS '商品 SKU 库存销量表:存储库存池、锁定库存和已售数量';
COMMENT ON COLUMN product.product_item_inventory.id IS '库存记录主键,由商品服务应用层生成雪花 ID'; COMMENT ON COLUMN product.product_item_inventory.id IS '库存记录主键,由商品服务应用层生成雪花 ID';
COMMENT ON COLUMN product.product_item_inventory.spu_no IS '商品 SPU 编码冗余字段,用于库存查询和对账'; COMMENT ON COLUMN product.product_item_inventory.spu_no IS '商品 SPU 编码冗余字段,用于库存查询和对账';
@ -224,6 +234,8 @@ COMMENT ON COLUMN product.product_item_inventory.stock_quantity IS 'SKU 当前
COMMENT ON COLUMN product.product_item_inventory.locked_quantity IS '待支付订单锁定库存'; COMMENT ON COLUMN product.product_item_inventory.locked_quantity IS '待支付订单锁定库存';
COMMENT ON COLUMN product.product_item_inventory.sold_quantity IS '支付成功后的累计销量'; COMMENT ON COLUMN product.product_item_inventory.sold_quantity IS '支付成功后的累计销量';
COMMENT ON COLUMN product.product_item_inventory.version IS '库存乐观锁版本号'; COMMENT ON COLUMN product.product_item_inventory.version IS '库存乐观锁版本号';
COMMENT ON TABLE product.inventory_adjustments IS '订单库存动作幂等表:记录确认成交和释放锁定库存';
COMMENT ON COLUMN product.inventory_adjustments.action IS '库存动作:confirm 支付成功确认成交;release 待支付取消/超时释放锁定';
DROP TRIGGER IF EXISTS set_products_updated_at ON product.products; DROP TRIGGER IF EXISTS set_products_updated_at ON product.products;
CREATE TRIGGER set_products_updated_at CREATE TRIGGER set_products_updated_at
@ -245,3 +257,4 @@ GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category TO svc_product;
GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category_bindings TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category_bindings TO svc_product;
GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_items TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_items TO svc_product;
GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_item_inventory TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_item_inventory TO svc_product;
GRANT SELECT, INSERT, UPDATE, DELETE ON product.inventory_adjustments TO svc_product;