""" Attachment Model ============= Model function for getting statement attachment information. """ from ows_accounting import config from ows_accounting import response from ows_accounting.constants import error from ows_accounting.utils import dynamodb def _get_attachment_primary_key_value(account_type, account_id, period_ids): """Get formatted attachment primary key value. Args: account_type (str): account type from GRASS. account_id (int): account id (vendor id). period_ids (list): list of accounting periods. Returns: str: Formatted primary key value """ primary_key_account_type_id = '{}{}'.format(account_type, account_id) periods_str = '_'.join(str(period_id) for period_id in period_ids) return '{}_{}'.format(primary_key_account_type_id, periods_str) def _prepare_attachment_item(item): """Prepare attachment data for json serialization. Args: item (dict): attachment data Returns: dict: attachment data ready for json serialization. """ item['file_size'] = int(item['file_size']) return item def get_attachments( account_type, account_id, period_ids): """Get attachments information for account by periods. Args: account_type (str): account type from GRASS. account_id (int): account id (vendor id). period_ids (list): list of accounting periods. Returns: Response: response object with a list of integer values of accounting period ids. Response error if key is not found. """ table = dynamodb.get_table( config.ACCOUNTING_STATEMENT_ATTACHMENT_TABLE) primary_key = _get_attachment_primary_key_value( account_type, account_id, period_ids ) records = dynamodb.query_items( table, 'label_type_id_period_id', primary_key) if records: prepared_records = [ _prepare_attachment_item(item) for item in records] return response.Response(prepared_records) return response.create_error_response( code=error.ERROR_CODE_INVALID_ATTACHMENT_PERIOD, message=error.ERROR_MESSAGE_INVALID_ATTACHMENT_PERIOD) def get_attachment( account_type, account_id, period_ids, file_name): """Get single attachment information for account by periods. Args: account_type (str): account type from GRASS. account_id (int): account id (vendor id). period_ids (list): list of accounting periods. file_name (str): file name with ext., e.g. test.txt. Returns: Response: response object with a list of integer values of accounting period ids. Response error if key is not found. """ table = dynamodb.get_table( config.ACCOUNTING_STATEMENT_ATTACHMENT_TABLE) primary_key = _get_attachment_primary_key_value( account_type, account_id, period_ids ) records = dynamodb.query_items( table, 'label_type_id_period_id', primary_key, 'file_name', file_name) if len(records) == 1: record = records[0] return response.Response(_prepare_attachment_item(record)) return response.create_error_response( code=error.ERROR_CODE_INVALID_ATTACHMENT_PERIOD, message=error.ERROR_MESSAGE_INVALID_ATTACHMENT_PERIOD)