【发布时间】:2016-12-15 04:27:57
【问题描述】:
我正在使用带有 Amasty_Promo 模块的 Magento 2。这个模块允许在购物车中添加一些促销/免费礼物,以违反一些购物车规则。测试用例是这样的
如果我的购物车中有一些免费/促销商品,然后如果我使用优惠券或任何错误的优惠券代码,则会从购物车中删除与免费商品/促销商品相关的先前规则。所以没有免费的礼物。
您能帮帮我,让我知道为什么会这样吗?非常感谢
【问题讨论】:
标签: magento2
我正在使用带有 Amasty_Promo 模块的 Magento 2。这个模块允许在购物车中添加一些促销/免费礼物,以违反一些购物车规则。测试用例是这样的
如果我的购物车中有一些免费/促销商品,然后如果我使用优惠券或任何错误的优惠券代码,则会从购物车中删除与免费商品/促销商品相关的先前规则。所以没有免费的礼物。
您能帮帮我,让我知道为什么会这样吗?非常感谢
【问题讨论】:
标签: magento2
我找到了原因,这是一个非常可靠的原因。
Magento 2 默认有四种规则
所以如果我们看到上面的四个规则我们就会得出一个结论
如果我们只有基于折扣的促销,上述结论是有意义的。但是,如果我们添加新规则或添加任何 3rd 方模块,例如 Amasty Promo 模块。我们还提供了一些选项来添加免费礼物相关规则。
所以现在在上述情况下,我们的网站将提供折扣和免费礼物。如果客户购物车对基于优惠券的规则和免费礼物都有折扣,那么 Magento 将仅应用基于优惠券的规则并忽略所有其他规则。
解决方案:
我们可以通过覆盖 \Magento\SalesRule\Model\Validator 来实现我们的要求
etc/di.xml 会是这样的
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<!-- We override it to apply the Amasty_Promo rules even after apply the coupon code -->
<preference for="\Magento\SalesRule\Model\Validator" type="\YourPackage\YourModule\Rewrite\SalesRule\Model\Validator" />
</config>
YourPackage\YourModule\Rewrite\SalesRule\Model\Validator.php
namespace YourPackage\YourModule\Rewrite\SalesRule\Model;
use Magento\Quote\Model\Quote\Address;
use Magento\Quote\Model\Quote\Item\AbstractItem;
class Validator extends \Magento\SalesRule\Model\Validator
{
/**
* Quote item discount calculation process
*
* @param AbstractItem $item
* @return $this
*/
public function process(AbstractItem $item)
{
$item->setDiscountAmount(0);
$item->setBaseDiscountAmount(0);
$item->setDiscountPercent(0);
$itemPrice = $this->getItemPrice($item);
if ($itemPrice < 0) {
return $this;
}
$appliedRuleIds = array();
if($this->getCouponCode()) {
$appliedRuleIds = $this->rulesApplier->applyRules(
$item,
$this->_getRules($item->getAddress()),
$this->_skipActionsValidation,
$this->getCouponCode()
);
}
$promoItemRuleIds = $this->rulesApplier->applyRules(
$item,
$this->_getPromoItemRules($item->getAddress()),
$this->_skipActionsValidation,
$this->getCouponCode()
);
$appliedRuleIds = array_merge($appliedRuleIds,$promoItemRuleIds );
$this->rulesApplier->setAppliedRuleIds($item, $appliedRuleIds);
return $this;
}
/**
* Get rules of promo items
*
* @param Address|null $address
* @return \Magento\SalesRule\Model\ResourceModel\Rule\Collection
*/
protected function _getPromoItemRules(Address $address = null)
{
$addressId = $this->getAddressId($address);
$key = $this->getWebsiteId() . '_'
. $this->getCustomerGroupId() . '_'
. '_'
. $addressId;
if (!isset($this->_rules[$key])){
$this->_rules[$key] = $this->_collectionFactory->create()
->setValidationFilter(
$this->getWebsiteId(),
$this->getCustomerGroupId(),
'',
null,
$address
)
->addFieldToFilter('is_active', 1)
->addFieldToFilter('simple_action', array('like'=>'%ampromo%'))//Condition for promo rules only
->load();
}
return $this->_rules[$key];
}
}
【讨论】: