Hi @Botble ,
I’m working on a Ninico project with a cart system for variable products, and I’m encountering an issue with product stock management.
The Problem:
I have a product with 2 units in stock. When I add the first item to the cart, it works as expected. However, when I try to add the second item, I receive a message saying the product is out of stock, even though there should still be one unit available.
This issue also happens when I have a product with 4 units in stock: I can add 3 items without any problem, but when I try to add the 4th one, it incorrectly says the product is out of stock.
Debugging:
After looking into the code, I found that the product quantity is being decremented twice—once before checking the cart and again when updating the cart item. Here’s the relevant code:
File: platform\plugins\ecommerce\src\Http\Controllers\Fronts\PublicCartController.php
Line number: 99
$product->quantity -= $request->input('qty', 1);
$outOfQuantity = false;
foreach (Cart::instance('cart')->content() as $item) {
if ($item->id == $product->id) {
$originalQuantity = $product->quantity;
$product->quantity = (int) $product->quantity - $item->qty;
if ($product->quantity < 0) {
$product->quantity = 0;
}
if ($product->isOutOfStock()) {
$outOfQuantity = true;
break;
}
$product->quantity = $originalQuantity;
}
}
Is this double decrement causing the issue, and what is the best way to fix it? I’m reducing the product stock in two places: once when I receive the request and again during the loop when checking cart items.
Any advice or insights would be greatly appreciated!
Thanks!