refactor(product): rename available_quantity to stock_quantity across the codebase

This commit is contained in:
robinj0726 2026-09-05 13:49:11 +08:00
parent e2df9fd2e7
commit bfdbe0361d
6 changed files with 167 additions and 162 deletions

View File

@ -79,7 +79,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
{ {
"sku_no": "SKU20260710000101", "sku_no": "SKU20260710000101",
"price": 12800, "price": 12800,
"available_quantity": 100, "stock_quantity": 100,
"k1": "规格", "k1": "规格",
"v1": "1kg" "v1": "1kg"
} }

View File

@ -40,7 +40,7 @@ INVENTORY -> ON_SALE
运营人员上架;至少存在一个可售 SKU。 运营人员上架;至少存在一个可售 SKU。
ON_SALE -> OFF_SALE ON_SALE -> OFF_SALE
所有当前可售 SKU 的 available_quantity - locked_quantity <= 0 时系统自动下架, 所有当前可售 SKU 的 stock_quantity - locked_quantity <= 0 时系统自动下架,
或由运营人员主动下架。 或由运营人员主动下架。
OFF_SALE -> ON_SALE OFF_SALE -> ON_SALE
@ -111,7 +111,7 @@ Content-Type: application/json
"expected_inventory_version": 8, "expected_inventory_version": 8,
"name": "红色 M 码", "name": "红色 M 码",
"price": 9900, "price": 9900,
"available_quantity": 50, "stock_quantity": 50,
"status": 1, "status": 1,
"image_ids": ["726390485721088011"] "image_ids": ["726390485721088011"]
} }
@ -136,11 +136,11 @@ Content-Type: application/json
- `price`; - `price`;
- `name`; - `name`;
- `available_quantity`; - `stock_quantity`;
- `status`; - `status`;
- `image_ids`。 - `image_ids`。
不能修改 `sku_no`、`k1/v1` 至 `k3/v3`、销量或锁定库存。`name` 可单独覆盖,不影响 SKU 编号和规格组合。`available_quantity` 是更新后的绝对数量,且不得小于 `locked_quantity`。 不能修改 `sku_no`、`k1/v1` 至 `k3/v3`、销量或锁定库存。`name` 可单独覆盖,不影响 SKU 编号和规格组合。`stock_quantity` 是更新后的绝对数量,且不得小于 `locked_quantity`。
SKU 和库存均需要版本校验,防止后台操作覆盖下单锁库存。 SKU 和库存均需要版本校验,防止后台操作覆盖下单锁库存。
@ -157,7 +157,7 @@ SKU 和库存均需要版本校验,防止后台操作覆盖下单锁库存。
{ {
"sku_no": "SKU-RED-M", "sku_no": "SKU-RED-M",
"price": 9900, "price": 9900,
"available_quantity": 20, "stock_quantity": 20,
"status": 1, "status": 1,
"k1": "颜色", "k1": "颜色",
"v1": "红色", "v1": "红色",
@ -194,7 +194,7 @@ SKU 和库存均需要版本校验,防止后台操作覆盖下单锁库存。
"sku_id": "726390485721088201", "sku_id": "726390485721088201",
"sku_no": "SKU-RED-M", "sku_no": "SKU-RED-M",
"price": 9900, "price": 9900,
"available_quantity": 20, "stock_quantity": 20,
"status": 1, "status": 1,
"is_archived": false, "is_archived": false,
"version": 1 "version": 1
@ -226,7 +226,7 @@ Content-Type: application/json
运营人员可以提交 `INVENTORY`、`ON_SALE`、`OFF_SALE`。无论商品是运营人员手动下架,还是因无可售库存自动切换为 `OFF_SALE`,都只能通过本接口显式重新设置为 `ON_SALE`;库存补充本身不会改变商品状态。 运营人员可以提交 `INVENTORY`、`ON_SALE`、`OFF_SALE`。无论商品是运营人员手动下架,还是因无可售库存自动切换为 `OFF_SALE`,都只能通过本接口显式重新设置为 `ON_SALE`;库存补充本身不会改变商品状态。
上架时必须存在至少一个启用、未归档且 `available_quantity > locked_quantity` 的 SKU。 上架时必须存在至少一个启用、未归档且 `stock_quantity > locked_quantity` 的 SKU。
```json ```json
{ {

View File

@ -27,7 +27,7 @@ var ErrInvalidLeafCategory = errors.New("category must be an existing second-lev
// 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. // ErrInsufficientStock is returned when stock - locked is less than the requested quantity.
var ErrInsufficientStock = errors.New("insufficient stock") var ErrInsufficientStock = errors.New("insufficient stock")
// 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.
@ -89,42 +89,42 @@ type ProductCountRecord struct {
// SKURecord is the persistence model for product.product_items. // SKURecord is the persistence model for product.product_items.
type SKURecord struct { type SKURecord struct {
ID string ID string
ProductID string ProductID string
SKUNo string SKUNo string
Name string Name string
Price int64 Price int64
ImageIDs []string ImageIDs []string
AvailableQuantity int32 StockQuantity int32
LockedQuantity int32 LockedQuantity int32
SoldQuantity int32 SoldQuantity int32
AttributesJSON string AttributesJSON string
K1 string K1 string
V1 string V1 string
K2 string K2 string
V2 string V2 string
K3 string K3 string
V3 string V3 string
Status int32 Status int32
IsArchived bool IsArchived bool
ArchivedAt *time.Time ArchivedAt *time.Time
Version int32 Version int32
DeletedAt *time.Time DeletedAt *time.Time
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
Inventory *InventoryRecord Inventory *InventoryRecord
} }
// InventoryRecord is the persistence model for product.product_item_inventory. // InventoryRecord is the persistence model for product.product_item_inventory.
type InventoryRecord struct { type InventoryRecord struct {
ID string ID string
SKUID string SKUID string
AvailableQuantity int32 StockQuantity int32
LockedQuantity int32 LockedQuantity int32
SoldQuantity int32 SoldQuantity int32
Version int32 Version int32
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
} }
// CartItemProductLookup identifies the SPU/SKU pair stored by one cart line. // CartItemProductLookup identifies the SPU/SKU pair stored by one cart line.
@ -158,7 +158,7 @@ type SKUUpdate struct {
ExpectedInventoryVersion int32 ExpectedInventoryVersion int32
Name *string Name *string
Price *int64 Price *int64
AvailableQuantity *int32 StockQuantity *int32
Status *int32 Status *int32
ImageIDs *[]string ImageIDs *[]string
} }
@ -209,17 +209,17 @@ type ProductStatusUpdate struct {
// CategoryProductRecord is the product summary returned by product list endpoints. // CategoryProductRecord is the product summary returned by product list endpoints.
type CategoryProductRecord struct { type CategoryProductRecord struct {
ID string ID string
SPUNo string SPUNo string
Title string Title string
Status productv1.ProductStatus Status productv1.ProductStatus
ImageIDs []string ImageIDs []string
Price int64 Price int64
SoldQuantity int64 SoldQuantity int64
AvailableQuantity int64 StockQuantity int64
LockedQuantity int64 LockedQuantity int64
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
} }
// CategoryRecord is the persistence model for product.product_category. // CategoryRecord is the persistence model for product.product_category.
@ -340,7 +340,7 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory (
sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
spu_no VARCHAR(100), spu_no VARCHAR(100),
sku_no VARCHAR(100), sku_no VARCHAR(100),
available_quantity INTEGER NOT NULL DEFAULT 0 CHECK (available_quantity >= 0), stock_quantity INTEGER NOT NULL DEFAULT 0 CHECK (stock_quantity >= 0),
locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0), locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0),
sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0), sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0),
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
@ -1267,9 +1267,9 @@ FOR UPDATE
} }
} }
if input.AvailableQuantity != nil { if input.StockQuantity != nil {
if *input.AvailableQuantity < 0 { if *input.StockQuantity < 0 {
return fmt.Errorf("available_quantity must be greater than or equal to 0") return fmt.Errorf("stock_quantity must be greater than or equal to 0")
} }
var lockedQuantity int32 var lockedQuantity int32
var inventoryVersion int32 var inventoryVersion int32
@ -1288,14 +1288,14 @@ FOR UPDATE
if inventoryVersion != input.ExpectedInventoryVersion { if inventoryVersion != input.ExpectedInventoryVersion {
return ErrSKUVersionConflict return ErrSKUVersionConflict
} }
if *input.AvailableQuantity < lockedQuantity { if *input.StockQuantity < lockedQuantity {
return fmt.Errorf("available_quantity cannot be less than locked_quantity") return fmt.Errorf("stock_quantity cannot be less than locked_quantity")
} }
if _, err := tx.ExecContext(ctx, ` if _, err := tx.ExecContext(ctx, `
UPDATE product.product_item_inventory UPDATE product.product_item_inventory
SET available_quantity = $2, version = version + 1, updated_at = NOW() SET stock_quantity = $2, version = version + 1, updated_at = NOW()
WHERE sku_id = $1 AND version = $3 WHERE sku_id = $1 AND version = $3
`, skuID, *input.AvailableQuantity, input.ExpectedInventoryVersion); err != nil { `, skuID, *input.StockQuantity, input.ExpectedInventoryVersion); err != nil {
return fmt.Errorf("update sku inventory %s: %w", input.ID, err) return fmt.Errorf("update sku inventory %s: %w", input.ID, err)
} }
} }
@ -1338,7 +1338,7 @@ SELECT EXISTS(
AND pi.deleted_at IS NULL AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE AND pi.is_archived = FALSE
AND pi.status = 1 AND pi.status = 1
AND inv.available_quantity > inv.locked_quantity AND inv.stock_quantity > inv.locked_quantity
) )
`, productID).Scan(&exists) `, productID).Scan(&exists)
if err != nil { if err != nil {
@ -1363,7 +1363,7 @@ WHERE p.id = $1
AND pi.deleted_at IS NULL AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE AND pi.is_archived = FALSE
AND pi.status = 1 AND pi.status = 1
AND inv.available_quantity > inv.locked_quantity AND inv.stock_quantity > inv.locked_quantity
) )
`, productID, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE)) `, productID, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE))
if err != nil { if err != nil {
@ -1440,7 +1440,7 @@ RETURNING id
return fmt.Errorf("insert sku: %w", err) return fmt.Errorf("insert sku: %w", err)
} }
if _, err := insertSKUInventory(ctx, tx, inventoryID, skuID, sku.AvailableQuantity); err != nil { if _, err := insertSKUInventory(ctx, tx, inventoryID, skuID, sku.StockQuantity); err != nil {
return err return err
} }
@ -1484,7 +1484,7 @@ WHERE id = $1 AND is_archived = FALSE
return ErrSKUNotFound return ErrSKUNotFound
} }
if _, err := updateSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { if _, err := updateSKUInventory(ctx, tx, id, sku.StockQuantity); err != nil {
return err return err
} }
@ -1494,7 +1494,7 @@ WHERE id = $1 AND is_archived = FALSE
return nil return nil
} }
// LockInventory atomically reserves quantity when available_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) (*InventoryRecord, error) {
if quantity <= 0 { if quantity <= 0 {
return nil, fmt.Errorf("quantity must be positive") return nil, fmt.Errorf("quantity must be positive")
@ -1546,8 +1546,8 @@ WHERE sku_id = $1
AND pi.is_archived = FALSE AND pi.is_archived = FALSE
AND pi.status = 1 AND pi.status = 1
) )
AND available_quantity - locked_quantity >= $2 AND stock_quantity - locked_quantity >= $2
RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, version, created_at, updated_at RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at
`, id, quantity) `, id, quantity)
inventory, err := scanInventory(row) inventory, err := scanInventory(row)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
@ -1781,13 +1781,13 @@ SELECT p.updated_at,
COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(to_json(p.image_ids)::text, '[]'),
COALESCE(sku_summary.price, 0), COALESCE(sku_summary.price, 0),
COALESCE(sku_summary.sold_quantity, 0), COALESCE(sku_summary.sold_quantity, 0),
COALESCE(sku_summary.available_quantity, 0), COALESCE(sku_summary.stock_quantity, 0),
COALESCE(sku_summary.locked_quantity, 0) COALESCE(sku_summary.locked_quantity, 0)
FROM product.products p FROM product.products p
LEFT JOIN LATERAL ( LEFT JOIN LATERAL (
SELECT MIN(pi.price) AS price, SELECT MIN(pi.price) AS price,
SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity,
SUM(COALESCE(inv.available_quantity, 0)) AS available_quantity, SUM(COALESCE(inv.stock_quantity, 0)) AS stock_quantity,
SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity
FROM product.product_items pi FROM product.product_items pi
LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id
@ -1860,13 +1860,13 @@ SELECT p.updated_at,
COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(to_json(p.image_ids)::text, '[]'),
COALESCE(sku_summary.price, 0), COALESCE(sku_summary.price, 0),
COALESCE(sku_summary.sold_quantity, 0), COALESCE(sku_summary.sold_quantity, 0),
COALESCE(sku_summary.available_quantity, 0), COALESCE(sku_summary.stock_quantity, 0),
COALESCE(sku_summary.locked_quantity, 0) COALESCE(sku_summary.locked_quantity, 0)
FROM product.products p FROM product.products p
LEFT JOIN LATERAL ( LEFT JOIN LATERAL (
SELECT MIN(pi.price) AS price, SELECT MIN(pi.price) AS price,
SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity,
SUM(COALESCE(inv.available_quantity, 0)) AS available_quantity, SUM(COALESCE(inv.stock_quantity, 0)) AS stock_quantity,
SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity
FROM product.product_items pi FROM product.product_items pi
LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id
@ -1969,14 +1969,14 @@ SELECT p.updated_at,
COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(to_json(p.image_ids)::text, '[]'),
COALESCE(sku_summary.price, 0), COALESCE(sku_summary.price, 0),
COALESCE(sku_summary.sold_quantity, 0), COALESCE(sku_summary.sold_quantity, 0),
COALESCE(sku_summary.available_quantity, 0), COALESCE(sku_summary.stock_quantity, 0),
COALESCE(sku_summary.locked_quantity, 0) COALESCE(sku_summary.locked_quantity, 0)
FROM product.products p FROM product.products p
JOIN product.product_category_bindings b ON b.product_id = p.id JOIN product.product_category_bindings b ON b.product_id = p.id
LEFT JOIN LATERAL ( LEFT JOIN LATERAL (
SELECT MIN(pi.price) AS price, SELECT MIN(pi.price) AS price,
SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity,
SUM(COALESCE(inv.available_quantity, 0)) AS available_quantity, SUM(COALESCE(inv.stock_quantity, 0)) AS stock_quantity,
SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity
FROM product.product_items pi FROM product.product_items pi
LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id
@ -2295,13 +2295,13 @@ RETURNING id,
if err != nil { if err != nil {
return nil, err return nil, err
} }
inventory, err := insertSKUInventory(ctx, tx, inventoryID, createdSKUID, sku.AvailableQuantity) inventory, err := insertSKUInventory(ctx, tx, inventoryID, createdSKUID, sku.StockQuantity)
if err != nil { if err != nil {
return nil, err return nil, err
} }
createdSKU.Inventory = inventory createdSKU.Inventory = inventory
if inventory != nil { if inventory != nil {
createdSKU.AvailableQuantity = inventory.AvailableQuantity createdSKU.StockQuantity = inventory.StockQuantity
createdSKU.LockedQuantity = inventory.LockedQuantity createdSKU.LockedQuantity = inventory.LockedQuantity
createdSKU.SoldQuantity = inventory.SoldQuantity createdSKU.SoldQuantity = inventory.SoldQuantity
} }
@ -2315,15 +2315,15 @@ func inventoryIDFromSKU(sku SKURecord) (int64, error) {
return parseID(sku.Inventory.ID, "inventory id") return parseID(sku.Inventory.ID, "inventory id")
} }
func insertSKUInventory(ctx context.Context, tx *sql.Tx, inventoryID, skuID int64, availableQuantity int32) (*InventoryRecord, error) { func insertSKUInventory(ctx context.Context, tx *sql.Tx, inventoryID, skuID int64, stockQuantity int32) (*InventoryRecord, error) {
row := tx.QueryRowContext(ctx, ` row := tx.QueryRowContext(ctx, `
INSERT INTO product.product_item_inventory (id, sku_id, spu_no, sku_no, available_quantity) INSERT INTO product.product_item_inventory (id, sku_id, spu_no, sku_no, stock_quantity)
SELECT $1, pi.id, p.spu_no, pi.sku_no, $3 SELECT $1, pi.id, p.spu_no, pi.sku_no, $3
FROM product.product_items pi FROM product.product_items pi
JOIN product.products p ON p.id = pi.product_id JOIN product.products p ON p.id = pi.product_id
WHERE pi.id = $2 WHERE pi.id = $2
RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, version, created_at, updated_at RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at
`, inventoryID, skuID, availableQuantity) `, inventoryID, skuID, stockQuantity)
inventory, err := scanInventory(row) inventory, err := scanInventory(row)
if err != nil { if err != nil {
return nil, fmt.Errorf("insert sku inventory %s: %w", formatID(skuID), err) return nil, fmt.Errorf("insert sku inventory %s: %w", formatID(skuID), err)
@ -2331,15 +2331,15 @@ RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, versio
return inventory, nil return inventory, nil
} }
func updateSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQuantity int32) (*InventoryRecord, error) { func updateSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, stockQuantity int32) (*InventoryRecord, error) {
row := tx.QueryRowContext(ctx, ` row := tx.QueryRowContext(ctx, `
UPDATE product.product_item_inventory UPDATE product.product_item_inventory
SET available_quantity = $2, SET stock_quantity = $2,
version = version + 1, version = version + 1,
updated_at = NOW() updated_at = NOW()
WHERE sku_id = $1 WHERE sku_id = $1
RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, version, created_at, updated_at RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at
`, skuID, availableQuantity) `, skuID, stockQuantity)
inventory, err := scanInventory(row) inventory, err := scanInventory(row)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("update sku inventory %s: %w", formatID(skuID), ErrSKUNotFound) return nil, fmt.Errorf("update sku inventory %s: %w", formatID(skuID), ErrSKUNotFound)
@ -2454,7 +2454,7 @@ SELECT pi.id,
pi.updated_at, pi.updated_at,
inv.id, inv.id,
inv.sku_id, inv.sku_id,
inv.available_quantity, inv.stock_quantity,
inv.locked_quantity, inv.locked_quantity,
inv.sold_quantity, inv.sold_quantity,
inv.version, inv.version,
@ -2523,7 +2523,7 @@ SELECT pi.id,
pi.updated_at, pi.updated_at,
inv.id, inv.id,
inv.sku_id, inv.sku_id,
inv.available_quantity, inv.stock_quantity,
inv.locked_quantity, inv.locked_quantity,
inv.sold_quantity, inv.sold_quantity,
inv.version, inv.version,
@ -2577,7 +2577,7 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) {
&imageIDsJSON, &imageIDsJSON,
&rec.Price, &rec.Price,
&rec.SoldQuantity, &rec.SoldQuantity,
&rec.AvailableQuantity, &rec.StockQuantity,
&rec.LockedQuantity, &rec.LockedQuantity,
); err != nil { ); err != nil {
return nil, fmt.Errorf("scan category product: %w", err) return nil, fmt.Errorf("scan category product: %w", err)
@ -2696,7 +2696,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) {
deletedAt sql.NullTime deletedAt sql.NullTime
inventoryID sql.NullInt64 inventoryID sql.NullInt64
inventorySKUID sql.NullInt64 inventorySKUID sql.NullInt64
availableQuantity sql.NullInt32 stockQuantity sql.NullInt32
lockedQuantity sql.NullInt32 lockedQuantity sql.NullInt32
soldQuantity sql.NullInt32 soldQuantity sql.NullInt32
inventoryVersion sql.NullInt32 inventoryVersion sql.NullInt32
@ -2720,7 +2720,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) {
&rec.UpdatedAt, &rec.UpdatedAt,
&inventoryID, &inventoryID,
&inventorySKUID, &inventorySKUID,
&availableQuantity, &stockQuantity,
&lockedQuantity, &lockedQuantity,
&soldQuantity, &soldQuantity,
&inventoryVersion, &inventoryVersion,
@ -2758,12 +2758,12 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) {
} }
if inventoryID.Valid { if inventoryID.Valid {
rec.Inventory = &InventoryRecord{ rec.Inventory = &InventoryRecord{
ID: formatID(inventoryID.Int64), ID: formatID(inventoryID.Int64),
SKUID: formatID(inventorySKUID.Int64), SKUID: formatID(inventorySKUID.Int64),
AvailableQuantity: nullInt32Value(availableQuantity), StockQuantity: nullInt32Value(stockQuantity),
LockedQuantity: nullInt32Value(lockedQuantity), LockedQuantity: nullInt32Value(lockedQuantity),
SoldQuantity: nullInt32Value(soldQuantity), SoldQuantity: nullInt32Value(soldQuantity),
Version: nullInt32Value(inventoryVersion), Version: nullInt32Value(inventoryVersion),
} }
if inventoryCreatedAt.Valid { if inventoryCreatedAt.Valid {
rec.Inventory.CreatedAt = inventoryCreatedAt.Time rec.Inventory.CreatedAt = inventoryCreatedAt.Time
@ -2771,7 +2771,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) {
if inventoryUpdatedAt.Valid { if inventoryUpdatedAt.Valid {
rec.Inventory.UpdatedAt = inventoryUpdatedAt.Time rec.Inventory.UpdatedAt = inventoryUpdatedAt.Time
} }
rec.AvailableQuantity = rec.Inventory.AvailableQuantity rec.StockQuantity = rec.Inventory.StockQuantity
rec.LockedQuantity = rec.Inventory.LockedQuantity rec.LockedQuantity = rec.Inventory.LockedQuantity
rec.SoldQuantity = rec.Inventory.SoldQuantity rec.SoldQuantity = rec.Inventory.SoldQuantity
} }
@ -2787,7 +2787,7 @@ func scanInventory(scanner rowScanner) (*InventoryRecord, error) {
if err := scanner.Scan( if err := scanner.Scan(
&id, &id,
&skuID, &skuID,
&rec.AvailableQuantity, &rec.StockQuantity,
&rec.LockedQuantity, &rec.LockedQuantity,
&rec.SoldQuantity, &rec.SoldQuantity,
&rec.Version, &rec.Version,

View File

@ -1411,9 +1411,9 @@ func skuUpdateFromProto(input *productv1.PatchExistingSKU) (repository.SKUUpdate
case "price": case "price":
value := input.GetPrice() value := input.GetPrice()
update.Price = &value update.Price = &value
case "available_quantity": case "stock_quantity":
value := input.GetAvailableQuantity() value := input.GetStockQuantity()
update.AvailableQuantity = &value update.StockQuantity = &value
case "status": case "status":
value := input.GetStatus() value := input.GetStatus()
update.Status = &value update.Status = &value
@ -1448,7 +1448,7 @@ func toProtoSKUChangeResult(result *repository.SKUChangeResult) *productv1.SKUCh
func hasSellableSKURecord(skus []repository.SKURecord) bool { func hasSellableSKURecord(skus []repository.SKURecord) bool {
for _, sku := range skus { for _, sku := range skus {
if sku.Status == 1 && sku.AvailableQuantity > 0 { if sku.Status == 1 && sku.StockQuantity > sku.LockedQuantity {
return true return true
} }
} }
@ -1463,8 +1463,8 @@ func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord,
if sku.GetPrice() < 0 { if sku.GetPrice() < 0 {
return repository.SKURecord{}, errors.New("price must be greater than or equal to 0") return repository.SKURecord{}, errors.New("price must be greater than or equal to 0")
} }
if sku.GetAvailableQuantity() < 0 { if sku.GetStockQuantity() < 0 {
return repository.SKURecord{}, errors.New("available_quantity must be greater than or equal to 0") return repository.SKURecord{}, errors.New("stock_quantity must be greater than or equal to 0")
} }
attrs, derivedName, err := buildSKUAttributesAndName(sku) attrs, derivedName, err := buildSKUAttributesAndName(sku)
@ -1481,19 +1481,19 @@ func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord,
} }
return repository.SKURecord{ return repository.SKURecord{
SKUNo: strings.TrimSpace(sku.GetSkuNo()), SKUNo: strings.TrimSpace(sku.GetSkuNo()),
Name: name, Name: name,
Price: sku.GetPrice(), Price: sku.GetPrice(),
ImageIDs: normalizeStringList(sku.GetImageIds()), ImageIDs: normalizeStringList(sku.GetImageIds()),
AvailableQuantity: sku.GetAvailableQuantity(), StockQuantity: sku.GetStockQuantity(),
AttributesJSON: attrs, AttributesJSON: attrs,
K1: strings.TrimSpace(sku.GetK1()), K1: strings.TrimSpace(sku.GetK1()),
V1: strings.TrimSpace(sku.GetV1()), V1: strings.TrimSpace(sku.GetV1()),
K2: strings.TrimSpace(sku.GetK2()), K2: strings.TrimSpace(sku.GetK2()),
V2: strings.TrimSpace(sku.GetV2()), V2: strings.TrimSpace(sku.GetV2()),
K3: strings.TrimSpace(sku.GetK3()), K3: strings.TrimSpace(sku.GetK3()),
V3: strings.TrimSpace(sku.GetV3()), V3: strings.TrimSpace(sku.GetV3()),
Status: statusValue, Status: statusValue,
}, nil }, nil
} }
@ -1691,29 +1691,29 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
protoSKUs := make([]*productv1.SKU, 0, len(skus)) protoSKUs := make([]*productv1.SKU, 0, len(skus))
for _, sku := range skus { for _, sku := range skus {
protoSKUs = append(protoSKUs, &productv1.SKU{ protoSKUs = append(protoSKUs, &productv1.SKU{
SkuId: sku.ID, SkuId: sku.ID,
ProductId: sku.ProductID, ProductId: sku.ProductID,
SkuNo: sku.SKUNo, SkuNo: sku.SKUNo,
Name: sku.Name, Name: sku.Name,
Price: sku.Price, Price: sku.Price,
AvailableQuantity: sku.AvailableQuantity, StockQuantity: sku.StockQuantity,
SoldQuantity: sku.SoldQuantity, SoldQuantity: sku.SoldQuantity,
AttributesJson: sku.AttributesJSON, AttributesJson: sku.AttributesJSON,
Status: sku.Status, Status: sku.Status,
ImageIds: sku.ImageIDs, ImageIds: sku.ImageIDs,
K1: sku.K1, K1: sku.K1,
V1: sku.V1, V1: sku.V1,
K2: sku.K2, K2: sku.K2,
V2: sku.V2, V2: sku.V2,
K3: sku.K3, K3: sku.K3,
V3: sku.V3, V3: sku.V3,
IsArchived: sku.IsArchived, IsArchived: sku.IsArchived,
ArchivedAt: timePtrToMillisString(sku.ArchivedAt), ArchivedAt: timePtrToMillisString(sku.ArchivedAt),
Version: sku.Version, Version: sku.Version,
DeletedAt: timePtrToMillisString(sku.DeletedAt), DeletedAt: timePtrToMillisString(sku.DeletedAt),
CreatedAt: timeToMillisString(sku.CreatedAt), CreatedAt: timeToMillisString(sku.CreatedAt),
UpdatedAt: timeToMillisString(sku.UpdatedAt), UpdatedAt: timeToMillisString(sku.UpdatedAt),
Inventory: toProtoInventory(sku.Inventory), Inventory: toProtoInventory(sku.Inventory),
}) })
} }
@ -1768,7 +1768,7 @@ func toProtoCartItemProduct(lineID string, record repository.CartItemProductReco
result.SkuName = record.SKU.Name result.SkuName = record.SKU.Name
result.Price = record.SKU.Price result.Price = record.SKU.Price
result.SkuImageIds = record.SKU.ImageIDs result.SkuImageIds = record.SKU.ImageIDs
result.SkuAvailableQuantity = record.SKU.AvailableQuantity result.SkuStockQuantity = record.SKU.StockQuantity
result.SkuLockedQuantity = record.SKU.LockedQuantity result.SkuLockedQuantity = record.SKU.LockedQuantity
result.SkuStatus = record.SKU.Status result.SkuStatus = record.SKU.Status
result.SkuIsArchived = record.SKU.IsArchived result.SkuIsArchived = record.SKU.IsArchived
@ -1780,17 +1780,17 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv
return nil return nil
} }
return &productv1.CategoryProduct{ return &productv1.CategoryProduct{
UpdatedAt: timeToMillisString(product.UpdatedAt), UpdatedAt: timeToMillisString(product.UpdatedAt),
CreatedAt: timeToMillisString(product.CreatedAt), CreatedAt: timeToMillisString(product.CreatedAt),
Title: product.Title, Title: product.Title,
ProductId: product.ID, ProductId: product.ID,
SpuNo: product.SPUNo, SpuNo: product.SPUNo,
Status: product.Status, Status: product.Status,
ImageIds: product.ImageIDs, ImageIds: product.ImageIDs,
Price: product.Price, Price: product.Price,
SoldQuantity: product.SoldQuantity, SoldQuantity: product.SoldQuantity,
AvailableQuantity: product.AvailableQuantity, StockQuantity: product.StockQuantity,
LockedQuantity: product.LockedQuantity, LockedQuantity: product.LockedQuantity,
} }
} }
@ -1799,14 +1799,14 @@ func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductI
return nil return nil
} }
return &productv1.ProductItemInventory{ return &productv1.ProductItemInventory{
InventoryId: inventory.ID, InventoryId: inventory.ID,
SkuId: inventory.SKUID, SkuId: inventory.SKUID,
AvailableQuantity: inventory.AvailableQuantity, StockQuantity: inventory.StockQuantity,
LockedQuantity: inventory.LockedQuantity, LockedQuantity: inventory.LockedQuantity,
SoldQuantity: inventory.SoldQuantity, SoldQuantity: inventory.SoldQuantity,
Version: inventory.Version, Version: inventory.Version,
CreatedAt: timeToMillisString(inventory.CreatedAt), CreatedAt: timeToMillisString(inventory.CreatedAt),
UpdatedAt: timeToMillisString(inventory.UpdatedAt), UpdatedAt: timeToMillisString(inventory.UpdatedAt),
} }
} }

View File

@ -207,7 +207,7 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory (
sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
spu_no VARCHAR(100), spu_no VARCHAR(100),
sku_no VARCHAR(100), sku_no VARCHAR(100),
available_quantity INTEGER NOT NULL DEFAULT 0 CHECK (available_quantity >= 0), stock_quantity INTEGER NOT NULL DEFAULT 0 CHECK (stock_quantity >= 0),
locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0), locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0),
sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0), sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0),
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
@ -216,11 +216,11 @@ 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)
); );
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 编码冗余字段,用于库存查询和对账';
COMMENT ON COLUMN product.product_item_inventory.sku_no IS '商品 SKU 编码冗余字段,用于库存查询和对账'; COMMENT ON COLUMN product.product_item_inventory.sku_no IS '商品 SKU 编码冗余字段,用于库存查询和对账';
COMMENT ON COLUMN product.product_item_inventory.available_quantity IS 'SKU 当前可售库存'; COMMENT ON COLUMN product.product_item_inventory.stock_quantity IS 'SKU 当前库存池数量,净可售=stock_quantity-locked_quantity';
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 '库存乐观锁版本号';

View File

@ -0,0 +1,5 @@
ALTER TABLE product.product_item_inventory
RENAME COLUMN available_quantity TO stock_quantity;
COMMENT ON TABLE product.product_item_inventory IS '商品 SKU 库存销量表:存储库存池、锁定库存和已售数量';
COMMENT ON COLUMN product.product_item_inventory.stock_quantity IS 'SKU 当前库存池数量,净可售=stock_quantity-locked_quantity';