getRate() and Magento tax percentage - magento

I'm trying to get the tax rate (percentage, not currency) for a given postcode so I can display it in a third-party quote PDF printout (no relation to the "quote" Magento uses as the shopping cart pre-checkout). While I'm still relatively new to Magento it appears that getRateRequest() and getRate() are the two main functions which get the tax rate based on all the variables (product tax class, customer tax class, etc.).
Since this is for a third-party extension and all our products are taxable I figured I would just use getRate() with the correct Varien Object input and it would return the tax rate. After a week of trial and error I can't figure out why I'm always getting a rate of zero. I've confirmed I'm calling the getRate() function and that it's not returning zero from the first if() statement checking for Country and Customer/Product class ID. In addition I've confirmed all the variables are being passed on and accessible in the getRate() function itself.
I've created an object with the below input (based on the output of getRateRequest()) that I call with getRate() and am hoping someone can shed light on what is wrong with my data input or why the getRate() function is always returning a result of zero. (I'm actually setting with $variables below, they are just defined earlier up and one of my test case values are below)
// UPDATED CODE (variable values come from 3rd party quote extension)
$country = 'US'; // use short country code
$region = '12'; // must be numeric!
$postcode = '95050';
// our quote extension stores the customer id ('2') which we use to get the tax class
$customer = Mage::getModel('customer/customer')->load( '2' );
$custTax = $customer->getTaxClassId();
$TaxRequest = new Varien_Object();
$TaxRequest->setCountryId( $country );
$TaxRequest->setRegionId( $region );
$TaxRequest->setPostcode( $postcode );
$TaxRequest->setStore( Mage::app()->getStore() );
$TaxRequest->setCustomerClassId( $custTax );
$TaxRequest->setProductClassId(2); // 2=taxable id (all our products are taxable)
$taxCalculationModel = Mage::getSingleton('tax/calculation');
$rate = $taxCalculationModel->getRate($TaxRequest);
My backup plan is to just do a direct SQL lookup formula although that will probably get a bit messy. Since our web development team didn't exactly follow good coding standards an eventual site re-write is in my future anyway once the initial launch fixes are in (all 4 pages of them).
Thanks for any help and taking the time to read this.
EDIT - Stack Overflow is awesome :)

You can also try this
$store = Mage::app()->getStore('default');
$request = Mage::getSingleton('tax/calculation')->getRateRequest(null, null, null, $store);
$taxclassid = $product->getData('tax_class_id');
$percent = Mage::getSingleton('tax/calculation')->getRate($request->setProductClassId($taxclassid));

If you change:
$TaxRequest->setRegionId(California);
to
$TaxRequest->setRegionId($stateId);
where $stateId is numeric region id. Your code should work then.

Related

Magento: Is Tablerate Shipping based on the cart sum with or without taxes?

I have a Shop with Products that have different Taxrates. Some have 0%, some 19% etc...
For Shipping im using Tablerates, for example:
up to 2000€ = 10€ shipping cost
up to or over 2400€ = 15€ shipping cost
Now comes the thing that at first i just want to understand, so there is not really a bug to fix here. I just need to know how it works to plan my tablerates accordingly.
I have orders with a total over 2400€ (incl. Tax), but the customer still gets the 10€ Shipping rate. This can only be if the System is using the Price without Tax to check against the table rates. Because only then would the price be in the Tablerate range for the lower rate. And yes i double checked the Tablerates Setup (not my first Magento Install).
1) Is this assumption correct that table rates are checked against the total without taxes?
2) Is there a way to set up tablerates to check against the cart total including taxes?
Anyone got any info on how that works in the background? I couldnt find anything as when youre searching the topic you mostly get tutorial on how to set up table rates.
Super thankful for any tipps or maybe other threads or places i could check for detailed infos on how that works.
note: i use Magento 1.9.2.1
For Question 1:
It would appear to be without tax.
Mage_Shipping_Model_Shipping::collectRatesByAddress calls setPackageValue to set the package value for the rate request.
This gets passed to Mage_Shipping_Model_Carrier_Tablerate::collectRates.
collectRates subtracts free shipping from the package value.
Then Mage_Shipping_Model_Carrier_Tablerate::getRate is called
$result = Mage::getModel('shipping/rate_result');
$rate = $this->getRate($request);
...
public function getRate(Mage_Shipping_Model_Rate_Request $request)
{
return Mage::getResourceModel('shipping/carrier_tablerate')->getRate($request);
}
This calls Mage_Shipping_Model_Resource_Carrier_Tablerate::getRate which binds the condition value to the query. (The condition name should be package_value in your case).
// Render condition by condition name
if (is_array($request->getConditionName())) {
$orWhere = array();
$i = 0;
foreach ($request->getConditionName() as $conditionName) {
$bindNameKey = sprintf(':condition_name_%d', $i);
$bindValueKey = sprintf(':condition_value_%d', $i);
$orWhere[] = "(condition_name = {$bindNameKey} AND condition_value <= {$bindValueKey})";
$bind[$bindNameKey] = $conditionName;
$bind[$bindValueKey] = $request->getData($conditionName);
$i++;
}
if ($orWhere) {
$select->where(implode(' OR ', $orWhere));
}
} else {
$bind[':condition_name'] = $request->getConditionName();
$bind[':condition_value'] = $request->getData($request->getConditionName());
$select->where('condition_name = :condition_name');
$select->where('condition_value <= :condition_value');
}
While it is possible to modify the order, baseSubtotal should be before tax.
See collectRatesByAddress:
$request->setBaseSubtotalInclTax($address->getBaseSubtotalInclTax()
+ $address->getBaseExtraTaxAmount());
As for your question 2.
As noted above, we have the data in the request, but we do not have an easy touchpoint.
One suggestion is to rewrite the Mage_Shipping_Model_Carrier_Tablerate and override getRate. What you would do would be to set the BaseSubtotal to the BaseSubtotalInclTax, call parent, then reset the request.
public function getRate(Mage_Shipping_Model_Rate_Request $request)
{
// TODO: wrap in try catch, to reset the value ??
// TODO: clone the request ??
// TODO: Test This
$oldPackageValue = $request->getPackageValue();
$request->setPackageValue($request->getBaseSubtotalInclTax());
$returnvalue = Mage::getResourceModel('shipping/carrier_tablerate')->getRate($request);
$request->setPackageValue($oldPackageValue);
return $returnvalue;
}
This is hacky, but minimally intrusive. It should withstand unrelated changes without forcing you to modify the code.
Another method involves rewriting and modifying Mage_Shipping_Model_Resource_Carrier_Tablerate::getRate to use the value you want.
NOTE: Neither of these methods are tested.

custom reason message for magento reward points

How to add a custom reason message for a reward action ?
I have created :
$customerId = 1303177;
$points = 10;
$customer = Mage::getModel('customer/customer')->load($customerId);
$reward = Mage::getModel('enterprise_reward/reward')
->setCustomer($customer)
->setWebsiteId(2)
->loadByCustomer();
$reward->setPointsDelta($points)
->setAction(Enterprise_Reward_Model_Reward::REWARD_ACTION_ADMIN)
->setComment('Added programmatically')
->updateRewardPoints();
i like to add something like
$reward->setReason('bonus point');
that would be visible in the reason column of the customer reward history ( back office )
If reason column already exists in the Rewards database table, then all you need is to use
$reward->setReason('bonus point');
$reward->save();
to save the values.
But if reason column doesn't exist then first create a new column reason in the database and then use the above code to save the values in that field.

Magento - save quote_address on cart addAction using observer

I am writing a custom Magento module that gives rate quotes (based on an external API) on the product page. After I get the response on the product page, it adds some of the info from the response into the product view's form.
The goal is to save the address (as well as some other things, but those can be in the session for now). The address needs to be saved to the quote, so that the checkout (onestepcheckout, free version) will automatically fill those values in (city, state, zip, country, shipping method [of which there are 3]) and load the rate quote via ajax (which it's already doing).
I have gone about this by using an Observer, and watching for the cart events. I fill in the address and save it. When I end up on the cart page or checkout page ~4/5 times the data is lost, and the sql table shows that the quote_address is getting save with no address info, even though there is an explicit save.
The observer method's I've used are:
checkout_cart_update_item_complete
checkout_cart_product_add_after
The code saving is: (I've tried this with the address, quote and cart all not calling save() with the same results, as well as not calling setQuote()
// $params = Mage::app()->getRequest()->getParams()
// $quote = Mage::getSingleton('checkout/cart')->getQuote()
// or
// $quote = observer->getProduct()->getQuoteItem()->getQuote();
// where applicable, but both methods seemed to === each other
$quote->getShippingAddress()
->setCountryId($params['estimate_to_country'])
->setCity($params['estimate_to_city'])
->setPostcode($params['estimate_to_zip_code'])
->setRegionId($params['estimate_to_state_code'])
->setRegion($params['estimate_to_state'])
->setCollectShippingRates(true)
->setShippingMethod($params['carrier_method'])
->setQuote($quote)
->save();
$quote->getBillingAddress()
->setCountryId($params['estimate_to_country'])
->setCity($params['estimate_to_city'])
->setPostcode($params['estimate_to_zip_code'])
->setRegionId($params['estimate_to_state_code'])
->setRegion($params['estimate_to_state'])
->setCollectShippingRates(true)
->setShippingMethod($params['carrier_method'])
->setQuote($quote)
->save();
$quote->save();
$cart->save();
// I also tried:
Mage::getSingleton('checkout/session')->setQuote($quote);
I imagine there's a good chance this is not the best place to save this info, but I am not quite sure. I was wondering if there is a good place to do this without overriding a whole controller to save the address on the add to cart action.
Thanks so much, let me know if I need to clarify
In Magento you can create your own events wherever you need but in this case you can use checkout_cart_product_add_after event to update the quore address details.
So here is the code for the same
$quote = Mage::getSingleton('checkout/session')->getQuote();
$billingAddress = Mage::getModel('sales/quote_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId(('Your_Value_Here'))
->setCustomerAddressIpd(('Your_Value_Here'))
->setCustomer_address_id(('Your_Value_Here'))
->setPrefix(('Your_Value_Here'))
->setFirstname(('Your_Value_Here'))
->setMiddlename(('Your_Value_Here'))
->setLastname(('Your_Value_Here'))
->setSuffix(('Your_Value_Here'))
->setCompany(('Your_Value_Here'))
->setStreet(('Your_Value_Here'))
->setCity(('Your_Value_Here'))
->setCountry_id(('Your_Value_Here'))
->setRegion(('Your_Value_Here'))
->setRegion_id(('Your_Value_Here'))
->setPostcode(('Your_Value_Here'))
->setTelephone(('Your_Value_Here'))
->setFax(('Your_Value_Here'));
$quote->setBillingAddress($billingAddress);
$shippingAddress = Mage::getModel('sales/quote_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId(('Your_Value_Here'))
->setCustomerAddressId(('Your_Value_Here'))
->setCustomer_address_id(('Your_Value_Here'))
->setPrefix(('Your_Value_Here'))
->setFirstname(('Your_Value_Here'))
->setMiddlename(('Your_Value_Here'))
->setLastname(('Your_Value_Here'))
->setSuffix(('Your_Value_Here'))
->setCompany(('Your_Value_Here'))
->setStreet(('Your_Value_Here'))
->setCity(('Your_Value_Here'))
->setCountry_id(('Your_Value_Here'))
->setRegion(('Your_Value_Here'))
->setRegion_id(('Your_Value_Here'))
->setPostcode(('Your_Value_Here'))
->setTelephone(('Your_Value_Here'))
->setFax(('Your_Value_Here'));
$quote->setShippingAddress($shippingAddress)
->setShipping_method('flatrate_flatrate')
->setShippingDescription($this->getCarrierName('flatrate'));
$quote->save();

Loading Thousands of Codes to Map to a Shopping Cart Rule in Magento

I've been looking at the salesrule_coupon table, and I've discovered that I can map many coupon codes to a single rule, if the rule itself is of type 'Auto.' This is highly convenient as my client needs us to sync the codes periodically with a feed of data.
So in loading in these thousands of codes (using a custom module & direct SQL calls) they load just fine, and I can test and verify that many of them work.
However in working my way down the list of these codes, they stop working. The first 30 or so will work just fine, but thereafter, Magento says that the codes are invalid.
I'm still debugging this, and I'll post updates if I discover anything... but I've tried and experienced this with two separate price rules now. One rule crapped out at the 31st code, the second at the 39th.
What's really strange is that, if I change these codes to point to a different rule (one with less than 30 codes) they're recognized and accepted. Nothing else changed, that I can determine.
Any ideas on how to proceed here? Has anyone attempted this before? This is an interesting one.
I fixed the same issue when I was creating something similar for one of my customers. The source of the problem for retrieving of valid coupon Magento Core Sales Rule module uses FIND_IN_SET() with GROUP_CONCAT() MySQL functions instead adding additional condition for joined table. So FIND_IN_SET just truncates number of coupon codes that are used in group concatenation to 31 item (32 bits mask). Also I noticed that they are using HAVING instead of where, so it affects performance a bit.
So what you need to do are the following:
Create rewrite for this resource model: Mage_SalesRule_Model_Mysql4_Rule_Collection (salesrule/rule_collection)
Then in your resource model that rewrites core one, you need to redefine this method setValidationFilter($websiteId, $customerGroupId, $couponCode='', $now=null) that applies limitations for sales rules on the frontend. Here the method body that I used:
/**
* Fix for validation with auto-coupons
* #todo remove this fix, after the bug in core will be fixed
*
* (non-PHPdoc)
* #see Mage_SalesRule_Model_Mysql4_Rule_Collection::setValidationFilter()
*/
public function setValidationFilter($websiteId, $customerGroupId, $couponCode='', $now=null)
{
if (is_null($now)) {
$now = Mage::getModel('core/date')->date('Y-m-d');
}
$this->getSelect()->where('is_active=1');
$this->getSelect()->where('find_in_set(?, website_ids)', (int)$websiteId);
$this->getSelect()->where('find_in_set(?, customer_group_ids)', (int)$customerGroupId);
if ($couponCode) {
$couponCondition = $this->getConnection()->quoteInto(
'extra_coupon.code = ?',
$couponCode
);
$this->getSelect()->joinLeft(
array('extra_coupon' => $this->getTable('salesrule/coupon')),
'extra_coupon.rule_id = main_table.rule_id AND extra_coupon.is_primary IS NULL AND ' . $couponCondition,
array()
);
$this->getSelect()->where('('
. $this->getSelect()->getAdapter()->quoteInto(' main_table.coupon_type <> ?', Mage_SalesRule_Model_Rule::COUPON_TYPE_SPECIFIC)
. $this->getSelect()->getAdapter()->quoteInto(' OR primary_coupon.code = ?', $couponCode) . ')'
);
$this->getSelect()->where('('
. $this->getSelect()->getAdapter()->quoteInto(' main_table.coupon_type <> ?', Mage_SalesRule_Model_Rule::COUPON_TYPE_AUTO)
. $this->getSelect()->getAdapter()->quoteInto(' OR extra_coupon.code IS NOT NULL') . ')'
);
} else {
$this->getSelect()->where('main_table.coupon_type = ?', Mage_SalesRule_Model_Rule::COUPON_TYPE_NO_COUPON);
}
$this->getSelect()->where('from_date is null or from_date<=?', $now);
$this->getSelect()->where('to_date is null or to_date>=?', $now);
$this->getSelect()->order('sort_order');
return $this;
}
Test fix & Enjoy Magento Development :)
Another solution is to increase the mysql limit you are running into with
SET GLOBAL group_concat_max_len=9999999;
as Ivan explained the FIND_IN_SET does not return all your coupon codes. You need to increase group_concat_max_len to be able to hold the length of all your coupon codes delimited by a comma (COUPON1, COUPON2, COUPON3).
Since you have likely used different codes with different lengths, this would explain why 1 rule worked for 30 while the other worked for 38.

Programmatically ship and comment single item of an order in Magento

I know there is a way to programmatically invoice, ship, and set state on an order (http://www.magentocommerce.com/boards/viewthread/74072/), but I actually need to drill down even deeper to the item level of an order. We have a situation where, depending on item type, two different items can be processed in two different locations (from the same order). I can go into the Magento back-end and "ship" one item without "shipping" the other and append comments to that one item, but I'm looking for a way to do this programmatically. Thank you in advance for your help!
Update:
Here is the code I ended up using to accomplish this:
$client = new SoapClient('http://somesite.domain/magento/index.php/api/?wsdl');
$session = $client->login('username', 'password');
function extract_item_id($items, $sku ){
foreach($items as $item ){
if ($item["sku"]==$sku) {
return $item["item_id"];
}
}
}
$orderNum = "200000052";
$oderInfo = $client->call($session, "sales_order.info", $orderNum );
$item_id = extract_item_id($oderInfo["items"], "someSKU") ;
$itemsQty = array( $item_id => "1" );
$shipment = array(
$orderNum,
$itemsQty,
"Comment associated with item shipped.",
true,
true
);
var_dump($shipment);
$nship = $client->call($session, 'sales_order_shipment.create', $shipment);
I've never done it, but it looks like the SOAP API supports creating individual shipment items. That'd be the first thing I'd check.
If that doesn't work, I'd examine the source code the the Magento admin and reverse engineer what its doing with to create a single item shipment. Specifically, start tracing at the saveAction of the admin's Shipment Controller
app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php
The order/shipment/invoice section of Magento codebase is one of the most volatile/iterative sections, with the core objects/methods/dependencies changing subtly between versions. Finding one "right" answer for this will prove difficult, if not impossible.

Resources