Hi,
I found an issue in J2Commerce 6.6.2 that causes empty records to be created in the #__j2commerce_carts table during normal page views. The problem is in VoucherModel.php. Methods that only read or remove voucher information call getCart() with cart creation enabled. Because of this, visitors and bots can create empty carts without adding any products. After changing these calls to:
$cartHelper->getCart(0, false);
refreshing the website no longer creates empty carts. I also tested adding a product manually, and the cart was created and populated correctly. The call inside setVoucher() should remain unchanged because that is an explicit cart operation. I am including the tested patch below.
Best regards
KK
-------------------------------------
diff --git a/administrator/components/com_j2commerce/src/Model/VoucherModel.php b/administrator/components/com_j2commerce/src/Model/VoucherModel.php
--- a/administrator/components/com_j2commerce/src/Model/VoucherModel.php
+++ b/administrator/components/com_j2commerce/src/Model/VoucherModel.php
@@ -889,7 +889,9 @@ public function removeVoucher(): void
// Clear voucher from cart table
$cartHelper = CartHelper::getInstance();
- $cartTable = $cartHelper->getCart();
+ // Removing a voucher is not a reason to create an empty cart.
+ // Load an existing cart only.
+ $cartTable = $cartHelper->getCart(0, false);
if (isset($cartTable->j2commerce_cart_id) && !empty($cartTable->j2commerce_cart_id)) {
$db = $this->getDatabase();
@@ -1258,7 +1260,10 @@ public function getVoucherCode(): string
{
$session = Factory::getApplication()->getSession();
$cartHelper = CartHelper::getInstance();
- $cartTable = $cartHelper->getCart();
+
+ // This is a read operation used during ordinary page rendering.
+ // It must never create a cart as a side effect.
+ $cartTable = $cartHelper->getCart(0, false);
if (isset($cartTable->cart_voucher) && !empty($cartTable->cart_voucher)) {
$session->set('voucher', $cartTable->cart_voucher, 'j2commerce');
@@ -1281,7 +1286,10 @@ public function hasVoucher(): bool
{
$session = Factory::getApplication()->getSession();
$cartHelper = CartHelper::getInstance();
- $cartTable = $cartHelper->getCart();
+
+ // Merely checking for a voucher must not create a cart.
+ // Existing carts are still loaded normally.
+ $cartTable = $cartHelper->getCart(0, false);
if (isset($cartTable->cart_voucher) && !empty($cartTable->cart_voucher)) {
$session->set('voucher', $cartTable->cart_voucher, 'j2commerce');