"""Model and functions to work with store data.""" from oto import response from sqlalchemy import CheckConstraint from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.dialects import mysql from availability.connectors import sql from availability.constants import error from availability.constants import field_const from availability.constants import models from availability.models import error_handlers class Store(sql.BaseModel): """Class representing the store table. The table is used to make a relation between the product and the store, where the product was uploaded. Store table provides configuration for polling, delay before polling start and for how long the product should be polled after the sales start date. """ __tablename__ = models.STORE_TABLE store_id = Column( 'id', mysql.INTEGER(unsigned=True), primary_key=True, autoincrement=False) name = Column(String(45), nullable=False) # TODO: check constraints on RDS. polling_delay_days = Column( Integer, CheckConstraint('{column}<{max}'.format( column=models.POLLING_DELAY_DAYS, max=models.MAXIMUM_POLLING_DELAY))) poll_days_after_sales = Column( Integer, CheckConstraint('{column}<{max}'.format( column=models.POLL_DAYS_AFTER_SALES, max=models.MAXIMUM_POLL_DAYS_AFTER_SALES))) def as_dict(self): """Return dictionary representation of the store data. Returns: dict: Store fields. """ return { field_const.STORE_ID: self.store_id, field_const.STORE_NAME: self.name, field_const.POLLING_DELAY_DAYS: self.polling_delay_days, field_const.POLL_DAYS_AFTER_SALES: self.poll_days_after_sales } @error_handlers.sqlalchemy_error_handler def get_store_by_id(store_id): """Get store data from db by store id. Args: store_id (int): Store PK. Returns: response.Response: Store.as_dict() in message attribute or error response. """ with sql.session_scope() as session: store = session.query(Store).filter_by( store_id=store_id).first() if not store: return response.create_not_found_response( error.ERROR_MESSAGE_STORE_NOT_FOUND) return response.Response(store.as_dict())