"""Model for sales_goal table in sales_goals database.""" from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String from sales_goals.connectors import mysql from sales_goals.constants import error from sales_goals.logic import countries from sales_goals.models import error_handlers class SalesGoalsForCountry(mysql.BaseModel): """Class representing the sales goals for a country.""" __tablename__ = 'sales_goals_for_country' id_for_country = Column( 'id', Integer, primary_key=True, autoincrement=True) sales_goal_id = Column( Integer, ForeignKey('sales_goal.id'), nullable=False) first_week_sales = Column(Integer) country_id = Column(Integer, nullable=False) country_name = Column(String, nullable=False) def to_dict(self): """Return object as dict. Returns: dict: Dictionary representation of object """ return { 'id': self.id_for_country, 'sales_goal_id': self.sales_goal_id, 'first_week_estimate': self.first_week_sales, 'country_name': self.country_name, 'country_id': self.country_id, } @error_handlers.sqlalchemy_error_handler @error_handlers.integrity_error_handler( error_code=error.ERROR_CODE_MODEL_VALIDATION) def fetch_sales_goals_for_country_by_country(sales_goal_id, territory_id): """Get marketing drivers data by project id. Args: sales_goal_id (int): the sales_goal_id. territory_id (int): the territory id. """ with mysql.sales_goals_session_scope() as session: return session.query(SalesGoalsForCountry).filter_by( sales_goal_id=sales_goal_id, country_id=territory_id, ).first() @error_handlers.sqlalchemy_error_handler @error_handlers.integrity_error_handler( error_code=error.ERROR_CODE_MODEL_VALIDATION) def fetch_sales_goals_for_country(sales_goal_id): """Get marketing drivers data by project id. Args: sales_goal_id (int): the sales_goal_id. """ with mysql.sales_goals_session_scope() as session: return session.query(SalesGoalsForCountry).filter_by( sales_goal_id=sales_goal_id, ).all() @error_handlers.sqlalchemy_error_handler @error_handlers.integrity_error_handler( error_code=error.ERROR_CODE_MODEL_VALIDATION) def upsert_sales_goals_for_country( sales_goal_id, territory_id, first_week_estimate): """Create or update territory sales goals. Args: project_id (int): project id of marketing driver. territory_id (int): territory id of marketing driver. first_week_estimate (int): the estimate of the first week of sales Returns: None """ sales_goals_for_country = fetch_sales_goals_for_country_by_country( sales_goal_id, territory_id) with mysql.sales_goals_session_scope() as session: if not sales_goals_for_country: country_name = countries.get_country_name_from_id(territory_id) sales_goals_for_country = SalesGoalsForCountry( sales_goal_id=sales_goal_id, first_week_sales=first_week_estimate, country_id=territory_id, country_name=country_name, ) else: sales_goals_for_country.first_week_sales = first_week_estimate session.add(sales_goals_for_country)