"""Provides logic for getting attachments information.""" from ows_accounting import config from ows_accounting import logic from ows_accounting import response from ows_accounting.constants import error from ows_accounting.constants import header from ows_accounting.models import attachment as attachment_model from ows_accounting.utils import pagination from ows_accounting.utils import s3 def get_attachments(account_id, account_type, period_ids): """Get all available attachments for particular account, period ids Args: account_id (int): vendor_id or subaccount_id. account_type (str): vendor or subaccount. period_ids (list): period ids list. Returns: Response: list of attachments objects with pagination. """ if account_type == header.GRASS_ACCOUNT_TYPE_SUBACCOUNT: return response.create_error_response( error.ERROR_CODE_INVALID_REQUEST, error.ERROR_MESSAGE_INVALID_ACCOUNT, 403) user_type = logic.get_user_type_from_accounting_type(account_type) attachments = attachment_model.get_attachments( user_type, account_id, period_ids) response_message = pagination.add_pagination([]) if attachments.status == 200: response_message = pagination.add_pagination(attachments.message) return response.Response(message=response_message) def get_attachment(account_id, account_type, period_ids, file_name): """Get single attachment for particular account, period ids, file_name Args: account_id (int): vendor_id or subaccount_id. account_type (str): vendor or subaccount. period_ids (list): period ids list. file_name (str): file name, e.g. test.csv Returns: Response: attachment object with s3_url field. Return response with code 404 if s3 object does not exist. """ if account_type == header.GRASS_ACCOUNT_TYPE_SUBACCOUNT: return response.create_error_response( error.ERROR_CODE_INVALID_REQUEST, error.ERROR_MESSAGE_INVALID_ACCOUNT, 403) user_type = logic.get_user_type_from_accounting_type(account_type) attachment = attachment_model.get_attachment( user_type, account_id, period_ids, file_name) if not attachment.status == 200: period_ids_str = ', '.join(str(x) for x in period_ids) return response.create_not_found_response( 'attachment not found in DB with params: {},{},{},{}'.format( str(account_id), account_type, period_ids_str, file_name)) item = attachment.message bucket_name = item.get('bucket_name') file_key = item.get('file_key') # Check if object exists if not s3.object_exists(bucket_name, file_key): return response.create_not_found_response( 'S3 object in bucket: {} for file key: {} not found.'.format( bucket_name, file_key)) item.update({'s3_url': s3.get_presigned_url( bucket_name, file_key, config.PRESIGNED_URL_EXPIRES)}) return response.Response(message=item)