""" Fact Sales Model. Model functions for getting fact sales information from Snowflake """ from ows_accounting import features from ows_accounting import response from ows_accounting.connectors import snowflake from ows_accounting.constants import header from ows_accounting.models.sql import revenue def get_account_revenue(account_type, account_id, periods): """Get revenue information for account by periods Args: account_type (str): account type from GRASS. account_id (int): account id. periods (list): list of accounting periods. Returns: generator: generator of dictionaries of revenue information. """ if not periods: periods = [0] sql = revenue.SQL_GET_VENDOR_REVENUE if features.is_vendor_gross_net_enabled(): sql = revenue.SQL_GET_GROSS_VENDOR_REVENUE if account_type == header.GRASS_ACCOUNT_TYPE_SUBACCOUNT: sql = revenue.SQL_GET_SUBACCOUNT_REVENUE if features.is_subaccount_gross_net_enabled(): sql = revenue.SQL_GET_SUBACCOUNT_NET_GROSS_REVENUE sql = sql.format(**revenue.SNOWFLAKE_REVENUE_PARAMS) with snowflake.db_session() as session: result = session.execute( sql.format(**revenue.SNOWFLAKE_REVENUE_PARAMS), {'account_id': account_id, 'periods': periods}).fetchall() return result def get_average_monthly_net_revenue(account_type, account_id): """Get the average monthly net revenue for a vendor/subaccount. Args: account_type (str): The account type (vendor or subaccount). account_id (int): The account id. Returns: response.Response: Containing the average monthly net revenue. """ if account_type == header.GRASS_ACCOUNT_TYPE_VENDOR: account_type = 'label' sql = revenue.SQL_GET_AVERAGE_MONTHLY_NET_REVENUE.format( account_type=account_type) with snowflake.db_session() as session: result = session.execute(sql, {'account_id': account_id}).fetchall() return response.Response({ 'average_monthly_net_revenue': round(result[0][0]) }) def get_budget_caps(): """Get the budget caps for all the labels. Returns: response.Response: Containing the budget caps. """ sql = revenue.SQL_GET_BUDGET_CAPS_BASED_ON_REVENUE with snowflake.db_session() as session: result = session.execute(sql).fetchall() processed_result = [{ 'account_type': 'vendor', 'account_id': a[0], 'monthly_total_budget': float(round(a[1], 2)), 'budget_type': a[2] } for a in result if a[1] and a[1] > 0] return response.Response({ 'items': processed_result }) def get_first_sale_accounting_period(account_type, account_id): """Get the first accounting period for which the account has sales. Returns: response.Response: Containing the ID of the accounting period. """ if account_type == header.GRASS_ACCOUNT_TYPE_VENDOR: account_type = 'label' sql = revenue.SQL_GET_FIRST_SALE_ACCOUNTING_PERIOD.format( account_type=account_type) with snowflake.db_session() as session: result = session.execute(sql, {'account_id': account_id}).fetchone() return response.Response(result[0])