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
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