""" Accounting period model. Model for getting details about accounting period """ from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import Numeric from sqlalchemy.exc import SQLAlchemyError from ows_accounting import response from ows_accounting.constants import db from ows_accounting.constants import error from ows_accounting.utils import mysql from ows_accounting.utils import sentry class CurrencyExchangeRates(mysql.BaseModel): """Table definition for currency exchange rates table.""" __tablename__ = "currency_exchange_rates" currency_exchange_rates_id = Column( 'id', Integer, primary_key=True, autoincrement=True) period_id = Column('period_id', Integer) currency_from_id = Column('currency_from_id', Integer) currency_to_id = Column('currency_to_id', Integer) exchange_rate = Column('exchange_rate', Numeric(18, 6)) def as_dict(self): """Return object as dict. Returns dict: Dictionary representation of the object """ currency_dict = { 'id': self.currency_exchange_rates_id, 'period_id': self.period_id, 'currency_from_id': self.currency_from_id, 'currency_to_id': self.currency_to_id, 'exchange_rate': self.exchange_rate } return currency_dict def get_currency_exchange_rate( period_id, currency_from_id, currency_to_id=db.CURRENCY_ID_USD): """Get currency exchange rate. Args: period_id (int): Accounting period id. currency_from_id (int): Source currency Id. currency_to_id (int): Destination currency Id. Returns: response.Response: Currency exchange rate or error in Response object. """ try: with mysql.db_session(False) as session: exchange_rate = session.query(CurrencyExchangeRates).filter_by( period_id=period_id, currency_to_id=currency_to_id, currency_from_id=currency_from_id).first() if not exchange_rate: return response.create_not_found_response( error.ERROR_MESSAGE_CURRENCY_NOT_FOUND) return response.Response(exchange_rate.as_dict()) except SQLAlchemyError as ex: if sentry.sentry_client: sentry.sentry_client.captureException() return response.create_fatal_response(str(ex))