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 11 commits into
base: 2.4-develop
Choose a base branch
from
Open
Changes from all commits
Commits
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
39 changes: 17 additions & 22 deletions app/code/Magento/CatalogInventory/Block/Plugin/ProductView.php
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
<?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\CatalogInventory\Model\Product\QuantityValidator;
use Magento\Framework\App\ObjectManager;

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

/**
* @param StockRegistryInterface $stockRegistry
* @param QuantityValidator|null $productQuantityValidator
*/
public function __construct(
StockRegistryInterface $stockRegistry
QuantityValidator $productQuantityValidator = null
) {
$this->stockRegistry = $stockRegistry;
$this->productQuantityValidator = $productQuantityValidator ?: ObjectManager::getInstance()->get(
QuantityValidator::class
);
}

/**
@@ -34,20 +37,12 @@ public function afterGetQuantityValidators(
\Magento\Catalog\Block\Product\View $block,
array $validators
) {
$stockItem = $this->stockRegistry->getStockItem(
$block->getProduct()->getId(),
$block->getProduct()->getStore()->getWebsiteId()
return array_merge(
$validators,
$this->productQuantityValidator->getData(
$block->getProduct()->getId(),
$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,47 @@
<?php
/**
* Copyright 2024 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);

namespace Magento\CatalogInventory\Model\Product;

use Magento\CatalogInventory\Api\StockRegistryInterface;
Copy link
Contributor

Choose a reason for hiding this comment

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

interface StockRegistryInterface has been deprecated. Please use alternate.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@engcom-Hotel The alternative for that interface is the MSI module. However, some users might have the MSI module disabled, can i use that ?

Copy link
Contributor

@engcom-Hotel engcom-Hotel Jan 24, 2025

Choose a reason for hiding this comment

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

Yes @Mohamed-Asar you can use that. BTW its not recommended to disable the MSI module.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@engcom-Hotel MSI module is not included in this repo. how do i proceed ?

Copy link
Contributor

Choose a reason for hiding this comment

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

Please refer to this repo: https://github.com/magento/inventory


class QuantityValidator
{
/**
* @param StockRegistryInterface $stockRegistry
*/
public function __construct(
private readonly StockRegistryInterface $stockRegistry
) {
}

/**
* To get quantity validators
*
* @param int $productId
* @param int|null $websiteId
*
* @return array
*/
public function getData(int $productId, int|null $websiteId): array
{
$stockItem = $this->stockRegistry->getStockItem($productId, $websiteId);

$params = [];
$validators = [];
$params['minAllowed'] = $stockItem->getMinSaleQty();
if ($stockItem->getMaxSaleQty()) {
$params['maxAllowed'] = $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
@@ -1,7 +1,7 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
* Copyright 2015 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);

@@ -12,6 +12,7 @@
use Magento\CatalogInventory\Api\Data\StockItemInterface;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\CatalogInventory\Block\Plugin\ProductView;
use Magento\CatalogInventory\Model\Product\QuantityValidator;
use Magento\CatalogInventory\Model\Stock\Item;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;
use Magento\Store\Model\Store;
@@ -35,6 +36,11 @@ class ProductViewTest extends TestCase
*/
protected $stockRegistry;

/**
* @var QuantityValidator|MockObject
*/
protected $productQuantityValidator;

protected function setUp(): void
{
$objectManager = new ObjectManager($this);
@@ -47,10 +53,17 @@ protected function setUp(): void
$this->stockRegistry = $this->getMockBuilder(StockRegistryInterface::class)
->getMock();

$this->productQuantityValidator = $objectManager->getObject(
QuantityValidator::class,
[
'stockRegistry' => $this->stockRegistry
]
);

$this->block = $objectManager->getObject(
ProductView::class,
[
'stockRegistry' => $this->stockRegistry
'productQuantityValidator' => $this->productQuantityValidator
]
);
}
@@ -59,6 +72,7 @@ public function testAfterGetQuantityValidators()
{
$result = [
'validate-item-quantity' => [
'minAllowed' => 1.0,
'maxAllowed' => 5.0,
'qtyIncrements' => 3.0
]
@@ -86,9 +100,9 @@ public function testAfterGetQuantityValidators()
->method('getStockItem')
->with('productId', 'websiteId')
->willReturn($this->stockItem);
$this->stockItem->expects($this->any())->method('getMinSaleQty')->willReturn(1);
$this->stockItem->expects($this->any())->method('getMaxSaleQty')->willReturn(5);
$this->stockItem->expects($this->any())->method('getQtyIncrements')->willReturn(3);

$this->assertEquals($result, $this->block->afterGetQuantityValidators($productViewBlock, $validators));
}
}
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 int $productId
* @param int|null $websiteId
*
* @return string
*/
public function getQuantityValidators(int $productId, int|null $websiteId): string
{
return $this->serializer->serialize(
array_merge(
['validate-grouped-qty' => '#super-product-table'],
$this->productQuantityValidator->getData($productId, $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->getId(),
$_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) {