""" Logic for Period ================ Provides logic for getting accounting period information. """ from ows_accounting import config from ows_accounting import response from ows_accounting.constants import db from ows_accounting.constants import error from ows_accounting.constants import header from ows_accounting.models import accounting_period from ows_accounting.models import fact_sales from ows_accounting.models import ows_contracts from ows_accounting.models import period as period_model def get_available_periods(account_id, account_type): """Get all available accounting periods that have sales for this particular account. Args: account_id (int): vendor_id or subaccount_id. account_type (str): vendor or subaccount. Returns: Response: response object with a list of integer values of accounting period ids. """ user_type = '' if account_type == header.GRASS_ACCOUNT_TYPE_VENDOR: user_type = 'L' if account_type == header.GRASS_ACCOUNT_TYPE_SUBACCOUNT: user_type = 'S' user_id_type = '{}{}'.format(account_id, user_type) result = period_model.get_available_periods(user_id_type) if result: return response.Response(result.message) return response.create_error_response( error.ERROR_CODE_INVALID_PERIOD, error.ERROR_MESSAGE_INVALID_PERIOD) def get_first_period(account_id, account_type, active_accounting_period): """Get first accounting period for this account. If there are sales for the account and it will be the account's `first_statement_period` value, or the period with the first sale. If there are no sales it will be the current active accounting period. """ first_sale_accounting_period = fact_sales.get_first_sale_accounting_period( account_type, account_id).message if not first_sale_accounting_period: return active_accounting_period vendor_first_statement_period = period_model.get_first_statement_period( account_id, account_type).message if vendor_first_statement_period != db.DEFAULT_FIRST_STATEMENT_PERIOD: return vendor_first_statement_period return first_sale_accounting_period def get_all_periods(account_id, account_type): """Get all accounting periods for this account, regardless of whether or not they have sales. """ most_recent_booked_contract = ows_contracts.get_booked_contracts( account_type, account_id, page_offset=0, page_limit=1, sort_order='desc') if not most_recent_booked_contract.message['items']: return response.Response({'items': []}) payment_interval = most_recent_booked_contract.message[ 'items'][0]['payment_interval'] active_accounting_period = config.ACTIVE_ACCOUNTING_PERIOD first_period = get_first_period( account_id, account_type, active_accounting_period) if payment_interval == db.PAYMENT_INTERVAL_QUARTER: periods = accounting_period.get_quarterly_period_information( first_period, active_accounting_period) else: periods = accounting_period.get_monthly_period_information( first_period, active_accounting_period) return periods