"""Model for store table in sales_goals database.""" from oto import response from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import String from sales_goals.connectors import mysql from sales_goals.constants import error from sales_goals.models import error_handlers class Store(mysql.BaseModel): """Class representing the sales goal's store.""" __tablename__ = 'store' store_id = Column( 'id', Integer, primary_key=True, autoincrement=True) name = Column(String, nullable=False) def to_dict(self): """Return object as dict. Returns: dict: Dictionary representation of object """ store_dict = { 'store_id': self.store_id, 'name': self.name } return store_dict @error_handlers.sqlalchemy_error_handler @error_handlers.integrity_error_handler( error_code=error.ERROR_CODE_MODEL_VALIDATION) def create(*, name): """Create a new record in the store table. Args: name (str): store name. Returns: response.Response: .message with Store.to_dict() on success, .errors on failure. """ store_obj = Store(name=name) with mysql.sales_goals_session_scope() as session: session.add(store_obj) return response.Response(store_obj.to_dict()) @error_handlers.sqlalchemy_error_handler @error_handlers.integrity_error_handler( error_code=error.ERROR_CODE_MODEL_VALIDATION) def fetch_by_store_ids(store_ids): """Get stores data from db by the list of store ids. Args: store_ids (list): list of store ids. Returns: response.Response: .message with List of Store.to_dict() on success, .errors on failure. """ with mysql.sales_goals_session_scope() as session: stores = session.query(Store).filter( Store.store_id.in_(store_ids)).all() if not stores: return response.create_not_found_response( error.ERROR_MESSAGE_STORES_DO_NOT_EXIST.format(store_ids=store_ids)) return response.Response([store.to_dict() for store in stores])