"""Import statements.""" import os from accounting import config from accounting.adapters.log import getlogger from accounting.data import get_db_adapter from accounting.data import read_statement_file SELECT_SQL = ( 'SELECT ' 'COUNT(*) as count ' 'FROM `dig_sales` ' 'WHERE `period_id` = {:d}') INSERT_SQL = ( 'INSERT INTO `dig_sales` ' '(`statement_id`, `dms_customer_id`, `actual_statement_no`, `paid`, ' '`year`, `quarter`, `month`, `check_detail_id`, `period_id`, ' ' `activity_rate`, `original_currency_id`) ' 'VALUES {}') VALUE_SQL = ( '({statement_id}, {dms_customer_id}, "{actual_statement_no}", "{paid}", ' '{year}, {quarter}, {month}, "{check_detail_id}", {period_id}, ' '{activity_rate}, {original_currency_id})') 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_statements(): """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: Statements already exist for the current period. """ logger = getlogger() if check_statements_exist_for_period(): raise Exception(ALREADY_EXISTS_TEXT.format(config.PERIOD_ID)) load_statements() logger.info(IMPORT_TEXT.format(config.PERIOD_ID)) def check_statements_exist_for_period(): """Check if currency exchange rates exist for the given period. Returns: bool: if rows exist for the given period. """ db_adapter = get_db_adapter() row = db_adapter.fetch_rows(SELECT_SQL.format(config.PERIOD_ID)) return row[0][0] > 0 def load_statements(): """Build insert sql for exchange rates. Returns: str: Insert SQL for exchange rates. """ # db_adapter = get_db_adapter() for statement in read_statement_file(os.environ.get('STATEMENTS_FILE')): adapter = get_db_adapter() values = VALUE_SQL.format(**statement) adapter.execute(INSERT_SQL.format(values))