"""Model for history table in salessheets database.""" from datetime import datetime from oto import response from sqlalchemy import Column from sqlalchemy import DateTime from sqlalchemy import Enum from sqlalchemy import exc as sqlalchemy_exc from sqlalchemy import Integer from sqlalchemy import String from salessheets.connectors import mysql from salessheets.connectors import sentry from salessheets.constants import errors from salessheets.constants import salessheets_history class Job(mysql.BaseModel): """Class representing the salessheets history's job.""" __tablename__ = 'sales_sheets_history' job_id = Column('id', Integer, primary_key=True, autoincrement=True) user_id = Column(String(127)) context = Column(String(1000)) context_type = Column(Enum(*salessheets_history.ALLOWED_CONTEXT_TYPES)) output_format = Column( Enum(*salessheets_history.ALLOWED_GENERATION_METHODS)) status = Column( Enum(*salessheets_history.GENERATION_STATUSES), default=salessheets_history.REQUESTED) timestamp = Column(DateTime, default=datetime.utcnow) def as_dict(self): """Return object as dict. Returns: dict: Dictionary representation of object """ job_dict = { 'id': self.job_id, 'user_id': self.user_id, 'context': self.context, 'context_type': self.context_type, 'output_format': self.output_format, 'status': self.status, 'timestamp': self.timestamp.isoformat(), } return job_dict def update_job(job_id, status): """Function the updates task status. Sets status and timestamp Args: job_id (int): task id status (str): new status, should be requested | in_progress | completed | error """ try: with mysql.salessheets_history_session_scope() as session: job = session.query(Job).filter_by(job_id=job_id) if not job: return response.create_not_found_response( errors.JOB_DOES_NOT_EXIST) job.update( { 'status': status, 'timestamp': datetime.utcnow() }) return response.Response() except ( sqlalchemy_exc.DBAPIError, sqlalchemy_exc.DisconnectionError, sqlalchemy_exc.SQLAlchemyError, TimeoutError): if sentry.sentry_capture_exception: sentry.sentry_capture_exception() return response.create_error_response( code=errors.ERROR_CODE_INVALID_JOB_STATUS, message=errors.ERROR_MESSAGE_INVALID_JOB_STATUS, status=400)