【代码修复】MALL:更新库存时,同时更新销量,和 taobao 保持一致的逻辑

This commit is contained in:
YunaiV 2024-07-23 12:39:04 +08:00
parent a55ca87709
commit 714f0be547
2 changed files with 20 additions and 7 deletions

View File

@ -26,7 +26,7 @@ public interface ProductSkuMapper extends BaseMapperX<ProductSkuDO> {
}
/**
* 更新 SKU 库存增加
* 更新 SKU 库存增加销量减少
*
* @param id 编号
* @param incrCount 增加库存正数
@ -34,13 +34,14 @@ public interface ProductSkuMapper extends BaseMapperX<ProductSkuDO> {
default void updateStockIncr(Long id, Integer incrCount) {
Assert.isTrue(incrCount > 0);
LambdaUpdateWrapper<ProductSkuDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<ProductSkuDO>()
.setSql(" stock = stock + " + incrCount)
.setSql(" stock = stock + " + incrCount
+ ", sales_count = sales_count - " + incrCount)
.eq(ProductSkuDO::getId, id);
update(null, lambdaUpdateWrapper);
}
/**
* 更新 SKU 库存减少
* 更新 SKU 库存减少销量增加
*
* @param id 编号
* @param incrCount 减少库存负数
@ -48,10 +49,12 @@ public interface ProductSkuMapper extends BaseMapperX<ProductSkuDO> {
*/
default int updateStockDecr(Long id, Integer incrCount) {
Assert.isTrue(incrCount < 0);
incrCount = - incrCount; // 取正
LambdaUpdateWrapper<ProductSkuDO> updateWrapper = new LambdaUpdateWrapper<ProductSkuDO>()
.setSql(" stock = stock + " + incrCount) // 负数所以使用 +
.setSql(" stock = stock - " + incrCount
+ ", sales_count = sales_count + " + incrCount)
.eq(ProductSkuDO::getId, id)
.ge(ProductSkuDO::getStock, -incrCount); // cas 逻辑
.ge(ProductSkuDO::getStock, incrCount);
return update(null, updateWrapper);
}

View File

@ -85,9 +85,19 @@ public interface ProductSpuMapper extends BaseMapperX<ProductSpuDO> {
* @param incrCount 增加的库存数量
*/
default void updateStock(Long id, Integer incrCount) {
// 拼接 SQL
if (incrCount == 0) {
return;
}
String sql;
if (incrCount > 0) {
sql = " stock = stock + " + incrCount + ", sales_count = sales_count - " + incrCount;
} else {
sql = " stock = stock - " + Math.abs(incrCount) + ", sales_count = sales_count + " + Math.abs(incrCount);
}
// 执行更新
LambdaUpdateWrapper<ProductSpuDO> updateWrapper = new LambdaUpdateWrapper<ProductSpuDO>()
// 负数所以使用 +
.setSql(" stock = stock +" + incrCount)
.setSql(sql)
.eq(ProductSpuDO::getId, id);
update(null, updateWrapper);
}