在篮子里设置自定义总行价 - Magento

时间:2014-05-28 12:15:13

标签: php magento

我正在Magento开发B2B网上商店。将产品添加到购物篮时,它将调用外部API以根据用户,产品和数量查找折扣。问题是API只返回总折扣价。

E.g。添加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)。

有没有人发现我的错误?我希望我已经正确解释了。

1 个答案:

答案 0 :(得分:1)

解决了它。只需在添加到购物车时将每个客户,产品和数量的价格存储在新表中,然后从calcRowTotal中的新表中获取价格。