I'm developing a B2B webshop in Magento. When adding a product to basket, it will call an external API to lookup discount based on the user, product, and quantity. Problem is that the API only returns the total discounted price.
E.g. adding 10 items of $5 may return a total discountet price of $40. So ideally the shopping cart would show $5 x 10 = $40
.
I've already accomplished this by overriding Mage_Sales_Model_Quote_Item
in my modules config.xml:
<global>
<models>
<sales>
<rewrite>
<quote_item>Frigg_Import_Model_QuoteItem</quote_item>
</rewrite>
</sales>
</models>
</global>
And then overriding the 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;
}
}
Then handling the event checkout_cart_product_add_after
and passing this to my Observer method 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();
}
}
}
Now this works, but only when adding to the basket. When I reload the browser, or go to the shopping cart page, the row prices have been reset to original price (in this case $5 x 10 = $50
).
Does anyone spot my error? I hope I've explained the properly.
sales_flat_quote_item
table, but when visiting the shopping cart, the prices have been reset. I'm guessing that I need to overwrite the method calculting the row total in shopping cart, but don't know how (yet). Any ideas? – frigg