Magento currency Converter - php

I am implementing custom filter by price range functionality on product list page in magento
I have multiple currency store, and base currency is INR , with other 6 to 7 currencies
I take input from price range and using following filter on product collection
$this->_productCollection = $layer->getProductCollection();
if($this->getRequest()->getParam('filterPrice')){
$baseCurrency = Mage::app()->getStore()->getBaseCurrencyCode();
$currentCurrency = Mage::app()->getStore()->getCurrentCurrencyCode();
$price = explode('-',$this->getRequest()->getParam('filterPrice'));
$min = str_replace(Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol(),'',$price[0]);
$min = $this->currencyConverter($min, $currentCurrency, $baseCurrency);
$max = str_replace(Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol(),'',$price[1]);
$max = $this->currencyConverter($max, $currentCurrency, $baseCurrency);
$this->_productCollection->addAttributeToFilter('price',array('from'=>$min,'to'=>$max));
}
Where currencyConverter function is like
public function currencyConverter($amount,$from,$to)
{
if($from!=$to){
$targetCurrency = Mage::getModel('directory/currency')->load($to);
$price = Mage::helper('directory')->currencyConvert($amount, $from, $targetCurrency);
$converted_final_price = Mage::app()->getStore()->roundPrice($price);
return $converted_final_price;
}else{
return $amount;
}
}
but I am getting following error
Undefined rate from "CAD-INR".
From other threads , I get to know that I need to setup currencies and rates from magento backend ,and I implement the same, but still error remains same.

Magento have rates only for pairs "Base currency => Display Currency".
You have Base currency "INR" and you likely have rate for pair "INR => CAD".
Your error say that your code try to get rate for "CAD" currency and in your system you have not rate for "CAD => INR".
Please, make sure, that you try to convert price in base currency to any other currency, and not between two display currencies.
But if you need this, you should use your own convert function, that calculates neccessary rate.

Related

how I can set the result number for getProductSearchResults()?

this code always return 10 records, anyone knows how to set 100?
Is for use the API of Google Cloud Vision Product Search.
# get the name of the product set
$productSetPath = $productSearchClient->productSetName($projectId, $location, $productSetId);
# product search specific parameters
$productSearchParams = (new ProductSearchParams())
->setProductSet($productSetPath)
->setProductCategories([$productCategory]);
# search products similar to the image
$response = $imageAnnotatorClient->productSearch($image, $productSearchParams);
if ($productSearchResults = $response->getProductSearchResults()) {
$results = $productSearchResults->getResults(); //this always return 10 results.
foreach ($results as $result) {
# display the product information.
$product = $result->getProduct();
$productName = $product->getName();
}
}
There is no place to specify the number of product search results in productSearchParams. BoundingPoly isn't related to the number of results. BoundingPoly is an optional parameter used to mark the area of the image that contains the product.

How to add math in PHP echo?

I have a website that everything is working well except lowest price. I mean all prices will be changed based on selected currency but not lowest price.
Lowest Price is showing correctly just based on US dollar not other currencies, I mean If we will change currency to Euro, still lowest price is showing on US dollar which is default currency.
In my Sql Database I have a table pt_currencie and Column rate
and on my room page, lowest price is showing with following PHP code:
<?php echo $lowestPrice; ?>
and in the controller, the code is:
$this->data['lowestPrice'] = $this->hotels_lib->bestPrice($this->data['hotel']->id);
and here is setting for userdata and change currency
function changeCurrency($id){
$this->db->where('id',$id);
$rs = $this->db->get('pt_currencies')->result();
$this->session->set_userdata('currencycode', $rs[0]->code);
$this->session->set_userdata('currencysymbol', $rs[0]->symbol);
$this->session->set_userdata('currencyname', $rs[0]->name);
$this->session->set_userdata('currencyrate', $rs[0]->rate);
}
}
How can I show $lowestPrice based on selected currency (rate) ?
what formula should I add into above code that lowest price show based on selected currency?
Ok if I'm understanding your question correctly, you will have to take the currency rates out of the db into a php array and then determine the lowest price using php with something like this:
$query = "SELECT rate FROM pt_currencie";
$result = mysqli_query($db_conn, $query);
$rate_arr = mysqli_fetch_fields($result);
$currLowestPrice = $lowestPrice;
foreach ($rate_arr as $rate) {
$tmpLowestPrice = $lowestPrice * $rate;
if($currlowestPrice > $tmpLowestPrice)
$currLowestPrice = $tmpLowestPrice;
}
So this should atleast give you the lowest price in $currLowestPrice for adjusted to currency rates by the end of the for loop (the code above will probably have to be adjusted a bit for your program)

Magento Custom Variable issue

I am in the process of writing a custom module whereby the user can enter a shipping cost per product.
I have added a custom variable to all of my products called 'initial_shipping_charge'. In my Get Shipping Rate function I am trying to loop through the products in my basket and get the variable (these will be added to a overall total).
The var_dump($shipping_price_initial); line returns NULL and not the variable that it contains - any idea why this is not working?
Thanks in advance.
protected function _getStandardShippingRate()
{
$rate = Mage::getModel('shipping/rate_result_method');
/* #var $rate Mage_Shipping_Model_Rate_Result_Method */
$rate->setCarrier($this->_code);
/**
* getConfigData(config_key) returns the configuration value for the
* carriers/[carrier_code]/[config_key]
*/
$shipping_price_value = rand(10 , 50);
//Create a basket session object
$session = Mage::getSingleton('checkout/session');
foreach ($session->getQuote()->getAllItems() as $item) {
$item_id = $item->getId();
$_basketProduct = Mage::getModel('catalog/product')->load($item_id);
$shipping_price_initial = $_basketProduct->getAttribute('initial_shipping_charge');
var_dump($shipping_price_initial);
}
$rate->setCarrierTitle($this->getConfigData('title'));
$rate->setMethod('standand');
$rate->setMethodTitle('Standard');
$rate->setPrice($shipping_price_value);
$rate->setCost(0);
return $rate;
}
$_basketProduct->getAttribute('initial_shipping_charge');
Should be
$_basketProduct->getData('initial_shipping_charge');
or
$_basketProduct->getInitialShippingCharge();
But i guess you don't even have the product cause you fetch the quote item id and try to load a product with that id....you need to:
$item->getProduct()
P.S.:
Product->Quote->Order
There is a conversion process, look for "quote to order conversion" or "product to quote item conversion"

Day rate discount

I am creating an intranet for a vehicle hire company
I set the default price as such:
$dayRate = '90.00';
I have created a field on my table to store a discount day rate if needed, called disc_day_rate which defaults to 0.
I pull the discount price as such
$discDayRate = $hire['disc_day_rate'];
I wish to find the lowest of these two numbers, but I think the default disc_day_rate of 0 is causing issues
I have tried using min(); and if ($discDayrate == "0") methods but after finding many answers on stackoverflow without having to post my own It's time to ask for help with an elegant solution
This ensures the 0.00 will never cause you a problem.
if ($discDayRate == 0.00) { ## don't use quotes here; it should be saved as a DECIMAL or INT in the database
$the_rate = $dayRate; ## back to the default
}
else {
if ($discDayRate < $dayRate) {
$the_rate = $diskDayRate;
}
else {
$the_rate = $dayRate;
}
}
$the_rate has your desired rate.

Invoicing a partial order; totals aren't updated

In our order proces it is possible to send an invoice for a partial order. So when a couple of order lines are being shipped, an invoice have to be send also.
To make this possible I use this code:
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($items);
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transactionSave->save();
$invoice->sendEmail();
$invoice->setEmailSent(true);
$invoice->save();
Where the $items variable is an array containing the order ids and the amount of products to be invoiced.
The created invoice shows the correct products to be invoiced, but somehow the totals aren't updated. The totals still are the totals of the complete order, instead of the partial invoice.
I probably have to update or recalculate the totals but can't find the right code to force the update.
Anyone around who can put me in the right direction?
Well, it seems I have found the problem. The functionality as described above works manually executing it in the administrator interface. The code as enclosed above I only got to work by changing a core file of Magento.
If you change line 103 of Mage_Sales_Model_Service_Order from continue; to $qty = 0; the functionality works.
In short, this is what happens. With continue the second row item isn't added to the invoice which the invoice makes thinks the curren item is the last item of the whole order and therefore needs to invoice the complete outstanding amount. In my case the invoice I did want to invoice and the row I didn't want to invoice.
I've submitted it as issue on the Magento issue list.
Today I faced with exactly this problem, but I found a more elegant way to solve it without editing the core. The solution is to pass the products that we don't want to invoice, with 0 quantity.
In this way, the code you changed in core will act exactly like in your solution :)
As an example if I have 2 products in my order:
array(
1234 => 1,
1235 => 2
)
passing this array:
$qtys = array(
1234 => 1,
1235 => 0
)
will force this code:
// Mage_Sales_Model_Service_Order: lines 97-103
if (isset($qtys[$orderItem->getId()])) { // here's the magic
$qty = (float) $qtys[$orderItem->getId()];
} elseif (!count($qtys)) {
$qty = $orderItem->getQtyToInvoice();
} else {
continue; // the line to edit according to previous solution
}
to act exactly like in your solution, so you don't have to edit core code.
Hope it helps :)
OK - took me a bit, but now I see how to correctly create the array.
foreach ($items as $itemId => $item) {
$itemQtyToShip = $item->getQtyToShip()*1;
if ($itemQtyToShip>0) {
$itemQtyOnHand = $stockItem->getQty()*1;
if ($itemQtyOnHand>0) {
//use the order item id as key
//set the amount to invoice for as the value
$toShip[$item->getId()] = $itemQtyToShip;
} else {
//if not shipping the item set the qty to 0
$toShip[$item->getId()] = 0;
}
}
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($toShip);
This creates a proper invoice.

Categories