Sfoglia il codice sorgente

fix(phase1): ProductService.decreaseStock 改用原子 UPDATE 防止超卖

User 3 mesi fa
parent
commit
3cf518fd07

+ 12 - 0
zxyj-backend/src/main/java/com/zxyj/common/ProductStatus.java

@@ -0,0 +1,12 @@
+package com.zxyj.common;
+
+public final class ProductStatus {
+    private ProductStatus() {}
+
+    public static final String DRAFT = "draft";
+    public static final String PENDING = "pending";
+    public static final String APPROVED = "approved";
+    public static final String REJECTED = "rejected";
+    public static final String ON_SHELF = "on_shelf";
+    public static final String OFF_SHELF = "off_shelf";
+}

+ 5 - 0
zxyj-backend/src/main/java/com/zxyj/mapper/ProductMapper.java

@@ -3,7 +3,12 @@ package com.zxyj.mapper;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.zxyj.entity.Product;
 import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Update;
 
 @Mapper
 public interface ProductMapper extends BaseMapper<Product> {
+
+    @Update("UPDATE products SET stock = stock - #{quantity}, sales_count = sales_count + #{quantity}, updated_at = NOW() WHERE id = #{productId} AND stock >= #{quantity}")
+    int decreaseStockAtomic(@Param("productId") Long productId, @Param("quantity") Integer quantity);
 }

+ 3 - 7
zxyj-backend/src/main/java/com/zxyj/service/ProductService.java

@@ -173,14 +173,10 @@ public class ProductService {
     }
 
     public boolean decreaseStock(Long productId, Integer quantity) {
-        Product product = productMapper.selectById(productId);
-        if (product == null || product.getStock() < quantity) {
+        if (quantity == null || quantity <= 0) {
             return false;
         }
-        product.setStock(product.getStock() - quantity);
-        product.setSalesCount((product.getSalesCount() != null ? product.getSalesCount() : 0) + quantity);
-        product.setUpdatedAt(new Date());
-        productMapper.updateById(product);
-        return true;
+        int rows = productMapper.decreaseStockAtomic(productId, quantity);
+        return rows > 0;
     }
 }