I am attempting to create an order total module to do some custom price adjustments. Just to get started with this I am just trying to get it to add $20 to every single order (eventually putting in the real logic).
I am having issues with the module that I created. The first issue is that it appears to be running twice (so it is taking $40 off instead of only $20 -- Logging showed me that both the collect and fetch methods are being run twice)
The second issue is that the discount line item is appearing below the Grand Total line.
Can someone tell me what I am doing wrong here? The contents of my config.xml and order total class are below.
config.xml Content
<global>
<sales>
<quote>
<totals>
<mud>
<class>Wpe_Multiunitdiscount_Model_Multiunitdiscount</class>
<before>grand_total</before>
</mud>
</totals>
</quote>
</sales>
</global>
Wpe_Multiunitdiscount_Model_Multiunitdiscount Content
class Wpe_Multiunitdiscount_Model_Multiunitdiscount extends Mage_Sales_Model_Quote_Address_Total_Abstract {
public function collect(Mage_Sales_Model_Quote_Address $address) {
$address->setGrandTotal($address->getGrandTotal() + 20 );
$address->setBaseGrandTotal($address->getBaseGrandTotal() + 20);
return $this;
}
public function fetch(Mage_Sales_Model_Quote_Address $address) {
$address->addTotal(array(
'code' => $this->getCode(),
'title' => Mage::helper('sales')->__('Super Tax'),
'value' => 20,
));
return $this;
}
}
Regarding the "double" issue, as far as I understand it, it's because magento collects your total twice, once for the shipping address and once for the billing address.
I'm sure there has to be a better way to manage this, but for now I've added in the first line of my collect method:
if ($address->getData('address_type')=='billing') return $this;
And for the "placement", have you try with "after" instead of "before" (changing the total alias, of course, let's say "tax" for example")?
HTH
You cannot touch any other totals when adding your own custom total. Please see this thread for more information: Magento upfront payment
Related
I am using Magento 1.9.0.1. I want to change the grand total at Shipping Information step while checkout.I added new field called Locality in Shipping Information step.Depending on the locality selected by user, some amount should added to Grand total .And the newly changed grand total should save in db and display in order page in back end.
I added new field Locality.
On change of locality field the grand total will change.
But I don't know how to change the grand total. Please help me...
I only need to know How change the grand total at Shipping Information step while checkout.
Currently working on the similar issue, but can't save totals after it, but the mail code looks like it. config.xml
<global>
<models>
<test_example>
<class>Test_Example_Model</class>
</test_example>
</models>
<events>
<checkout_controller_onepage_save_shipping_method>
<observers>
<check_totals>
<class>Test_Example_Model_Observer</class>
<method>checkTotals</method>
</check_totals>
</observers>
</checkout_controller_onepage_save_shipping_method>
</events>
</global>
Function of observer
public function checkTotals(Varient_Event_Observer $observer)
{
$quote = Mage::getSingleton('checkout/type_onepage')->getQuote();
$grandTotal = '12';
$quote->setData('grand_total', $grandTotal);
$quote->setData('base_grand_total', $grandTotal);
$quote->save();
}
}
But I stuck on save() method, because it doesn't work somehow
I have a magento store with two currency, and my items in cart have a dynamic price.
I succesfully calculate my quote_item price, with an observer and setCustomPrice and setOriginalCustom price
$quote_item->setCustomPrice($price);
$quote_item->setOriginalCustomPrice($price);
And my observer:
<sales_quote_add_item>
But i have a problem, when i change the currency of my store, the subtotal is not update.
How to handle multiple-currency and custom quote item price ?
handle it through observer
< sales_quote_item_set_product>
$baseCurrencyCode = Mage::app()->getStore()->getBaseCurrencyCode();
$currentCurrencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
if($currentCurrencyCode!=$baseCurrencyCode)
$price= Mage::helper('directory')->currencyConvert($baseprice, $baseCurrencyCode, $currentCurrencyCode);
else
$price = $baseprice;
$item->setPrice($baseprice);
$item->setRowTotal($item->getQty() * $price);
I've had this very same issue over the last week. Using the ->setOriginalCustomPrice method is fine for a single currency site, but with currency switching, its rigidness means you need to update the cart items and list price everytime the currency is switched, which is very inefficient in my opinion.
I came up with a more elegant solution. Create a module and within the model section of your config add this;
<models>
<catalog>
<rewrite>
<product>PixieMedia_CustomPrice_Model_Product</product>
</rewrite>
</catalog>
</models>
Counter intuitively, the main ->getFinalPrice function is in the product model and not the price model.
Now create your new Product.php model in /app/code/local/Namespace/Module/Model/Product.php
class PixieMedia_CustomPrice_Model_Product extends Mage_Catalog_Model_Product {
public function getFinalPrice($qty=null)
// REWRITTEN FUNCTION TO RETURN THE SPECIAL PRICE AND ENSURE CURRENCY CONVERSION
{
$qBreak = false;
$customPrice = Mage::Helper('pixiemedia_customprice')->getCustomerPrice($this);
if($qty) {
$qBreak = $this->getQtyBreakPrice($this->getSku(),$qty,$customPrice[0]);
}
if($qBreak) { return $qBreak; } else { return $customPrice[0]; }
}
}
On the particular project I was working on, the client is using multiple price lists for customer specific pricing, the scope of which would make Magento horrendously slow to index pricing. So we've loaded all the data to a custom table and perform a lookup to return the customer's correct price or qty break.
It's dead easy to hook your own logic in and return what ever price you wish. This fully supports currency conversion, so no need to fiddle around re-converting prices.
Hope this helps someone out. Enjoy :)
You probably miss a call to:
$quote->collectTotals()->save();
I'm doing a module to Magento my module have the same functions of Crosssell native function from magento.
I have this product grid and the user select some checkboxes to associate this products to the main product.
All ok.
But, I've create a custom attribute to save the ID's of this products and make a Observer to 'catalog_product_save_after' event:
<events>
<catalog_product_save_after>
<observers>
<brindeproduto_save_product_data>
<type>singleton</type>
<class>brindeproduto/observer</class>
<method>saveProductTabData</method>
</brindeproduto_save_product_data>
</observers>
</catalog_product_save_after>
</events>
On my saveProductTabData I load the main product by the ID on Request, and put the IDS of the selecte products on my custom attribute like these "1,2,3,4,5,6".
Ok, but when I do $product->save(); I got infinite load on my browser, without any error or exeption.
The code on observer are simple.
$product = Mage::getModel('catalog/product')->load($product_id);
//some logical Specific information that is not in question now.
$product->save();
Nothing more.
I've tryed debug the save function and get some intriguing result.
On Mage_Core_Model_Abstract function save(), I put some die on parts of code, and get all of then. this code it's part of function save line 330 on Magento 1.5 Community.
if ($dataCommited) {
$this->_afterSaveCommit();
}
return $this;
It's the last line on function. I put die before return.
if ($dataCommited) {
$this->_afterSaveCommit();
}
die('test');
return $this;
I've got the die. But nothing more before return. Some body have ideia of what's happen?? Lost by 5 hours on that.
Any help will be mutch appreciated.
You should NOT be doing any save in your observer (*_save_after).
This will cause a never ending loop
I have created attributes that save directly to a quote item in my checkout_cart_product_add_after Observer method will not persist the value as it seems to be reverted after the Observer exits.
See code samples below:
config.xml (snippet):
<checkout_cart_product_add_after>
<observers>
<module>
<type>model</type>
<class>NativeRemedies_OrderGroove_Model_Observer</class>
<method>productAddAfter</method>
</module>
</observers>
</checkout_cart_product_add_after>
Observer.php (snippet):
public function handleOrderGroove()
{
foreach($this->og->products as $_product){
if($_product->every>0){
foreach($this->_quote->getAllVisibleItems() as $_item){
//if sku is in the active list of recurring products selected add quote item id to array
if($_item->getSku()==$_product->id){
Mage::helper('nrordergroove')->setRecurringItem($_item->getItemId());
$_item->setOrdergrooveActive(true)->save();
$_item->getProduct()->setPrice(2);
$_item->setCustomPrice(2);
$_item->setOriginalCustomPrice(2);
$_item->getProduct()->setIsSuperMode(true);
}
}
} // else, do nothing
}
The $_item object in this example isn't providing the facility to retain the attribute as set - even when calling ->save().
Thank in advance for your help. I have seen all of the tutorials about setting custom prices and attributes - nothing seems to remedy the situation!
Edit 1
I'm starting to feel like this is a bug in 1.6+. I have seen much discussion on various boards about this working in >=1.4.
Edit 2
Just to be absolutely clear, the issue here is that the Custom Pricing attribute is being overwritten effectively by the Product model or the collectTotals methods. I need a workaround.
As it happens my working code here did, in fact, work. An extension conflict with Amasty's Special Promotions was causing the custom pricing to be unset. This is tested as working with the following Magento versions:
1.5 Community
1.6.1 Community
1.11.1.1 Enterprise
Here is the answer to your question, yes this is in the newer version of Magento 1.5+:
When checking out items get converted from a quote to a order at which point your attribute are being lost.
You would need to add something similar to this observer in order for your attributes to retain at checkout:
<sales_convert_quote_item_to_order_item>
<observers>
<extra_options>
<type>model</type>
<class>extra_options/observer</class>
<method>salesConvertQuoteItemToOrderItem</method>
</extra_options>
</observers>
</sales_convert_quote_item_to_order_item>
Here we move the option from the quote item to the order item.
public function salesConvertQuoteItemToOrderItem(Varien_Event_Observer $observer)
{
$quoteItem = $observer->getItem();
if ($additionalOptions = $quoteItem->getOptionByCode('additional_options')) {
$orderItem = $observer->getOrderItem();
$options = $orderItem->getProductOptions();
$options['additional_options'] = unserialize($additionalOptions->getValue());
$orderItem->setProductOptions($options);
}
}
Take a look here for more details:
Magento - Quote/order product item attribute based on user input
Hello i need to use magento to sell a product that will have custom price rules.
the rule will depend by the quantity of this product sold.
I know that magento can make special rule, if a customer by ++ quantity of this product, but me i need to apply different rule and i cant find the way.
For example, product bought from customers first 100 times, price is :100$
product bought 200-500 times, price is 400$
500-1000times, product is 800$
1000 - > product is fixed price 1000$
is it possible for magento to do this?
Thank you
You can do this by creating a module that uses the checkout_cart_product_add_after and checkout_cart_update_items_after observers.
Then inside your observer class you can put the following function in to set the price:
public function yourAddToCartFunction($observer) {
if ($p = $observer->getQuoteItem()->getParentItem()) {
$discount_amount = $your_discount_logic;
$p->setCustomPrice($discount_amount)->setOriginalCustomPrice($discount_amount); #configs
} else {
$p = $observer->getQuoteItem();
$discount_amount = $your_discount_logic;
$p->setCustomPrice($discount_amount)->setOriginalCustomPrice($discount_amount); #simple products
}
}
You will more than likely need a different function for the cart update observer call. The one above is for the cart_add_after event. The function for the cart update is nearly identical except you have to go through the cart object to get the logic.
public function yourCartUpdateFunction($observer) {
$cart = $observer->cart;
$quote = $cart->getQuote();
foreach($quote->getAllVisibleItems() as $item) {
if ($p = $item->getParentItem()) {
$discount_amount = $your_discount_logic;
$p->setCustomPrice($discount_amount)->setOriginalCustomPrice($discount_amount); #configs
} else {
$discount_amount = $your_discount_logic;
$item->setCustomPrice($discount_amount)->setOriginalCustomPrice($discount_amount); #simple products
}
}
}
The reason you would want the second function is if the logic needs to happen again if the cart is updated. If the price is going to stick forever no matter what happens once it is in the cart, you can probably exclude the second function.
MASSIVE EDIT:
Ok this is how I would do this. I am assuming you are starting with a basic, functional module.
The first thing you want to do is setup your observers in your modules config.xml file. In this case you are going to use be using the checkout_cart_product_add_after and checkout_cart_update_items_after observers. You will set that up by adding the following to your config.xml file:
<config>
...
<global>
...
<events>
<checkout_cart_product_add_after>
<observers>
<call_this_something_unique>
<type>singleton</type>
<class>Ocaff_Custompricing_Model_Cart_Observer</class>
<method>calculateAddToCart</method>
</call_this_something_unique>
</observers>
</checkout_cart_product_add_after>
<checkout_cart_update_items_after>
<observers>
<call_this_something_unique_2>
<type>singleton</type>
<class>Ocaff_Custompricing_Model_Cart_Observer</class>
<method>calculateCartUpdate</method>
</call_this_something_unique_2>
</observers>
</checkout_cart_update_items_after>
</events>
...
</global>
...
</config>
Basically what this does is it tells Magento that when the checkout_cart_product_add_after event is triggered, run the calculateAddToCart method of the Ocaff_Custompricing_Model_Cart_Observer class and also to run the calculateCartUpdate when the checkout_cart_update_items_after event is triggered.
Ok now that you have your configuration put together you can create your model. In the case of this example the class would be located in the /app/code/local/Ocaff/Custompricing/Model/Cart/Observer.php file (however you will put the class that matches your module)
Ok now in your Observer.php file you are going to put the following code:
<?php
class Ocaff_Custompricing_Model_Cart_Observer {
public function calculateAddToCart($observer) {
if ($p = $observer->getQuoteItem()->getParentItem()) {
$discount_amount = Mage::helper('custompricing')->calculatePrice($p);
$p->setCustomPrice($discount_amount)->setOriginalCustomPrice($discount_amount); #configs
} else {
$p = $observer->getQuoteItem();
$discount_amount = Mage::helper('custompricing')->calculatePrice($p);
$p->setCustomPrice($discount_amount)->setOriginalCustomPrice($discount_amount); #simple products
}
}
public function calculateCartUpdate($observer) {
$cart = $observer->cart;
$quote = $cart->getQuote();
foreach($quote->getAllVisibleItems() as $item) {
if ($p = $item->getParentItem()) {
$discount_amount = Mage::helper('custompricing')->calculatePrice($prpoduct);
$p->setCustomPrice($discount_amount)->setOriginalCustomPrice($discount_amount); #configs
} else {
$discount_amount = Mage::helper('custompricing')->calculatePrice($p);
$item->setCustomPrice($discount_amount)->setOriginalCustomPrice($discount_amount); #simple products
}
}
}
}
Ok a few notes here. both functions take a single paramater that I have called observer (and pretty much everywhere else calls it that too). This is a single variable that holds all the information that Magento passes along to all the functions that handle the event. In the case of the calculateAddToCart function we are only grabbing the Quote Item (which is confusing since in checkout with Magento there are quite a few different objects that kind of all represent the same thing if you are looking at it from 50,000 feet). What this function does is takes the quote item and determines if the product that was added to cart is a simple or configurable product and takes that appropiate action.
The calculateCartUpdate function basically does the exact same thing, but it has to instead iterate through all the products in the cart since in Magento you update the entire cart all at once, not every line item.
In both functions you will notice that I am updating the Custom Price and the Original Custom Price field. I am not 100% sure why you have to update both (and really why ask questions if it works :))
Ok now you may or may not notice that I have done something a little less than conventional for figuring out the $discount_amount variable. I am calling a helper function to get the price that the product should be set to. I put this into a helper because you may want to access that logic elsewhere in the system and I generally prefer to put that kind of logic into a Helper (in fact I am pretty sure you are going to want to use this on the product and category pages since you are modifying the way pricing is working for some products and customers get mad when prices change up unexpectadly).
Ok now onto the helper function. Since I am not 100% sure what logic you really want in the end, we are just going to keep this function simple and have it return $2. This will make everything that goes into the cart $2 no matter what its price actually is. This is going to be where you figure out your logic for pricing.
<?php
class Ocaff_Custompricing_Helper_Data {
public function calculatePrice($product=null) {
// Your custom logic will go here. Whatever number you come up with and return will be the price that the item is set to
return 2;
}
}
For the most part this should get you about 90% of where you want to be. Try this out and post questions and I'll do my best to help you.
Another Edit: Activating Helpers in config.xml
Put this code inside your config.xml file right after your observers block detailed above. This will tell Magento the location of the helper files for your module.
<helpers>
<custompricing>
<class>Ocaff_Custompricing_Helper</class>
</custompricing>
</helpers>
This is a tier prices feature, you don't need to create a catalog price rule. Check in the product edit page when you manage your products in the backend, the tab Prices and see the option "Tier Prices"