"""Revenue cache model. Revenue cache models are stored in AWS ElastiCache Redis (For reducing RedShift load) """ import json import time from ows_accounting import response from ows_accounting.connectors import redis from ows_accounting.constants import error def _get_key(account_type, account_id, period_id): """Get generated key for cache. Args: account_type (str): Account type from grass account_id (int): Account Id period_id (int): Accounting period Id Returns: string: Key for cache record identifier """ return 'revenue:{account_type}:{account_id}:{period_id}'.format( account_type=account_type, account_id=str(account_id), period_id=str(period_id) ) def _get_created_time(): """Get cache record creation time in specified format. Returns: string: Formatted current time """ return time.strftime("%Y%m%d%H%M%S", time.localtime()) def save( account_type, account_id, period_id, revenue, num_transactions, gross_revenue=None): """Save revenue information to cache. Args: account_type (str): Account type from grass account_id (int): Account Id period_id (int): Accounting period Id revenue (float): Account net revenue num_transactions (int): Account number of transactions gross_revenue (float): Account gross revenue Returns: response.Response: Saved data or error response """ data = { 'revenue': revenue, 'num_transactions': num_transactions, 'created': _get_created_time() } if gross_revenue: data['gross_revenue'] = gross_revenue result = redis.client.set( _get_key(account_type, account_id, period_id), json.dumps(data)) if result: return response.Response(data) return response.create_error_response( code=error.ERROR_CODE_ELASTICACHE_ERROR, message=error.ERROR_MESSAGE_ELASTICACHE_RECORD ) def get(account_type, account_id, period_id): """Get revenue information. Args: account_type (str): Account type from grass account_id (int): Account Id period_id (int): Accounting period Id Returns: response.Response: Account revenue data or error response """ result = redis.client.get(_get_key(account_type, account_id, period_id)) if result: return response.Response(message=json.loads(result.decode('utf8'))) return response.create_not_found_response()