xin
2025-09-17 6d31d535d737ed26c4d9d61cd4e0b5483cb9b0ba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.oying.modules.pc.product.service.impl;
 
import com.oying.modules.pc.product.domain.Product;
import com.oying.modules.pc.product.mapper.ProductStockMapper;
import com.oying.modules.pc.product.service.ProductInventoryService;
import com.oying.modules.pc.product.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
@Service
@RequiredArgsConstructor
public class ProductInventoryServiceImpl implements ProductInventoryService {
 
    private final ProductStockMapper productStockMapper;
    private final ProductService productService;
 
    @Override
    public Product getProductById(Long productId) {
        return productService.getProduct(productId);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Product setStockQuantity(Long productId, Integer quantity, Long version) {
        Product existingProduct = this.getProductById(productId);
        productStockMapper.updateStock(productId, quantity, existingProduct.getVersion());
        return this.getProductById(productId);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Product increaseStock(Long productId, Integer amount) {
        Product existingProduct = this.getProductById(productId);
        productStockMapper.increaseStock(productId, amount, existingProduct.getVersion());
        return getProductById(productId);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Product decreaseStock(Long productId, Integer amount) {
        Product existingProduct = this.getProductById(productId);
        if (existingProduct.getStockQuantity() < amount) {
            throw new RuntimeException("库存不足,当前库存: " + existingProduct.getStockQuantity() + ", 请求数量: " + amount);
        }
        productStockMapper.decreaseStock(productId, amount, existingProduct.getVersion());
        return getProductById(productId);
    }
 
    @Override
    public boolean isStockSufficient(Long productId, Integer requiredAmount) {
        if (requiredAmount == null || requiredAmount <= 0) {
            throw new IllegalArgumentException("需求数量必须大于0");
        }
        Product existingProduct = this.getProductById(productId);
        return existingProduct.getStockQuantity() >= requiredAmount;
    }
 
}