Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Grouped product frontend quantity validation added and code refactor #39480

Open
wants to merge 20 commits into
base: 2.4-develop
Choose a base branch
from
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
f990b58
Grouped product frontend quantity validation added and code refactor
Mohamed-Asar Dec 15, 2024
5f2b740
Merge branch '2.4-develop' into bug/39479-grouped-product-qty-validation
Mohamed-Asar Dec 18, 2024
52bd8e8
Merge branch '2.4-develop' of https://github.com/Mohamed-Asar/magento…
Mohamed-Asar Dec 20, 2024
94fadc8
Ignore item qty validation if zero qty entered in grouped product
Mohamed-Asar Dec 20, 2024
9ac7ef5
Merge branch 'bug/39479-grouped-product-qty-validation' of https://gi…
Mohamed-Asar Dec 20, 2024
eea8ae5
Merge branch '2.4-develop' of https://github.com/Mohamed-Asar/magento…
Mohamed-Asar Dec 30, 2024
a192377
Unit test & static test cases issues fixed
Mohamed-Asar Dec 30, 2024
ceb8597
Static test fixed
Mohamed-Asar Dec 30, 2024
3e0c5a7
Indent issue fixed
Mohamed-Asar Dec 31, 2024
4213997
Merge branch '2.4-develop' into bug/39479-grouped-product-qty-validation
engcom-Hotel Jan 23, 2025
1ca6c6d
Code review changes
Mohamed-Asar Jan 23, 2025
96bfa59
Merge branch '2.4-develop' of https://github.com/Mohamed-Asar/magento…
Mohamed-Asar Feb 18, 2025
cc2409a
Merge branch '2.4-develop' of https://github.com/Mohamed-Asar/magento…
Mohamed-Asar Mar 5, 2025
baeb177
Removed deprecated methods, get data using MSI and unit test added
Mohamed-Asar Mar 7, 2025
9a46f52
Static test case fix
Mohamed-Asar Mar 10, 2025
2e64918
Merge branch '2.4-develop' into bug/39479-grouped-product-qty-validation
engcom-Hotel Mar 11, 2025
b0ad802
Merge branch '2.4-develop' into bug/39479-grouped-product-qty-validation
engcom-Hotel Mar 14, 2025
7545bdb
Merge branch '2.4-develop' into bug/39479-grouped-product-qty-validation
engcom-Hotel Mar 26, 2025
841ffaa
Merge branch '2.4-develop' of https://github.com/Mohamed-Asar/magento…
Mohamed-Asar Apr 3, 2025
559d0f8
Test case failures fix
Mohamed-Asar Apr 3, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 17 additions & 24 deletions app/code/Magento/CatalogInventory/Block/Plugin/ProductView.php
Original file line number Diff line number Diff line change
@@ -1,53 +1,46 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
* Copyright 2015 Adobe
* All Rights Reserved.
*/
namespace Magento\CatalogInventory\Block\Plugin;

use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\Catalog\Block\Product\View;
use Magento\CatalogInventory\Model\Product\QuantityValidator;

class ProductView
{
/**
* @var StockRegistryInterface
* @var QuantityValidator
*/
private $stockRegistry;
private $productQuantityValidator;

/**
* @param StockRegistryInterface $stockRegistry
* @param QuantityValidator $productQuantityValidator
*/
public function __construct(
StockRegistryInterface $stockRegistry
QuantityValidator $productQuantityValidator
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use ObjectManager to initialize as this change is BiC.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

) {
$this->stockRegistry = $stockRegistry;
$this->productQuantityValidator = $productQuantityValidator;
}

/**
* Adds quantities validator.
*
* @param \Magento\Catalog\Block\Product\View $block
* @param View $block
* @param array $validators
* @return array
*/
public function afterGetQuantityValidators(
\Magento\Catalog\Block\Product\View $block,
View $block,
array $validators
) {
$stockItem = $this->stockRegistry->getStockItem(
$block->getProduct()->getId(),
$block->getProduct()->getStore()->getWebsiteId()
return array_merge(
$validators,
$this->productQuantityValidator->getData(
$block->getProduct()->getSku(),
$block->getProduct()->getStore()->getWebsiteId()
)
);

$params = [];
if ($stockItem->getMaxSaleQty()) {
$params['maxAllowed'] = (float)$stockItem->getMaxSaleQty();
}
if ($stockItem->getQtyIncrements() > 0) {
$params['qtyIncrements'] = (float)$stockItem->getQtyIncrements();
}
$validators['validate-item-quantity'] = $params;

return $validators;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php
/**
* Copyright 2024 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);

namespace Magento\CatalogInventory\Model\Product;

use Magento\Framework\Exception\LocalizedException;
use Magento\InventoryConfigurationApi\Api\GetStockItemConfigurationInterface;
use Magento\InventorySalesApi\Api\StockResolverInterface;
use Magento\InventorySalesApi\Api\Data\SalesChannelInterface;
use Magento\Store\Model\StoreManagerInterface;

class QuantityValidator
{
/**
* @param GetStockItemConfigurationInterface $getStockItemConfiguration
* @param StoreManagerInterface $storeManager
* @param StockResolverInterface $stockResolver
*/
public function __construct(
private readonly GetStockItemConfigurationInterface $getStockItemConfiguration,
private readonly StoreManagerInterface $storeManager,
private readonly StockResolverInterface $stockResolver
) {
}

/**
* To get quantity validators
*
* @param string $sku
* @param int|null $websiteId
*
* @return array
*/
public function getData(string $sku, int|null $websiteId): array
{
try {
$stockItemConfig = $this->getStockItemConfiguration->execute(
$sku,
$this->getStockId($websiteId)
);

$params = [];
$validators = [];
$params['minAllowed'] = $stockItemConfig->getMinSaleQty();

if ($stockItemConfig->getMaxSaleQty()) {
$params['maxAllowed'] = $stockItemConfig->getMaxSaleQty();
}
if ($stockItemConfig->getQtyIncrements() > 0) {
$params['qtyIncrements'] = $stockItemConfig->getQtyIncrements();
}
$validators['validate-item-quantity'] = $params;

return $validators;
} catch (\Exception $e) {
return [];
}
}

/**
* Get Stock ID by Website ID
*
* @param int|null $websiteId
* @return int
* @throws LocalizedException
*/
private function getStockId(?int $websiteId): int
{
if ($websiteId === null) {
$websiteId = $this->storeManager->getWebsite()->getId();
}

$websiteCode = $this->storeManager->getWebsite($websiteId)->getCode();
$stock = $this->stockResolver->execute(
SalesChannelInterface::TYPE_WEBSITE,
$websiteCode
);

return (int) $stock->getStockId();
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
<?php
/**
* Copyright 2025 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);

namespace Magento\CatalogInventory\Test\Unit\Model\Product;

use Magento\CatalogInventory\Model\Product\QuantityValidator;
use Magento\InventoryConfigurationApi\Api\GetStockItemConfigurationInterface;
use Magento\InventoryConfigurationApi\Api\Data\StockItemConfigurationInterface;
use Magento\InventorySalesApi\Api\Data\SalesChannelInterface;
use Magento\InventoryApi\Api\Data\StockInterface;
use Magento\InventorySalesApi\Api\StockResolverInterface;
use Magento\Store\Api\Data\WebsiteInterface;
use Magento\Store\Model\StoreManagerInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;

/**
* @covers \Magento\CatalogInventory\Model\Product\QuantityValidator
*/
class QuantityValidatorTest extends TestCase
{
private const WEBSITE_ID = 1;
private const WEBSITE_CODE = 'base';
private const STOCK_ID = 1;
private const TEST_SKU = 'TEST-SKU';

/**
* @var QuantityValidator
*/
private $quantityValidator;

/**
* @var GetStockItemConfigurationInterface|MockObject
*/
private $getStockItemConfiguration;

/**
* @var StoreManagerInterface|MockObject
*/
private $storeManager;

/**
* @var StockResolverInterface|MockObject
*/
private $stockResolver;

protected function setUp(): void
{
$this->getStockItemConfiguration = $this->createMock(GetStockItemConfigurationInterface::class);
$this->storeManager = $this->createMock(StoreManagerInterface::class);
$this->stockResolver = $this->createMock(StockResolverInterface::class);

$this->quantityValidator = new QuantityValidator(
$this->getStockItemConfiguration,
$this->storeManager,
$this->stockResolver
);
}

public function testGetDataWithValidators(): void
{
$website = $this->createMock(WebsiteInterface::class);
$website->method('getCode')->willReturn(self::WEBSITE_CODE);

$stock = $this->createMock(StockInterface::class);
$stock->method('getStockId')->willReturn(self::STOCK_ID);

$stockItemConfiguration = $this->createMock(StockItemConfigurationInterface::class);
$stockItemConfiguration->method('getMinSaleQty')->willReturn(2.0);
$stockItemConfiguration->method('getMaxSaleQty')->willReturn(10.0);
$stockItemConfiguration->method('getQtyIncrements')->willReturn(2.0);

// Set expectations
$this->storeManager->expects($this->once())
->method('getWebsite')
->with(self::WEBSITE_ID)
->willReturn($website);

$this->stockResolver->expects($this->once())
->method('execute')
->with(SalesChannelInterface::TYPE_WEBSITE, self::WEBSITE_CODE)
->willReturn($stock);

$this->getStockItemConfiguration->expects($this->once())
->method('execute')
->with(self::TEST_SKU, self::STOCK_ID)
->willReturn($stockItemConfiguration);

$expected = [
'validate-item-quantity' => [
'minAllowed' => 2,
'maxAllowed' => 10,
'qtyIncrements' => 2.0
]
];

$result = $this->quantityValidator->getData(self::TEST_SKU, self::WEBSITE_ID);
$this->assertEquals($expected, $result);
}
}
6 changes: 4 additions & 2 deletions app/code/Magento/CatalogInventory/etc/module.xml
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
* Copyright 2011 Adobe
* All Rights Reserved.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Magento_CatalogInventory" >
<sequence>
<module name="Magento_Catalog"/>
<module name="Magento_InventoryConfigurationApi"/>
<module name="Magento_InventorySalesApi"/>
</sequence>
</module>
</config>
46 changes: 46 additions & 0 deletions app/code/Magento/GroupedProduct/ViewModel/ValidateQuantity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php
/**
* Copyright 2024 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);

namespace Magento\GroupedProduct\ViewModel;

use Magento\CatalogInventory\Model\Product\QuantityValidator;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\View\Element\Block\ArgumentInterface;

/**
* ViewModel for Grouped Products Block
*/
class ValidateQuantity implements ArgumentInterface
{
/**
* @param Json $serializer
* @param QuantityValidator $productQuantityValidator
*/
public function __construct(
private readonly Json $serializer,
private readonly QuantityValidator $productQuantityValidator,
) {
}

/**
* To get the quantity validators
*
* @param string $sku
* @param int|null $websiteId
*
* @return string
*/
public function getQuantityValidators(string $sku, int|null $websiteId): string
{
return $this->serializer->serialize(
array_merge(
['validate-grouped-qty' => '#super-product-table'],
$this->productQuantityValidator->getData($sku, $websiteId)
)
);
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Copyright 2015 Adobe
* All Rights Reserved.
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<attribute name="class" value="page-product-grouped"/>
<referenceContainer name="product.info.form.content">
<block class="Magento\GroupedProduct\Block\Product\View\Type\Grouped" name="product.info.grouped" before="product.info.addtocart" template="Magento_GroupedProduct::product/view/type/grouped.phtml"/>
<block class="Magento\GroupedProduct\Block\Product\View\Type\Grouped" name="product.info.grouped" before="product.info.addtocart" template="Magento_GroupedProduct::product/view/type/grouped.phtml">
<arguments>
<argument name="validateQuantityViewModel" xsi:type="object">Magento\GroupedProduct\ViewModel\ValidateQuantity</argument>
</arguments>
</block>
<container name="product.info.grouped.extra" after="product.info.grouped" before="product.info.grouped" as="product_type_data_extra" label="Product Extra Info"/>
</referenceContainer>
<referenceContainer name="product.info.grouped.extra">
Original file line number Diff line number Diff line change
@@ -1,31 +1,34 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
* Copyright 2015 Adobe
* All Rights Reserved.
*/

/**
* Grouped product data template
*
* @var $block \Magento\Catalog\Block\Product\View\BaseImage
* @var $block \Magento\GroupedProduct\Block\Product\View\Type\Grouped
* @var $escaper \Magento\Framework\Escaper
*/
?>
<?php $block->setPreconfiguredValue(); ?>
<?php $_product = $block->getProduct(); ?>
<?php $_associatedProducts = $block->getAssociatedProducts(); ?>
<?php $_hasAssociatedProducts = count($_associatedProducts) > 0; ?>
<?php
$block->setPreconfiguredValue();
$_product = $block->getProduct();
$_associatedProducts = $block->getAssociatedProducts();
$_hasAssociatedProducts = count($_associatedProducts) > 0;
$viewModel = $block->getData('validateQuantityViewModel');
?>

<div class="table-wrapper grouped">
<table class="table data grouped"
id="super-product-table"
data-mage-init='{ "Magento_GroupedProduct/js/product-ids-resolver": {} }'>
<caption class="table-caption"><?= $block->escapeHtml(__('Grouped product items')) ?></caption>
<caption class="table-caption"><?= $escaper->escapeHtml(__('Grouped product items')) ?></caption>
<thead>
<tr>
<th class="col item" scope="col"><?= $block->escapeHtml(__('Product Name')) ?></th>
<th class="col item" scope="col"><?= $escaper->escapeHtml(__('Product Name')) ?></th>
<?php if ($_product->isSaleable()): ?>
<th class="col qty" scope="col"><?= $block->escapeHtml(__('Qty')) ?></th>
<th class="col qty" scope="col"><?= $escaper->escapeHtml(__('Qty')) ?></th>
<?php endif; ?>
</tr>
</thead>
@@ -34,30 +37,34 @@
<tbody>
<?php foreach ($_associatedProducts as $_item): ?>
<tr>
<td data-th="<?= $block->escapeHtml(__('Product Name')) ?>" class="col item">
<strong class="product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong>
<td data-th="<?= $escaper->escapeHtml(__('Product Name')) ?>" class="col item">
<strong class="product-item-name"><?= $escaper->escapeHtml($_item->getName()) ?></strong>
<?php if ($block->getCanShowProductPrice($_product)): ?>
<?php if ($block->getCanShowProductPrice($_item)): ?>
<?= /* @noEscape */ $block->getProductPrice($_item) ?>
<?php endif; ?>
<?php endif; ?>
</td>
<?php if ($_product->isSaleable()): ?>
<td data-th="<?= $block->escapeHtml(__('Qty')) ?>" class="col qty">
<td data-th="<?= $escaper->escapeHtml(__('Qty')) ?>" class="col qty">
<?php if ($_item->isSaleable()): ?>
<div class="control qty">
<input type="number"
name="super_group[<?= $block->escapeHtmlAttr($_item->getId()) ?>]"
data-selector="super_group[<?= $block->escapeHtmlAttr($_item->getId()) ?>]"
value="<?= $block->escapeHtmlAttr($_item->getQty() * 1) ?>"
title="<?= $block->escapeHtmlAttr(__('Qty')) ?>"
name="super_group[<?= $escaper->escapeHtmlAttr($_item->getId()) ?>]"
data-selector="super_group[<?= $escaper->escapeHtmlAttr($_item->getId()) ?>]"
value="<?= $escaper->escapeHtmlAttr($_item->getQty() * 1) ?>"
title="<?= $escaper->escapeHtmlAttr(__('Qty')) ?>"
class="input-text qty"
data-validate="{'validate-grouped-qty':'#super-product-table'}"
data-validate="<?= $escaper->escapeHtmlAttr($viewModel->getQuantityValidators(
$_item->getSku(),
$_item->getWebsiteId()
)) ?>"
data-no-validation-for-zero-qty="true"
data-errors-message-box="#validation-message-box"/>
</div>
<?php else: ?>
<div class="stock unavailable" title="<?= $block->escapeHtmlAttr(__('Availability')) ?>">
<span><?= $block->escapeHtml(__('Out of stock')) ?></span>
<div class="stock unavailable" title="<?= $escaper->escapeHtmlAttr(__('Availability')) ?>">
<span><?= $escaper->escapeHtml(__('Out of stock')) ?></span>
</div>
<?php endif; ?>
</td>
@@ -85,7 +92,7 @@
<tr>
<td class="unavailable"
colspan="<?php if ($_product->isSaleable()): ?>4<?php else: ?>3<?php endif; ?>">
<?= $block->escapeHtml(__('No options of this product are available.')) ?>
<?= $escaper->escapeHtml(__('No options of this product are available.')) ?>
</td>
</tr>
</tbody>
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
* Copyright 2015 Adobe
* All Rights Reserved.
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<attribute name="class" value="page-product-grouped"/>
<referenceContainer name="product.info.form.content">
<block class="Magento\GroupedProduct\Block\Product\View\Type\Grouped" name="product.info.grouped" before="product.info.addtocart" template="Magento_GroupedProduct::product/view/type/grouped.phtml"/>
<block class="Magento\GroupedProduct\Block\Product\View\Type\Grouped" name="product.info.grouped" before="product.info.addtocart" template="Magento_GroupedProduct::product/view/type/grouped.phtml">
<arguments>
<argument name="validateQuantityViewModel" xsi:type="object">Magento\GroupedProduct\ViewModel\ValidateQuantity</argument>
</arguments>
</block>
<container name="product.info.grouped.extra" after="product.info.grouped" before="product.info.grouped" as="product_type_data_extra" label="Product Extra Info"/>
</referenceContainer>
</body>
3 changes: 3 additions & 0 deletions lib/web/mage/validation.js
Original file line number Diff line number Diff line change
@@ -1643,6 +1643,9 @@ define([
isQtyIncrementsValid = typeof params.qtyIncrements === 'undefined' ||
resolveModulo(qty, $.mage.parseNumber(params.qtyIncrements)) === 0.0;

if ($(element).data('no-validation-for-zero-qty') === true && qty === 0) {
return true;
}
result = qty > 0;

if (result === false) {