Function to get the latest currency exchange rate based on base currency and transaction currency

The following function can be used to get the latest exchange rate of base currency and transaction currency.

/**
 * Function to get the latest currency exchange rate based on base currency and transaction currency
 * @param baseCurrency
 * @param sourceCurrency
 * @return exchangeRate
 **/
function getExchangeRate(baseCurrency, sourceCurrency) {
    try {
        let exchangeRate = 0;
        var currencyrateSearchObj = search.create({
            type: "currencyrate",
            filters:
                [
                    ["basecurrency", "anyof", baseCurrency],
                    "AND",
                    ["transactioncurrency", "anyof", sourceCurrency]
                ],
            columns:
                [
                    search.createColumn({
                        name: "exchangerate",
                        summary: "MAX",
                        label: "Exchange Rate",
                    }).setWhenOrderedBy({name: 'effectivedate', join: 'currencyrate'})
                ]
        });
        currencyrateSearchObj.run().each(function (result) {
            exchangeRate = result.getValue({
                name: "exchangerate",
                summary: "MAX",
                label: "Exchange Rate"
            });
        });
        return exchangeRate;
    } catch (e) {
        log.debug("Error @ getExchangeRate", e);
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *