diff --git a/app/Endpoint/Api/Http/Controllers/ShoppingCartItemController.php b/app/Endpoint/Api/Http/Controllers/ShoppingCartItemController.php index 112aa77d..da2504dc 100644 --- a/app/Endpoint/Api/Http/Controllers/ShoppingCartItemController.php +++ b/app/Endpoint/Api/Http/Controllers/ShoppingCartItemController.php @@ -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, diff --git a/app/Exceptions/ProductNotEnoughException.php b/app/Exceptions/ProductNotEnoughException.php new file mode 100644 index 00000000..e4ba8258 --- /dev/null +++ b/app/Exceptions/ProductNotEnoughException.php @@ -0,0 +1,11 @@ +