我正在开发一个B2B网店在Magento。在向购物篮中添加产品时,它将调用外部API来根据用户、产品和数量查找折扣。问题是API只返回总折扣价格。
。加上10件5美元的商品,总折扣价可能是40美元。所以理想情况下,购物车应该显示$5 x 10 = $40
。
我已经通过在我的模块config.xml中覆盖Mage_Sales_Model_Quote_Item
实现了这一点:
<global>
<models>
<sales>
<rewrite>
<quote_item>Frigg_Import_Model_QuoteItem</quote_item>
</rewrite>
</sales>
</models>
</global>
然后重写calcRowTotal()
class Frigg_Import_Model_QuoteItem extends Mage_Sales_Model_Quote_Item
{
protected $customRowTotalPrice = null;
public function setCustomRowTotalPrice($price)
{
$this->customRowTotalPrice = $price;
}
public function calcRowTotal()
{
if ($this->customRowTotalPrice !== null) {
$this->setRowTotal($this->getStore()->roundPrice($this->customRowTotalPrice));
$this->setBaseRowTotal($this->getStore()->roundPrice($this->customRowTotalPrice));
return $this;
}
$qty = $this->getTotalQty();
$total = $this->getStore()->roundPrice($this->getCalculationPriceOriginal()) * $qty;
$baseTotal = $this->getStore()->roundPrice($this->getBaseCalculationPriceOriginal()) * $qty;
$this->setRowTotal($this->getStore()->roundPrice($total));
$this->setBaseRowTotal($this->getStore()->roundPrice($baseTotal));
return $this;
}
}
然后处理事件checkout_cart_product_add_after
并将其传递给我的观察者方法setPriceForItem
:
<?php
class Frigg_Import_Model_Observer
{
// Event: Price for single item
public function setPriceForItem(Varien_Event_Observer $observer)
{
$customer = Mage::getSingleton('customer/session')->getCustomer();
$item = $observer->getQuoteItem();
if ($item->getParentItem()) {
$item = $item->getParentItem();
}
$quantity = $item->getQty(); // e.g. 5
$product = $item->getProduct();
// Call API here and get the total price based on quantity (e.g. 40)
// ....
$customTotalRowPriceFromAPI = 40;
if ($customTotalRowPriceFromAPI) {
$item->setCustomRowTotalPrice($customTotalRowPriceFromAPI);
$item->getProduct()->setIsSuperMode(true);
$item->save();
}
}
}
现在可以工作了,但只在添加到篮子时。当我重新加载浏览器或转到购物车页面时,行价格已重置为原始价格(在本例中为$5 x 10 = $50
)。
有人发现我的错误吗?我希望我已经解释清楚了
解决了。只需在添加到购物车时将每个客户、产品和数量的价格存储在一个新表中,然后从calcRowTotal
中的新表中获取价格。