fix(api): decrement SKU stock only when remaining quantity is sufficient

Prevent oversell by conditioning stock updates and locking SKUs in primary-key order, and record the same concurrent-counter rule in the API spec and agent guide.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Chengdong Zhang
2026-09-18 17:41:06 +08:00
co-authored by Cursor
parent 53548196f8
commit 835afbe5e0
4 changed files with 32 additions and 6 deletions
+1 -1
View File
@@ -15,7 +15,7 @@
- **金额**`i64`/`number` 最小单位 + 币种码;换算走后端 `/api/currencies/convert` 或共享 `formatMoney(minor, code, exponent, locale)`。**禁止浮点金额运算**,禁止在前端硬编码 exponent=2(JPY 是 0)——用币种表里的 exponent。
- **i18n 内容**:凡是面向用户的内容字段都是 `{"en","zh"}` JSONBUI 文案一律 `$t()`,缺键加到本应用的 `locales-extra.ts`**不要**从应用代理改 `packages/shared` 语言包以外的文件(共享包改动属契约变更,需谨慎并跑齐三个构建)。
- **TS 纪律**:禁止 `any`/`as any`/`@ts-ignore`;外部数据用类型守卫或 schema 校验;客户端方法类型在 `@vmall/shared` 命名导出。
- **Rust 纪律**:错误统一 `ApiError``{"error":{"code","message"}}`);SQL 用 `sqlx::query*` + 显式 bind;状态迁移必须校验前置状态(参考 orders/shipments 的 `UPDATE ... WHERE status = ...` 模式)。
- **Rust 纪律**:错误统一 `ApiError``{"error":{"code","message"}}`);SQL 用 `sqlx::query*` + 显式 bind;状态迁移必须校验前置状态(参考 orders/shipments 的 `UPDATE ... WHERE status = ...` 模式)。**并发计数扣减**(目前只有 `skus.stock`):多行 `FOR UPDATE` 必须先 `ORDER BY` 主键;扣减必须 `SET col = col - $qty WHERE id = $1 AND col >= $qty``rows_affected = 0``Conflict`。禁止无条件 `SET col = col - n`。回补用 `col = col + n`,不要用读出的绝对值写回。商家覆盖赋值(`SET stock = $n`)不是扣减,不走此模式。
- **RBAC**:受保护路由声明角色(`auth.require(&[...])`);店铺资源必须过 `auth.own_shop()` 作用域,跨店返回 404。
## 开发流程(OpenSpec
+11 -5
View File
@@ -184,11 +184,16 @@ pub async fn insert_item(
}
pub async fn decrement_stock(tx: &mut PgConnection, sku_id: Uuid, qty: i32) -> ApiResult<()> {
sqlx::query("UPDATE skus SET stock = stock - $2 WHERE id = $1")
.bind(sku_id)
.bind(qty)
.execute(&mut *tx)
.await?;
let result = sqlx::query(
"UPDATE skus SET stock = stock - $2 WHERE id = $1 AND stock >= $2",
)
.bind(sku_id)
.bind(qty)
.execute(&mut *tx)
.await?;
if result.rows_affected() == 0 {
return Err(ApiError::Conflict("insufficient stock".into()));
}
Ok(())
}
@@ -329,6 +334,7 @@ pub async fn lock_purchasable_skus(
JOIN shops sh ON sh.id = p.shop_id
WHERE s.id = ANY($1) AND s.active = TRUE
AND p.status = 'published' AND sh.status = 'active'
ORDER BY s.id
FOR UPDATE OF s",
)
.bind(sku_ids)
+19
View File
@@ -79,6 +79,25 @@ async fn checkout_rejects_empty_cart() {
assert!(matches!(err, ApiError::BadRequest(m) if m.contains("empty")));
}
#[tokio::test]
#[serial]
async fn decrement_stock_rejects_when_guard_fails() {
let state = common::spawn_state().await;
let sku_id = sellable_sku(&state, "guard", 100, 1).await;
let mut tx = state.db.begin().await.unwrap();
let err = order::repo::decrement_stock(&mut tx, sku_id, 2)
.await
.unwrap_err();
tx.rollback().await.unwrap();
assert!(matches!(err, ApiError::Conflict(m) if m.contains("insufficient stock")));
let left: i32 = sqlx::query_scalar("SELECT stock FROM skus WHERE id = $1")
.bind(sku_id)
.fetch_one(&state.db)
.await
.unwrap();
assert_eq!(left, 1);
}
#[tokio::test]
#[serial]
async fn checkout_rejects_insufficient_stock() {
+1
View File
@@ -28,6 +28,7 @@ Implementation considerations
- **Money:** `i64` minor units + ISO code; `money::convert_minor` is a pure function, not a repository.
- **SQL:** `sqlx::query*` / `query_as` with explicit binds. Prefer column lists over `SELECT *` on `users` (use `USER_COLUMNS` + `User` row vs `UserPublic` JSON).
- **State machines:** `UPDATE … WHERE status = …`; zero rows → `ApiError::Conflict`, never a silent no-op success.
- **Concurrent counters:** any column that concurrent requests decrement (today: `skus.stock`) follows the same “predicate or it did not happen” rule as status. `SELECT … FOR UPDATE` of multiple rows MUST `ORDER BY` the primary key so lock order is global. Decrement MUST be `UPDATE … SET col = col - $qty WHERE id = $1 AND col >= $qty`; `rows_affected = 0``Conflict` (do not rely on `CHECK (col >= 0)` as the only signal). Restore with `col = col + n`, never `SET col = $absolute` from a stale read. Merchant overwrite (`SET stock = $n` on SKU upsert) is assignment, not decrement. Remaining shipment qty is not a stored counter: `create` serializes on `orders … FOR UPDATE` and checks remainder in that transaction.
- **RBAC:** `AuthUser::require`, `require_customer`, `require_admin`, `require_shop` / `own_shop`. Cross-shop resource access is 404, not 403.
High-level request flow