"""Import currency exchange rates.""" import os from accounting import config from accounting.adapters.file import read_exchange_rate_file from accounting.adapters.log import getlogger from accounting.data import get_db_adapter SELECT_SQL = ( 'SELECT ' 'COUNT(*) as count ' 'FROM `currency_exchange_rates` ' 'WHERE `period_id` = {:d}') INSERT_SQL = ( 'INSERT INTO `currency_exchange_rates` ' '(`period_id`, `currency_from_id`, `currency_to_id`, `exchange_rate`) ' 'VALUES {}') VALUE_SQL = ( '({period_id}, {currency_from_id}, {currency_to_id}, {exchange_rate})') ALREADY_EXISTS_TEXT = ( 'Exchange rates already exist for period {:d}. ' 'Canceling import.') MISMATCH_TEXT = ( 'Import period id does not match current period id. ' 'Given {:d}, expecting {:d}. ' 'Canceling import.') IMPORT_TEXT = 'Importing currency exchange rates for period {:d}' def import_exchange_rates(): """Import currency exchange rates. Performs checks that the given period id does not already exist in the db. Checks that the imported period_id matches the current period_id. Raises: Exception: Exchange rates already exist for the current period. """ db_adapter = get_db_adapter() logger = getlogger() if check_rates_exist_for_period(config.PERIOD_ID): raise Exception(ALREADY_EXISTS_TEXT.format(config.PERIOD_ID)) logger.info(IMPORT_TEXT.format(config.PERIOD_ID)) db_adapter.execute(get_sql( os.environ.get('CURRENCY_EXCHANGE_RATES_FILE'), config.PERIOD_ID)) def check_rates_exist_for_period(period_id): """Check if currency exchange rates exist for the given period. Args: period_id (int): Current period id. Returns: bool: if rows exist for the given period. """ db_adapter = get_db_adapter() row = db_adapter.fetch_rows(SELECT_SQL.format(period_id)) return row[0][0] > 0 def get_sql(filename, period_id): """Build insert sql for exchange rates. Args: filename (str): Path to exchange rates file. period_id (int): Current period id. Returns: str: Insert SQL for exchange rates. """ value_list = [] for rate in read_exchange_rate_file(filename): if period_id != rate['period_id']: raise Exception(MISMATCH_TEXT.format(rate['period_id'], period_id)) value_list.append(VALUE_SQL.format(**rate)) return INSERT_SQL.format(', '.join(value_list))