Sunday, January 27, 2013

Salesforce.com - Custom Currency Conversion Code

I would like to explain this issue through a scenario, suppose we need to do integration between SAP and Salesforce.com. Salesforce.com partner portal will used to create opportunity for partners and SAP will be used to maintain the placed orders. 

We need to update the amount of opportunity products which will be rolled up at opportunity level to display actual amount. 

What will the actual amount? if Salesforce.com Opportunity's Currency in USD and SAP Opportunity's Currency in INR.

There is a limitation; Salesforce.com system does not allow you to change the currency of Opportunity if there is any product line item associated with it.

In this case we need to add custom apex code in salesforce.com web service which will identify  the CurrencyCode of Opportunities to covert the amount.

You can use this method for currency conversion:
   1 parameter - Old Currency code which will be used a base/incoming Currency and amount
   2 parameter - New Currency code in which you want to actual amount. 
   3 parameter - Amount to convert 


public Double convertCurrencyWithApexCode(String oCurrency, String nCurrency, Double amount){
        Set<String> isoCodes = new Set<String>();
        Map<String,Double> conversion_rates = new Map<String,Double>();
        
        isoCodes.add(oCurrency);
        isoCodes.add(nCurrency);
        
        for(CurrencyType curr: [SELECT IsoCode,ConversionRate 
                                             FROM CurrencyType 
                                             WHERE IsoCode in: isoCodes]){          
            conversion_rates.put(curr.IsoCode,curr.ConversionRate);        
        }
        //Convert incoming Opportuntiy Amount into USD...
        Double conversionRate = conversion_rates.get(oCurrency);
        amount = amount / v;
        
        //convert amount as per new currency. 
        if(nCurrency != 'USD'){
            conversionRate = conversion_rates.get(nCurrency);
            amount = amount * conversionRate;
        }
        return amount;
    }

Double amt = converCurrencyWithApexCode ('INR','USD',5403.00);

Using this code we can avoid the inconsistency between two systems, which is most important for any business.

5 comments:

  1. Replies
    1. Double conversionRate = conversion_rates.get(oCurrency);
      amount = amount / conversionRate;

      it is conversionRate

      Delete
  2. Thanks for the conversion algorithm. Besides the v variable fix I would bulkify it since the CurrencyType query will fire every time its called.

    ReplyDelete
  3. do you have a bulkified version of this code?

    ReplyDelete