В первой части было описано как можно грузить курсы валют с сайта ЦБ РФ. Но иногда случаются ситуации, когда сервер ЦБ РФ временно перестает отвечать на запросы. В таком случае необходим другой источник курсов, т.к. ждать когда вновь поднимут сервер можно долго. Поиск в google навел на скромный API сайта РБК, который позволяет так же ежедневно грузить курсы валют.Ниже представлена реализация загрузки в SAP.
Пример отчета загрузки курсов валют в SAP с РБК
types: begin of t_fline,
line(255) type c,
end of t_fline .
types: t_fline_tab type standard table of t_fline .
types: begin of t_valute,
numcode(20),
charcode(20),
nominal type vtb_dfans-cffact,
name(150),
value type vtb_dfans-value,
end of t_valute .
types: t_data type sorted table of t_valute with unique key numcode charcode.
types: t_date_str(10) type c .
start-of-selection.
perform load_cbrf_rates_from_rbc_site using sy-datum.
*&---------------------------------------------------------------------*
*& Form load_cbrf_rates_from_rbc_site
*&---------------------------------------------------------------------*
form load_cbrf_rates_from_rbc_site using iv_date type bldat.
types: begin of ty_response,
line(50),
end of ty_response.
data: begin of ls_date,
year(4) type c,
month(2) type c,
day(2) type c,
end of ls_date.
data: lr_client type ref to if_http_client,
lr_response type ref to if_http_response,
* lr_request TYPE REF TO if_http_request,
l_response type string,
l_url type string,
lv_datetext(10) type c,
lt_tcurc type table of tcurc,
ls_tcurc type tcurc,
lt_response type table of ty_response,
ls_response type ty_response,
ls_data type t_valute,
lt_data type t_data,
lv_date type t_date_str.
clear lv_datetext.
if iv_date is initial.
ls_date = sy-datum.
write sy-datum to lv_date dd/mm/yyyy.
else.
ls_date = iv_date.
write iv_date to lv_date dd/mm/yyyy.
endif.
" Дата в формате ГГГГ/ММ/ДД
concatenate ls_date-year '/' ls_date-month '/' ls_date-day into lv_datetext.
clear lt_data[].
" Поулчим валюты, по которым хотим получить курс
select * from tcurc into table lt_tcurc where not waers eq 'USD2'.
loop at lt_tcurc into ls_tcurc." ALTWR
concatenate 'http://cbrates.rbc.ru/tsv/' ls_tcurc-altwr '/' lv_datetext '.tsv'
into l_url.
" 'http://cbrates.rbc.ru/tsv/978/2013/10/07.tsv' 978 - код валюты по гос. классификатору
" 'http://cbrates.rbc.ru/tsv/cb/978.tsv' - загрузка всех курсов валюты Евро (978)
" за все время существования РБК (одним файлом).
call method cl_http_client=>create_by_url
exporting
url = l_url
importing
client = lr_client
exceptions
internal_error = 1
argument_not_found = 2
plugin_not_active = 3
others = 4.
if sy-subrc ne 0.
" Ошибка обращения к серверу
" message e002 raising create_url_err.
endif.
* Отправка запроса
call method lr_client->send
* exporting timeout = timeout
exceptions http_communication_failure = 1
http_invalid_state = 2
http_processing_failed = 3
others = 4.
if sy-subrc ne 0.
" Ошибка запроса к серверу
" message e003 raising send_error.
endif.
* Получение ответа сервера
call method lr_client->receive
exceptions
http_communication_failure = 1
http_invalid_state = 2
http_processing_failed = 3
others = 4.
if sy-subrc ne 0.
" Ошибка получения ответа от сервера
" message e004 raising receive_error.
endif.
lr_response = lr_client->response .
l_response = lr_response->get_cdata( ).
* Закрытие соединения
call method lr_client->close
exceptions
http_invalid_state = 1
others = 2.
check not l_response is initial
and not l_response cp '*Document Not Found*'.
" В ответе приходят следующие данные, разделенные табуляцией:
" Кратность. Число, дробная часть отделена точкой.
" Курс. Число, дробная часть отделена точкой.
replace all occurrences of cl_abap_char_utilities=>newline
in l_response with ''.
clear lt_response[].
split l_response at cl_abap_char_utilities=>horizontal_tab
into table lt_response.
clear ls_data.
ls_data-numcode = ls_tcurc-altwr.
ls_data-charcode = ls_tcurc-waers.
read table lt_response into ls_response index 1.
ls_data-nominal = ls_response-line.
read table lt_response into ls_response index 2.
replace all occurrences of '.' in ls_response-line with ','.
ls_data-value = ls_response-line.
select single ltext from tcurt into ls_data-name
where spras eq 'R' and waers eq ls_tcurc-waers.
insert ls_data into table lt_data.
endloop.
perform check_rates changing lt_data.
*
perform create_exchrate using lt_data lv_date.
endform. "load_cbrf_rates_from_rbc_site
*&---------------------------------------------------------------------*
*& Form check_rates
*&---------------------------------------------------------------------*
form check_rates changing ct_data type t_data.
data: begin of ls_waers,
waers type waers_curc,
end of ls_waers,
lt_waers like standard table of ls_waers,
ls_data like line of ct_data.
select waers from tcurc into table lt_waers.
loop at ct_data into ls_data.
read table lt_waers with key waers = ls_data-charcode transporting no fields.
if sy-subrc is not initial.
delete table ct_data from ls_data.
endif.
endloop.
endform. "check_rates
*&---------------------------------------------------------------------*
*& Form create_exchrate
*&---------------------------------------------------------------------*
form create_exchrate using it_data type t_data
iv_date type t_date_str.
data: ls_data like line of it_data,
ls_rec type bapi1093_0,
ls_rec2 type bapi1093_0,
lt_rec type standard table of bapi1093_0,
lt_return type standard table of bapiret2,
ls_return like line of lt_return,
lv_usd2_kurs type p length 9 decimals 4.
loop at it_data into ls_data.
replace all occurrences of ',' in ls_data-value with '.' .
clear ls_rec.
ls_rec-rate_type = 'M'.
ls_rec-from_curr = ls_data-charcode.
ls_rec-to_currncy = 'RUB'.
ls_rec-valid_from = iv_date+6(4).
ls_rec-valid_from+4(2) = iv_date+3(2).
ls_rec-valid_from+6(2) = iv_date(2).
ls_rec-exch_rate = ls_data-value.
ls_rec-from_factor = ls_data-nominal.
ls_rec-to_factor = '1'.
if ls_data-charcode = 'USD'. "#EC NOTEXT
move ls_rec to ls_rec2.
ls_rec2-from_curr = 'USD2'.
ls_rec2-exch_rate = ls_rec-exch_rate * '1.02'.
lv_usd2_kurs = ls_rec2-exch_rate.
ls_rec2-exch_rate = lv_usd2_kurs.
append ls_rec2 to lt_rec.
endif.
append ls_rec to lt_rec.
endloop.
perform add_new_conversion tables lt_rec.
call function 'BAPI_EXCHRATE_CREATEMULTIPLE'
exporting
upd_allow = 'X'
* CHG_FIXED = ' '
* DEV_ALLOW = '000'
tables
exchrate_list = lt_rec
return = lt_return
.
read table lt_return into ls_return with key type = 'E'.
if sy-subrc = 0.
message id ls_return-id type ls_return-type number ls_return-number
with ls_return-message_v1 ls_return-message_v2 ls_return-message_v3 ls_return-message_v4.
call function 'BAPI_TRANSACTION_ROLLBACK'.
else.
call function 'BAPI_TRANSACTION_COMMIT'.
endif.
endform. "create_exchrate
*&---------------------------------------------------------------------*
*& Form add_new_conversion
*&---------------------------------------------------------------------*
form add_new_conversion tables ct_rec structure bapi1093_0.
data: ls_sap_data like line of ct_rec,
lt_convers type standard table of tcurf,
ls_curf type tcurf.
data: lv_inv_date type gdatu_invv.
loop at ct_rec into ls_sap_data.
" get conversion customizing on date
select * from tcurf up to 1 rows into ls_curf
where kurst = ls_sap_data-rate_type
and fcurr = ls_sap_data-from_curr
and tcurr = ls_sap_data-to_currncy
and gdatu ge lv_inv_date
order by gdatu descending.
exit.
endselect.
lv_inv_date = ls_sap_data-valid_from.
translate lv_inv_date using '09182736455463728190'.
if sy-subrc is not initial
or ls_curf-ffact <> ls_sap_data-from_factor
or ls_curf-tfact <> ls_sap_data-to_factor.
clear ls_curf.
ls_curf-kurst = ls_sap_data-rate_type.
ls_curf-fcurr = ls_sap_data-from_curr.
ls_curf-tcurr = ls_sap_data-to_currncy.
ls_curf-gdatu = lv_inv_date.
ls_curf-ffact = ls_sap_data-from_factor.
ls_curf-tfact = ls_sap_data-to_factor.
insert tcurf from ls_curf.
if sy-subrc is not initial.
modify tcurf from ls_curf.
endif.
endif.
endloop.
endform. "add_new_conversion
Комментариев нет:
Отправить комментарий