"""Lambda create_subaccount_sme_analytics function module.""" import config from config import app_logger as logger from owsrequest import request class MultipleSubaccountsExist(Exception): """Bad Request cannot retry Exception.""" pass class BadRequest(Exception): """Bad Request cannot retry Exception.""" pass class RetryException(Exception): """Retry Exception.""" pass def check_subaccount_already_exist(input_data): """Check that subaccount is already exist.""" vendor_id = input_data.get('vendor_id') subaccount_name = input_data.get('rep_owner_name') logger.info( f'Check if subaccount with name subaccount_name ' f'{subaccount_name} and vendor {vendor_id} is already exist.') get_subaccount_result = request.process( config.LAMBDA_NAME, config.ENVIRONMENT, config.GET_SUBACCOUNT_ENDPOINT_METHOD, config.OWS_SERVICE_NAME, config.GET_SUBACCOUNT_ENDPOINT.format( vendor_id=vendor_id), headers=config.OWS_REQUEST_HEADERS) logger.info(get_subaccount_result) # if no such subaccounts if get_subaccount_result.status_code == 404: return if get_subaccount_result.status_code == 200: subaccounts = list( filter( lambda s: s['subaccount_name'] == subaccount_name, get_subaccount_result.json()['items'] )) if not subaccounts: return if len(subaccounts) == 1: logger.info( f'Subaccount with subaccount_name {subaccount_name} ' f'is already exists.') return subaccounts[0] if len(subaccounts) > 1: raise MultipleSubaccountsExist( f'There are several subaccounts for vendor ' f'{vendor_id} with name {subaccount_name}.') if get_subaccount_result.status_code >= 500: logger.info( f'Error ows response ' f'status_code={get_subaccount_result.status_code} ' f'error={get_subaccount_result.text}') raise RetryException( 'check_subaccount_already_exist failed, so retry.') # if response status code not 404 and not 200 return BadRequest('Error with checking subaccount') def handler(event, context): """Lambda entry point.""" input_data = event or {} existing_subaccount = check_subaccount_already_exist(input_data) if existing_subaccount: # skip subaccount creation if subaccount is already exist return existing_subaccount else: return {'subaccount_id': None}