feat: stock

This commit is contained in:
2025-02-10 18:03:58 +08:00
parent c91b7c96d8
commit 387c01f91b
6 changed files with 253 additions and 1 deletions

View File

@@ -33,6 +33,11 @@ class PlaceOrderService extends BaseOrderService
$this->isAutoSelectCoupon = 2;
}
/**
* @var array
*/
private array $rollbackStockCache = [];
/**
* 统一下单逻辑
@@ -45,12 +50,16 @@ class PlaceOrderService extends BaseOrderService
$this->siteId = (int)$this->request->input('site_id');
$this->couponId = (int)$this->request->input('coupon_id',0);
// 生成购物车信息 检测商品和库存等
$this->check();
// 计算
$this->compute();
// 下单 减少库存 写入数据库
$this->placeOrder();
// 加入取消延迟队列
$this->joinCancelDelayQueue();
return $this->return->success('success',$this->orderRes);
@@ -73,22 +82,61 @@ class PlaceOrderService extends BaseOrderService
$producer->produce($message);
}
/**
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Exception
*/
private function reduceStock(): void
{
$this->rollbackStockCache = [];
foreach ($this->cartFirstData as $goodId => $stock) {
$this->rollbackStockCache[$goodId] = $stock;
if (!($this->redis->zAdd($this->stockKey,'-'.$stock,$goodId))) {
throw new Exception('cache error');
}
}
}
/**
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function rollbackStock(): void
{
if (empty($this->rollbackStockCache)) return;
foreach ($this->rollbackStockCache as $goodId => $stock) {
$this->redis->zAdd($this->stockKey,$stock,$goodId);
}
}
/**
* 下单
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function placeOrder(): void
{
try {
Db::beginTransaction();
$this->reduceStock();
$this->insertOrder();
$this->insertOrderGoods();
Db::commit();
} catch (Exception $e){
//回滚数据库 和 缓存
Db::rollBack();
$this->rollbackStock();
//意外抛出
throw new ErrException($e->getMessage());
}
}