codeunit 50750 /Riksbankens Valutakurser ACU/
{
/*Retrieves the latest currency exchange rates from Sveriges Riksbank.
Link to Sveriges Riksbanks API-portal: https://developer.api.riksbank.se/apis
Tutorial: https://www.navuser.com/how-to-call-a-rest-api-get-request-in-al/
*/
TableNo = /Job Queue Entry/;
var
GeneralLedgerSetup: Record /General Ledger Setup/;
Currency: Record Currency;
CurrencyExchangeRate: Record /Currency Exchange Rate/;
BaseURL: Label 'https:/api.riksbank.se/swea/v1/Observations/Latest/';
MyHTTPClient: HttpClient;
HTTPResponseMessage: HttpResponseMessage;
RequestFailError: Label 'Unable to process the request through the API.';
InvalidResponseError: Label 'Invalid response.';
trigger OnRun();
var
JsonString: Text;
JsonTokenVar: JsonToken;
JsonObj: JsonObject;
CurrencyExchangeRateDate: Date;
CurrencyExchangeRateValue: Decimal;
begin
GeneralLedgerSetup.GET();
GeneralLedgerSetup.TESTFIELD(/LCY Code/, 'SEK');
//Loops through all the currencies.
if Currency.FindSet() then begin
repeat
JsonString := GetCurrencyDataByAPI();
//if not JsonObj.ReadFrom(JsonString) then
// Error(InvalidResponseError);
JsonTokenVar.ReadFrom(JsonString);
if JsonTokenVar.IsObject then begin
//Retrieves the relevant currency data from the retrieved data from Sveriges Riksbank.
CurrencyExchangeRateDate := GetJsonObjectValueFromToken('date', JsonTokenVar).AsDate();
CurrencyExchangeRateValue := GetJsonObjectValueFromToken('value', JsonTokenVar).AsDecimal();
CurrencyExchangeRateValue := Round(CurrencyExchangeRateValue, 0.01);
InsertCurrencyExchangeRate(CurrencyExchangeRateDate, CurrencyExchangeRateValue);
end;
until Currency.Next() = 0;
end;
end;
local procedure InsertCurrencyExchangeRate(CurrencyExchangeRateDate: Date; CurrencyExchangeRateValue: Decimal);
begin
//Inserts the currency data.
CurrencyExchangeRate.Init();
CurrencyExchangeRate./Currency Code/ := Currency.Code;
CurrencyExchangeRate./Starting Date/ := CurrencyExchangeRateDate;
CurrencyExchangeRate./Exchange Rate Amount/ := 1;
CurrencyExchangeRate./Adjustment Exch. Rate Amount/ := 1;
CurrencyExchangeRate./Relational Exch. Rate Amount/ := CurrencyExchangeRateValue;
CurrencyExchangeRate./Relational Adjmt Exch Rate Amt/ := CurrencyExchangeRateValue;
if not CurrencyExchangeRate.Insert() then
CurrencyExchangeRate.Modify();
end;
local procedure GetCurrencyDataByAPI() JsonString: Text;
begin
//Retrieves the currency daata from Sveriges Riksbank and returns it as a JsonString.
if not MyHTTPClient.Get(BaseURL + GeneralLedgerSetup./LCY Code/ + Currency.Code + 'PMI', HTTPResponseMessage) then
Error(RequestFailError);
HTTPResponseMessage.Content().ReadAs(JsonString);
end;
local procedure GetJsonObjectValueFromToken(Parameter: Text; JsonTokenVar: JsonToken): JsonValue;
begin
//Getting values of the parameters in the JSON object.
JsonTokenVar.AsObject().Get(Parameter, JsonTokenVar);
exit(JsonTokenVar.AsValue());
end;