""" Other validators ================ Collection of validators that require more functionality than JSON Schema. """ from ows_accounting import response from ows_accounting.constants import error from ows_accounting.constants import header from ows_accounting.logic import period def validate_periods(request): """Checks given periods are active. Args: request (Flask.request): the request. Returns: response.Response: On success, a list of periods in the DB. On error, code and message corresponding to error triggered. """ # Check if passed account type is valid account_id, account_type = get_account_info_from_request(request) response_account_type = validate_account_type(account_type) if not response_account_type: return response_account_type # Check if account type is present in DB or has periods associated with it response_available_periods = period.get_available_periods( account_id, account_type) if not response_available_periods: return response_available_periods # Check if periods from DB correspond to request db_periods = sorted(response_available_periods.message) request_periods = get_period_from_request(request) if db_periods and request_periods in ','.join( map(str, db_periods)): return response.Response(message=db_periods) return response.create_error_response( code=error.ERROR_CODE_INVALID_REQUEST, message=error.ERROR_MESSAGE_INVALID_PERIOD) def validate_account_type(account_type): """Checks if account type for DynamoDB lookup is valid. Args: account_type (str): Input value to check. Returns: response.Response: Returns status 200 and account type on success. """ if account_type not in [ header.GRASS_ACCOUNT_TYPE_VENDOR, header.GRASS_ACCOUNT_TYPE_SUBACCOUNT]: message = '{error} {account_type}'.format( error=error.ERROR_MESSAGE_INVALID_ACCOUNT, account_type=account_type) return response.create_error_response( code=error.ERROR_CODE_INVALID_REQUEST, message=message) return response.Response(message=account_type) def get_period_from_request(request): """Gets period from request args or body. Args: request (Flask.request): the request. Returns: request_period(str): Retrieved period. """ if request.method == 'POST': data = request.get_json() request_period = data.get('periods') else: request_period = request.args.get('periods', '') request_period = ','.join(sorted(request_period.split(','))) return request_period def get_account_info_from_request(request): """Gets account info from request header or args. Args: request (Flask.request): the request. Returns: account_id, account_type(tuple): Retrieved account info. """ account_id = request.headers.get( header.GRASS_ACCOUNT_ID) or request.args.get('account_id') account_type = request.headers.get( header.GRASS_ACCOUNT_TYPE) or request.args.get('account_type') return account_id, account_type