Live Currency Updates, for Salesforce Multiple Currency

Updated: May 27, 2020

Do you have multiple currencies enabled, and you miss to update them or have to spend time while checking the latest currency conversions? So here is the solution, this Lightning Component fetches the real-time values and you can put this anywhere in your Salesforce Instance.

Here, I am fetching live currency conversion data from an API and to convert that JSON to apex class I used https://json2apex.herokuapp.com/ one of the best tools to convert JSON directly into Apex class and also it creates Test Class simultaneously.

https://api.exchangeratesapi.io/latest

Note: To test this out, make sure your org has multiple currencies enabled. For fetching the details of multiple currencies I have used CurrencyType field. Moreover, this field doesn't allow DML operations.


Let's see the code.

currencyConvertorComponent.cmp
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction"
                access="global" 
                controller = "CreateDataFromApi">
    <!-- -->
    
    <!--Attributes -->
    
    <aura:attribute name="currencyValue" type="list" />
    
    <!--Handlers -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <!--Body -->
    <div class="slds-grid slds-wrap" style="background: white;">
        <aura:iteration items="{!v.currencyValue}" var="code"> 
            
            <div class="slds-col slds-size_1-of-2 slds-p-around_small" style = "height = 100%;">
                <article class="slds-card">
                    <div class="slds-card__body slds-card__body_inner">
                        <lightning:avatar src="/bad/image/url.jpg" initials="{!code.symbol}" fallbackIconName="standard:avatar"  alternativeText="{!code.IsoCode}" class="slds-m-right_small"/>
                        {!code.country}
                        <aura:if isTrue = "{!code.corporateCurrency}">
                            <lightning:badge label="Corporate Currency"  class="slds-m-left_xx-small"/> 
                        </aura:if>
                        
                        <p><lightning:formattedText class = "rate" value="Current Conversion Rate = " /> {!code.currentRate}</p>
                        <p><lightning:formattedText class = "rate" value="Latest Conversion Rate = " />  {!code.updatedRate}</p>
                    </div>
                </article>
                
            </div>
        </aura:iteration>
        
    </div>
</aura:component>
currencyConvertorComponentController.js
({
    doInit : function(component, event, helper) {
        var action = component.get("c.createAllData");
        action.setCallback(this, function(response) {
            var currency_symbols = {
                'USD': '$', // US Dollar
                'EUR': '€', // Euro
                'CRC': '₡', // Costa Rican Colón
                'GBP': '£', // British Pound Sterling
                'ILS': '₪', // Israeli New Sheqel
                'INR': '₹', // Indian Rupee
                'JPY': '¥', // Japanese Yen
                'KRW': '₩', // South Korean Won
                'NGN': '₦', // Nigerian Naira
                'PHP': '₱', // Philippine Peso
                'PLN': 'zł', // Polish Zloty
                'PYG': '₲', // Paraguayan Guarani
                'THB': '฿', // Thai Baht
                'UAH': '₴', // Ukrainian Hryvnia
                'VND': '₫', // Vietnamese Dong
            };
            
            var state         = response.getState();
            var currencyValue = [];
            if (state === "SUCCESS"){
                var serverResponse = response.getReturnValue();
                var currencyConversionResponse = serverResponse.varCurrencyConvert;
                var updatedOrgCurrency = serverResponse.listOfCurrencyInOrg;
                
                for (var i = 0; i< updatedOrgCurrency.length ; i = i+1){
                    
                    for ( var key in currencyConversionResponse.rates ) {
                        if(updatedOrgCurrency[i].IsoCode == key){
                            currencyValue.push({country:key,currentRate:updatedOrgCurrency[i].ConversionRate,corporateCurrency:updatedOrgCurrency[i].IsCorporate, updatedRate:currencyConversionResponse.rates[key], symbol:currency_symbols[key]});
                             
                        }
                    }                
                }
                component.set("v.currencyValue",currencyValue);
               
            }
            else{
                alert('Error...');
            }
        });
        $A.enqueueAction(action); 
    }
})
currencyConvertorComponent.css
.THIS .rate{
    font-weight: bold;
}
CreateDataFromApi.apxc
public class CreateDataFromApi {
    public static String method ='GET';
    @AuraEnabled
    public CurrencyConvert varCurrencyConvert;
    @AuraEnabled
    public List<CurrencyType> listOfCurrencyInOrg;
    @AuraEnabled
    public String corporateCurrency;
    @AuraEnabled
    public static CreateDataFromApi createAllData(){
        CreateDataFromApi varCreateDataFromApi   = new CreateDataFromApi();
        varCreateDataFromApi.listOfCurrencyInOrg = [Select Id, ConversionRate, DecimalPlaces, IsActive, IsCorporate, IsoCode from CurrencyType where IsActive = true ORDER BY ConversionRate DESC];
        for (CurrencyType varcurrency : varCreateDataFromApi.listOfCurrencyInOrg){
            if (varcurrency.IsCorporate == true)
                varCreateDataFromApi.corporateCurrency = varcurrency.IsoCode;
        }
        varCreateDataFromApi.varCurrencyConvert = CurrencyConvert.parse(HttpCallout.makeCallout('https://api.exchangeratesapi.io/latest?base='+varCreateDataFromApi.corporateCurrency,method));
        
        return varCreateDataFromApi;
    }
}

Do, let me know if this helps you!


Thanks for your time.

470 views0 comments

Recent Posts

See All