"""Lambda function module.""" import copy import json import dynamodb # noqa import common_config import sentry # noqa import s3 # noqa import util # noqa from constants import general from constants import common def format_period_ids_string(period_ids): """Format period ids to store in dynamodb. Args: period_ids (list): periods ids list Returns: str: Formatted periods string, separated by coma e.g. 217,218,219 """ return ','.join(str(period_id) for period_id in period_ids) def get_attachment_destination_key(account_id, account_type, file_name): """Get attachment destination key for S3 move operation. Args: account_id (int): account id account_type (str): account type file_name (str): attachment file name Result: str: destination S3 key suitable for move operation """ account_dir = '{}{}'.format(account_type, account_id) dest_key = common_config.S3_DESTINATION_KEY_TEMPLATE.format( attachments_dir=common_config.S3_PER_LABEL_DIR, account_dir=account_dir, file_name=file_name) return dest_key @sentry.sentry_capture_exception def handler(event, context): """Lambda entry point.""" if common_config.IGNORE_ALL_EVENTS is not None: common_config.logger.warning(common.IGNORE_MESSAGE) return sns_body = event['Records'][0]['Sns'] message_json = sns_body['Message'] message = json.loads(message_json) attachment_month_data = util.s3_event_get_attachment_details( message['s3_event'], message['attachment_attrs']) account_id = attachment_month_data['label_id'] account_type = attachment_month_data['account_type'] source_key = attachment_month_data['file_key'] file_name = util.get_file_name_from_key(source_key) dest_key = get_attachment_destination_key( account_id, account_type, file_name) move_successful = s3.move_object( bucket=common_config.S3_BUCKET_NAME, source_key=source_key, dest_key=dest_key) if move_successful: attachment_month_data['file_key'] = dest_key else: common_config.logger.info(general.MOVE_ERROR) period_id = attachment_month_data['period_ids'] attachment_month_data['event_timestamp'] = sns_body['Timestamp'] # generate primary key for monthly label Item attachment_month_data['label_type_id_period_id'] = ( util.get_attachment_primary_key_value( account_type, account_id, [period_id])) # Get ready quarter data attachment_quarter_data = copy.copy(attachment_month_data) quarter_period_ids = util.get_quarter_periods_by_period(period_id) attachment_quarter_data['period_ids'] = format_period_ids_string( quarter_period_ids) # Form sort key, to avoid duplicates attachment_quarter_data['file_name'] = util.format_quarter_file_name( attachment_quarter_data['file_name'], period_id) # Form primary key attachment_quarter_data['label_type_id_period_id'] = ( util.get_attachment_primary_key_value( attachment_quarter_data['account_type'], attachment_quarter_data['label_id'], quarter_period_ids ) ) dynamodb.batch_write_data(common_config.DYNAMODB_TABLE_SUCCESS, [ attachment_month_data, attachment_quarter_data])