This script provides a better way to calculate the exchange rate in a more accurate way and also with better performance.
This will give you the exchange rate of a specific date. Even if a future date is selected(future dates don’t have exchange rates), this function will consider the current date. Also if a day like Sunday is selected and if it does not have any exchange rate on that selected day, this function will not create any error as it will consider the nearest 4 days and the rate of the latest date will be considered.
The inputs of this function are the date and the target currency. It will return an object that shows the exchange rate on that date to the target currency. One can use the id of the source currency to obtain the specific exchange rate.
function exchangeRateCalculator(bill_currency, dateValue) {
try {
var exchangeRateObject = {};
log.debug('dateValue', dateValue);
// var currencyArray = [];
var dateformated = format.parse({
value: dateValue,
type: format.Type.DATE,
timezone: format.Timezone.EUROPE_LONDON
});
var today = new Date();
if (dateformated.getTime() > today.getTime()) {
dateformated = format.parse({
value: today,
type: format.Type.DATE,
timezone: format.Timezone.EUROPE_LONDON
});
}
var month = dateformated.getMonth() + 1;
var year = dateformated.getFullYear();
var date = dateformated.getDate();
toDate = date + "/" + month + '/' + year;
dateformated.setDate(dateformated.getDate() - 4);
var month = dateformated.getMonth() + 1;
var year = dateformated.getFullYear();
var date = dateformated.getDate();
fromDate = date + "/" + month + '/' + year;
// for (var key in currencies) {
// currencyArray.push(currencies[key]);
// }
log.debug('fromDate', fromDate);
log.debug('toDate', toDate)
var currencyrateSearchObj = search.create({
type: "currencyrate",
filters: [
["basecurrency", "anyof", bill_currency],
"AND",
["effectivedate", "within", fromDate, toDate]
],
columns: [
search.createColumn({ name: "basecurrency", label: "Base Currency" }),
search.createColumn({ name: "transactioncurrency", label: "Transaction Currency" }),
search.createColumn({ name: "exchangerate", label: "Exchange Rate" }),
search.createColumn({
name: "effectivedate",
sort: search.Sort.ASC,
label: "Effective Date"
})
]
});
var searchResultCount = currencyrateSearchObj.runPaged().count;
currencyrateSearchObj.run().each(function(result) {
var baseCurrency = result.getValue(currencyrateSearchObj.columns[0]);
var transactioncurrency = result.getValue(currencyrateSearchObj.columns[1]);
var exchangeRate = result.getValue(currencyrateSearchObj.columns[2]);
if (!exchangeRateObject[baseCurrency]) {
exchangeRateObject[baseCurrency] = {};
exchangeRateObject[baseCurrency][transactioncurrency] = exchangeRate
} else
exchangeRateObject[baseCurrency][transactioncurrency] = exchangeRate
return true;
});
return exchangeRateObject;
} catch (err) {
return false;
log.debug('error @ exchangeRateCalculator', err)
}
}