diff --git a/app/Http/Controllers/User/OrderController.php b/app/Http/Controllers/User/OrderController.php index 94625726..3d0f4a94 100755 --- a/app/Http/Controllers/User/OrderController.php +++ b/app/Http/Controllers/User/OrderController.php @@ -9,6 +9,7 @@ use App\Models\Payment; use App\Services\CouponService; use App\Services\OrderService; use App\Services\PaymentService; +use App\Services\PlanService; use App\Services\UserService; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; @@ -75,7 +76,9 @@ class OrderController extends Controller abort(500, __('You have an unpaid or pending order, please try again later or cancel it')); } - $plan = Plan::find($request->input('plan_id')); + $planService = new PlanService($request->input('plan_id')); + + $plan = $planService->plan; $user = User::find($request->session()->get('id')); if (!$plan) { @@ -153,6 +156,10 @@ class OrderController extends Controller } } + if (!$planService->decrementInventory()) { + abort(500, __('Failed to create order')); + } + if (!$order->save()) { DB::rollback(); abort(500, __('Failed to create order')); diff --git a/app/Services/OrderService.php b/app/Services/OrderService.php index 792a01ec..54866a36 100644 --- a/app/Services/OrderService.php +++ b/app/Services/OrderService.php @@ -249,6 +249,11 @@ class OrderService return false; } } + $planService = new PlanService($order->plan_id); + if (!$planService->incrementInventory()) { + DB::rollBack(); + return false; + } DB::commit(); return true; } diff --git a/app/Services/PlanService.php b/app/Services/PlanService.php new file mode 100644 index 00000000..f6d771b0 --- /dev/null +++ b/app/Services/PlanService.php @@ -0,0 +1,29 @@ +plan = Plan::lockForUpdate()->find($planId); + } + + public function incrementInventory() + { + if ($this->plan->inventory_limit !== NULL) { + return $this->plan->increment('inventory_limit'); + } + } + + public function decrementInventory() + { + if ($this->plan->inventory_limit !== NULL) { + return $this->plan->decrement('inventory_limit'); + } + } +}