6
0
Fork 0

购物车商品库存校验

release
李静 2021-12-10 15:22:38 +08:00
parent 74f4283a65
commit 027b869dab
2 changed files with 30 additions and 6 deletions

View File

@ -3,6 +3,7 @@
namespace App\Endpoint\Api\Http\Controllers;
use App\Endpoint\Api\Http\Resources\ShoppingCartItemResource;
use App\Exceptions\ProductNotEnoughException;
use App\Exceptions\ProductOfflineException;
use App\Models\ProductSku;
use Illuminate\Http\Request;
@ -40,7 +41,11 @@ class ShoppingCartItemController extends Controller
throw new ProductOfflineException();
}
$item = $request->user()->shoppingCartItems()->firstOrCreate([
if ($input['quantity'] > $sku->saleable_stock) {
throw new ProductNotEnoughException();
}
$shoppingCartItem = $request->user()->shoppingCartItems()->firstOrCreate([
'sku_id' => $sku->id,
], [
'name' => $sku->name,
@ -51,8 +56,12 @@ class ShoppingCartItemController extends Controller
'quantity' => $input['quantity'],
]);
if (! $item->wasRecentlyCreated) {
$item->increment('quantity', $input['quantity']);
if (! $shoppingCartItem->wasRecentlyCreated) {
if ($shoppingCartItem->quantity + $input['quantity'] > $sku->saleable_stock) {
throw new ProductNotEnoughException();
}
$shoppingCartItem->increment('quantity', $input['quantity']);
}
return response()->noContent();
@ -71,13 +80,17 @@ class ShoppingCartItemController extends Controller
'quantity' => ['bail', 'required', 'int', 'min:1'],
]);
$item = $request->user()->shoppingCartItems()->findOrFail($id);
$shoppingCartItem = $request->user()->shoppingCartItems()->findOrFail($id);
if (is_null($sku = $item->sku()->online()->first())) {
if (is_null($sku = $shoppingCartItem->sku()->online()->first())) {
throw new ProductOfflineException();
}
$item->update(array_merge($input, [
if ($input['quantity'] > $sku->saleable_stock) {
throw new ProductNotEnoughException();
}
$shoppingCartItem->update(array_merge($input, [
'name' => $sku->name,
'cover' => $sku->cover,
'sell_price' => $sku->sell_price,

View File

@ -0,0 +1,11 @@
<?php
namespace App\Exceptions;
class ProductNotEnoughException extends BizException
{
public function __construct(string $message = '商品库存不足')
{
parent::__construct($message);
}
}