"""Snapshot exchange_rates task.""" from abacus_common_data.currency import Currency import pandas from lib.constants import DIRECTORY_MODULE_CALCULATE_TOTALS from lib.constants import FILE_NAME_EXCHANGE_RATES_PARQUET from lib.utils import aws from lib.utils import ows from tasks.accounting_run_calculate import helpers def snapshot_exchange_rates(dag_run: dict, **kwargs) -> None: """Task to snapshot exchange_rates as a parquet file and save them on S3. Args: dag_run (dict): config of the DAG this task belongs to kwargs (dict): any other optional arguments """ event = helpers.get_event_from_params(dag_run, **kwargs) accounting_period, accounting_run = helpers.get_event_records(event.target_id) snapshot_directory = helpers.build_snapshot_prefix_from_accounting_run( accounting_period, accounting_run, DIRECTORY_MODULE_CALCULATE_TOTALS ) exchange_rates_location = aws.location( snapshot_directory, FILE_NAME_EXCHANGE_RATES_PARQUET ) exchange_rates = _get_exchange_rates(accounting_period.get('statement_period_id')) exchange_rates_df = pandas.DataFrame(exchange_rates) exchange_rates_df.to_parquet( exchange_rates_location.url, index=False ) def _get_exchange_rates(statement_period_id: int) -> list: """Request exchange_rates from ows-royalties. Args: statement_period_id (int): ID of the parent statement_period Returns: a list of formatted exchange_rates """ exchange_rates = [] response = ows.get_exchange_rates_by_statement_period(statement_period_id) for exchange_rate in response: from_currency_id = Currency(exchange_rate.get('from_currency_code')).number to_currency_id = Currency(exchange_rate.get('to_currency_code')).number exchange_rates.append({ 'exchangeRateId': exchange_rate.get('exchange_rate_id'), 'exchangeFromCurrencyId': from_currency_id, 'exchangeToCurrencyId': to_currency_id, 'exchangeRate': exchange_rate.get('rate') }) return exchange_rates