Ejemplo n.º 1
0
class Promoter(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(30),
                         nullable=False,
                         unique=True,
                         index=True)
    name = db.Column(db.String(100), nullable=False, index=True)
    description = db.Column(db.String)
    created_on = db.Column(db.DateTime, nullable=False, default=datetime.now)
    longitude = db.Column(db.Float(precision=9))
    latitude = db.Column(db.Float(precision=9))
    email = db.Column(db.String(40))
    category_id = db.Column(db.Integer, db.ForeignKey('event_category.id'))
    category = db.relationship(EventCategory)
    users = db.relationship('User',
                            secondary='promoter_user',
                            backref=db.backref('promoters'))

    def __repr__(self):
        return f'<Promoter: {self.username}>'

    def get_user_role(self, user: User):
        promoter_user = PromoterUser.query.filter(
            PromoterUser.user == user).first()
        return promoter_user.role
Ejemplo n.º 2
0
class Replay(db.Model):
    __tablename__ = 'replay'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    guid = db.Column(db.String(128), default=False, nullable=False)
    version = db.Column(db.Integer, default=False, nullable=False)
    release = db.Column(db.String(128), default=False, nullable=False)

    created_at = db.Column(db.DateTime,
                           nullable=False,
                           server_default=func.now())

    total_players = db.Column(db.Integer, default=False, nullable=False)

    elimination_events = db.relationship("Elimination", backref="Replay")
    stats = db.relationship("ReplayStats", backref="Replay")

    @hybrid_property
    def weapon_usage(self):
        return Counter(i.weapon_type for i in self.elimination_events)

    def __init__(self, **kwargs):
        super(Replay, self).__init__(**kwargs)

    def __json__(self):
        return ['id', 'guid', 'created_at', 'total_players', 'weapon_usage']
Ejemplo n.º 3
0
class COURSE(db.Model):
	__tablename__ = "course_users"
	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
	firstname = db.Column(db.String(128), nullable=True)
	lastname = db.Column(db.String(128), nullable=False)
	email = db.Column(db.String(128), unique=True, nullable=False)
	password = db.Column(db.String, nullable=False)
	admin = db.Column(db.Boolean, default=False, nullable=False)
	email_sent = db.Column(db.Boolean, default=False, nullable=False)
	confirmed = db.Column(db.Boolean, default=False, nullable=False)

	def __init__(self, firstname, lastname, email, password):
		self.firstname = firstname
		self.lastname = lastname
		self.email = email	
		self.password = bcrypt.generate_password_hash(password, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode()

	def to_json(self):
		return {
			'id': self.id,
			'firstname': self.firstname,
			'lastname': self.lastname,
			'email': self.email,
			'admin': self.admin,
			'email_sent': self.email_sent,
			'confirmed': self.confirmed
			
		}

	def encode_auth_token(self, user_id):
		try:
			payload = {
					'exp': datetime.datetime.utcnow() + datetime.timedelta(
																days=current_app.config.get('TOKEN_EXPIRATION_DAYS'),
																seconds=current_app.config.get('TOKEN_EXPIRATION_SECONDS')
																),
					'iat': datetime.datetime.utcnow(),
					'sub': user_id
						}
			return jwt.encode(
							payload,
							current_app.config.get('SECRET_KEY'),
							algorithm='HS256'
							)
		except Exception as e:
			return e


	@staticmethod
	def decode_auth_token(auth_token):
		
		try:
			payload = jwt.decode(auth_token, current_app.config.get('SECRET_KEY'))
			return payload['sub']
		except jwt.ExpiredSignatureError:
			return 'Signature expired. Please log in again'
		except jwt.InvalidTokenError:
			return 'Invalid Token. Please log in again'
Ejemplo n.º 4
0
class MembershipPlan(db.Model):

    __tablename__ = 'membership_plan'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name =  db.Column(db.String(100))
    description =  db.Column(db.String(1000))
    price = db.Column(db.Numeric)
    project_limit = db.Column(db.Integer)
    user_limit = db.Column(db.Integer)
    plan_duration = db.Column(db.Text)
    created_at = db.Column(db.TIMESTAMP)
    created_by = db.Column(db.String(50))
    updated_at =  db.Column(db.Date)
    updated_by = db.Column(db.String(50))
    is_active = db.Column(db.Boolean, default = True)
    is_deleted = db.Column(db.Boolean, default = False)
    
    def __init__(self, id = None, name = "", description = "", price = None, project_limit = None, user_limit = None, plan_duration = None, created_by = "", created_at = "", is_active = "", is_deleted = ""):
        self.id = id
        self.name = name
        self.description = description
        self.price = price
        self.project_limit = project_limit
        self.user_limit = user_limit
        self.plan_duration = plan_duration
        self.created_at = datetime.now()
        self.created_by = created_by

    @classmethod
    def get(cls, id: int):
        return MembershipPlan.query.get(id)
     
    @classmethod
    def all(cls):
        return cls.query.filter_by(is_deleted = False, is_active = True).order_by(cls.created_at.desc())
    
    def to_json(self):
        return json.loads(json.dumps({ "id": self.id, "name" : self.name, "description":self.description, "price":self.price, "project_limit" : self.project_limit, "user_limit" : self.user_limit, "plan_duration" : self.plan_duration, "created_by" : self.created_by, "created_at" : self.created_at, "updated_at" : self.updated_at, "updated_by" : self.updated_by, "is_active" : self.is_active }, default=default_proc))
        
    def save(self):
        db.session.add(self)
        db.session.commit()
        
    def update(self):
        db.session.commit()
        
    def exists(self, id):
        return db.session.query(db.exists().where(id == id)).scalar()

    def delete(self):
        if self.is_deleted:
            return Response.createFailResponse(self, ResponseMessages.not_found, HTTPStatus.NO_CONTENT)
        self.is_deleted = True
        db.session.commit()

    def __repr__(self):
        return "<name: {}>".format(self.name)
Ejemplo n.º 5
0
class User(db.Model):

    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(128), nullable=False)
    email = db.Column(db.String(128), nullable=False)
    active = db.Column(db.Boolean(), default=True, nullable=False)

    def __init__(self, username, email):
        self.username = username
        self.email = email
Ejemplo n.º 6
0
class NewCourse(db.Model):
	__tablename__ = "newcourse"
	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
	coursetitle = db.Column(db.String(128), nullable=False)
	coursedetails = db.Column(db.String(300), nullable=False)

	def __init__(self, **kwargs):
		super(NewCourse, self).__init__(**kwargs)

	def to_json(self):
		
		return {
			'id': self.id,
			'coursetitle': self.coursetitle,
			'coursedetails': self.coursedetails,
			
		}
Ejemplo n.º 7
0
class Elimination(db.Model):
    __tablename__ = 'elimination'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    replay_id = db.Column(db.Integer,
                          db.ForeignKey('replay.id', ondelete='CASCADE'))

    eliminator = db.Column(db.String(255), nullable=False)
    eliminated = db.Column(db.String(255), nullable=False)
    knocked = db.Column(db.Boolean)
    weapon_type = db.Column(db.Integer, default=False, nullable=False)
    time = db.Column(db.DateTime, default=False, nullable=False)

    def __init__(self, replayId, **kwargs):
        super(Elimination, self).__init__(**kwargs)

    def __json__(self):
        return ['eliminator', 'eliminated', 'knocked', 'weapon_type', 'time']
Ejemplo n.º 8
0
class Parecer(db.Model):
    __tablename__ = 'parecer'

    id = db.Column(db.Integer, primary_key=True)
    fiscalCampo = db.Column(db.String(50))
    bilhete_id = db.Column(db.Integer, db.ForeignKey('bilhete.id'))

    def __init__(self, fiscalCampo=None, bilhete_id=None):
        self.fiscalCampo = fiscalCampo
        self.bilhete_id = bilhete_id
Ejemplo n.º 9
0
class ProfileImage(db.Model):
    __tablename__ = "profileimage"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    image_location = db.Column(db.String(128), nullable=False)
    border_radius = db.Column(db.String(100), nullable=False)
    status = db.Column(db.String(140), nullable=False)

    def __init__(self, **kwargs):
        super(ProfileImage, self).__init__(**kwargs)

    def to_json(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'image_location': self.image_location,
            'border_radius': self.border_radius,
            'status': self.status,
        }
Ejemplo n.º 10
0
class Accountdetails(db.Model):
    __tablename__ = "accountdetails"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    company = db.Column(db.String(128), nullable=False)
    job_title = db.Column(db.String(100), nullable=False)
    city = db.Column(db.String(100), nullable=False)
    country = db.Column(db.String(100), nullable=False)
    instituition = db.Column(db.String(100), nullable=False)
    about_me = db.Column(db.String(140), nullable=False)

    def __init__(self, **kwargs):
        super(Accountdetails, self).__init__(**kwargs)

    def to_json(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'company': self.company,
            'job_title': self.job_title,
            'city': self.city,
            'country': self.country,
            'instituition': self.instituition,
            'about_me': self.about_me
        }
Ejemplo n.º 11
0
class EventCategory(db.Model):
    __tablename__ = 'event_category'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False, unique=True, index=True)
    description = db.Column(db.String)
    default = db.Column(db.Boolean, default=False)
    parent_id = db.Column(db.Integer,
                          db.ForeignKey('event_category.id'),
                          nullable=True)
    children = db.relationship('EventCategory')

    def __repr__(self):
        return f'<Event category: {self.name}'
Ejemplo n.º 12
0
class Bilhete(db.Model):
    __tablename__ = 'bilhete'

    id = db.Column(db.Integer, primary_key=True)
    num_bilhete = db.Column(db.String(10))
    date_posted = db.Column(db.DateTime, nullable=False)
    parecer = db.relationship('Parecer',
                              uselist=False,
                              backref='bilhete',
                              lazy='dynamic')

    def __init__(self, num_bilhete=None, date_posted=None):
        self.num_bilhete = num_bilhete
        self.date_posted = datetime.datetime.now()
Ejemplo n.º 13
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    password_hash = db.Column(db.String(200), nullable=False)
    created_on = db.Column(db.DateTime, nullable=False, default=datetime.now)
    last_login = db.Column(db.DateTime)
    is_active = db.Column(db.Boolean, default=True)
    is_admin = db.Column(db.Boolean, default=False)
    email_verified = db.Column(db.Boolean, default=False)

    username = db.Column(db.String(30),
                         nullable=False,
                         unique=True,
                         index=True)
    email = db.Column(db.String(40), nullable=False, unique=True)
    first_name = db.Column(db.String(30))
    last_name = db.Column(db.String(30))

    country = db.Column(db.String(3))
    birthdate = db.Column(db.DateTime)

    def __repr__(self):
        return f'<User: {self.username}>'

    @property
    def password(self):
        raise AttributeError('password not readable')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password, method='sha256')

    def check_password(self, password) -> bool:
        return check_password_hash(self.password_hash, password)

    @property
    def full_name(self) -> str:
        return ' '.join(self.first_name, self.last_name)

    @classmethod
    def create_user(cls, **kwargs):
        user = cls(**kwargs)

        db.session.add(user)
        db.session.commit()

        return user
Ejemplo n.º 14
0
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    password_hash = db.Column(db.String)
    pomodoros = db.relationship('Pomodoro', backref='user', lazy='dynamic')

    @property
    def password(self, password):
        raise AttributeError('password: write-only field')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    @staticmethod
    def get_by_username(username):
        return User.query.filter_by(username=username).first()

    def __repr__(self):
        return "<User {}>".format(self.username)
Ejemplo n.º 15
0
class Pomodoro(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    length_seconds = db.Column(db.Integer, default=1500)  # Default 25 minutes
    end_time = db.Column(db.DateTime, default=datetime.utcnow)
    context = db.Column(db.String(80), default="")
    interruptions = db.Column(db.Integer)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    @staticmethod
    def create_new_pomodoro(context, interruptions, user_id):
        pomodoro = Pomodoro(context=context,
                            interruptions=interruptions,
                            user_id=user_id)
        db.session.add(pomodoro)
        db.session.commit()

    @staticmethod
    def past_n_days(n, user_id):
        now = datetime.utcnow()
        n_days_ago = now - timedelta(days=n)  # TODO: floor to midnight
        res = db.session.query(Pomodoro).filter(
            Pomodoro.user_id == user_id, Pomodoro.end_time > n_days_ago,
            Pomodoro.end_time <= now).all()
        return res
Ejemplo n.º 16
0
class ReplayStats(db.Model):
    __tablename__ = 'stats'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    created_at = db.Column(db.DateTime,
                           nullable=False,
                           server_default=func.now())

    replay_id = db.Column(db.Integer,
                          db.ForeignKey('replay.id', ondelete='CASCADE'))
    username = db.Column(db.String(255), nullable=False)

    eliminations = db.Column(db.Integer, default=False, nullable=False)
    accuracy = db.Column(db.Float, default=False, nullable=False)
    assists = db.Column(db.Integer, default=False, nullable=False)
    weapon_damage = db.Column(db.Integer, default=False, nullable=False)
    other_damage = db.Column(db.Integer, default=False, nullable=False)
    revives = db.Column(db.Integer, default=False, nullable=False)
    damage_taken = db.Column(db.Integer, default=False, nullable=False)
    damage_structures = db.Column(db.Integer, default=False, nullable=False)
    materials_gathered = db.Column(db.Integer, default=False, nullable=False)
    materials_used = db.Column(db.Integer, default=False, nullable=False)
    total_traveled = db.Column(db.Integer, default=False, nullable=False)
    position = db.Column(db.Integer, default=False, nullable=False)

    replay = db.relationship("Replay", backref="ReplayStats")

    @hybrid_property
    def died(self):
        return any(i for i in self.replay.elimination_events
                   if i.eliminated == self.username and not i.knocked)

    @hybrid_property
    def knocks(self):
        return len([
            i for i in self.replay.elimination_events
            if i.eliminator == self.username and i.knocked
        ])

    @hybrid_property
    def knocked(self):
        return len([
            i for i in self.replay.elimination_events
            if i.eliminated == self.username and i.knocked
        ])

    @hybrid_property
    def winner(self):
        return self.position == 1

    def __init__(self, replay_id, username, stats, team_stats):
        self.replay_id = replay_id
        self.username = username

        self.eliminations = stats['eliminations']
        self.accuracy = stats['accuracy']
        self.assists = stats['assists']
        self.weapon_damage = stats['weapon_damage']
        self.other_damage = stats['other_damage']
        self.revives = stats['revives']
        self.damage_taken = stats['damage_taken']
        self.damage_structures = stats['damage_structures']
        self.materials_gathered = stats['materials_gathered']
        self.materials_used = stats['materials_used']
        self.total_traveled = stats['total_traveled']

        self.position = team_stats['position']

    def __json__(self):
        return [
            'replay_id', 'username', 'eliminations', 'accuracy', 'assists',
            'weapon_damage', 'other_damage', 'revives', 'damage_taken',
            'damage_structures', 'materials_gathered', 'materials_used',
            'total_traveled', 'position', 'died', 'knocks', 'knocked', 'winner'
        ]
Ejemplo n.º 17
0
class Application(db.Model):
    __tablename__ = "applications"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    domain = db.Column(db.String(128), nullable=False)
    certificate = db.Column(db.String(128), nullable=False)
    contact_firstname = db.Column(db.String(128), nullable=True)
    contact_lastname = db.Column(db.String(128), nullable=True)
    contact_email = db.Column(db.String(128), nullable=True)
    contact_streetaddress = db.Column(db.String(128), nullable=True)
    contact_homecountry = db.Column(db.String(128), nullable=True)
    contact_phonenumber = db.Column(db.String(128), nullable=True)
    contact_company_name = db.Column(db.String(128), nullable=True)
    education_highest_degree = db.Column(db.String(128), nullable=True)
    education_year = db.Column(db.String(128), nullable=True)
    education_school = db.Column(db.String(128), nullable=True)
    education_city = db.Column(db.String(128), nullable=True)
    education_country = db.Column(db.String(128), nullable=True)
    general_main_language = db.Column(db.String(128), nullable=True)
    general_coding_years = db.Column(db.Integer(), nullable=True)
    general_coding_languages = db.Column(db.String(256), nullable=True)
    general_industry = db.Column(db.String(128), nullable=True)
    requirements_project_name_1 = db.Column(db.String(128), nullable=True)
    requirements_project_description_1 = db.Column(db.String(512),
                                                   nullable=True)
    requirements_project_start_date_1 = db.Column(db.String(128),
                                                  nullable=True)
    requirements_project_start_date_2 = db.Column(db.String(128),
                                                  nullable=True)
    requirements_responsible = db.Column(db.String(128), nullable=True)
    requirements_accountable = db.Column(db.String(128), nullable=True)
    requirements_consulted = db.Column(db.String(128), nullable=True)
    requirements_informed = db.Column(db.String(128), nullable=True)
    requirements_project_company_1 = db.Column(db.String(128), nullable=True)
    requirements_project_reference_name_1 = db.Column(db.String(128),
                                                      nullable=True)
    requirements_project_reference_email_1 = db.Column(db.String(128),
                                                       nullable=True)
    requirements_project_reference_phonenumber_1 = db.Column(db.String(128),
                                                             nullable=True)
    terms_agree = db.Column(db.String(128), nullable=True)
    status = db.Column(db.String(128), nullable=True)

    def __init__(self, **kwargs):
        super(Application, self).__init__(**kwargs)

    def to_json(self):
        return {
            'id': self.id,
            'domain': self.domain,
            'certificate': self.certificate,
            'contact_firstname': self.contact_firstname,
            'contact_lastname': self.contact_lastname,
            'contact_email': self.contact_email,
            'contact_streetaddress': self.contact_streetaddress,
            'contact_homecountry': self.contact_homecountry,
            'contact_phonenumber': self.contact_phonenumber,
            'contact_company_name': self.contact_company_name,
            "education_highest_degree": '',
            "education_year": self.education_year,
            "education_school": self.education_school,
            "education_city": self.education_city,
            "education_country": self.education_country,
            "general_main_language": self.general_main_language,
            "general_coding_years": self.general_coding_years,
            "general_coding_languages": self.general_coding_languages,
            "general_industry": self.general_industry,
            "requirements_project_name_1": self.requirements_project_name_1,
            "requirements_project_description_1":
            self.requirements_project_description_1,
            "requirements_project_start_date_1":
            self.requirements_project_start_date_1,
            "requirements_project_start_date_2":
            self.requirements_project_start_date_2,
            "requirements_responsible": self.requirements_responsible,
            "requirements_accountable": self.requirements_accountable,
            "requirements_consulted": self.requirements_consulted,
            "requirements_informed": self.requirements_informed,
            "requirements_project_company_1":
            self.requirements_project_company_1,
            "requirements_project_reference_name_1":
            self.requirements_project_reference_name_1,
            "requirements_project_reference_email_1":
            self.requirements_project_reference_email_1,
            "requirements_project_reference_phonenumber_1":
            self.requirements_project_reference_phonenumber_1,
            "terms_agree": self.terms_agree,
            "status": self.status
        }
Ejemplo n.º 18
0
class users(db.Model):
    """This class represents the users table."""
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    first_name = db.Column(db.String(200))
    last_name = db.Column(db.String(200))
    address = db.Column(db.String(200))
    username = db.Column(db.String(200))
    encrypted_password = db.Column(db.String(200))
    temp_password = db.Column(db.String(200))
    isreset_password = db.Column(db.Boolean, default=True)
    mobile = db.Column(db.String(200))
    ismobile_verified = db.Column(db.Boolean, default=True)
    email = db.Column(db.Integer)
    isemail_verified = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.TIMESTAMP)
    created_by = db.Column(db.String(200))
    updated_at = db.Column(db.TIMESTAMP)
    updated_by = db.Column(db.String(200))
    is_active = db.Column(db.Boolean, default=True)
    is_deleted = db.Column(db.Boolean, default=False)

    def __init__(self,
                 id=None,
                 first_name="",
                 last_name="",
                 address="",
                 username="",
                 encrypted_password="",
                 temp_password="",
                 mobile="",
                 email="",
                 isemail_verified="",
                 ismobile_verified="",
                 created_by=""):
        """initialize with id."""
        self.id = id
        self.first_name = first_name
        self.last_name = last_name
        self.address = address
        self.username = username
        self.encrypted_password = encrypted_password
        self.temp_password = temp_password
        self.mobile = mobile
        self.email = email
        self.created_at = datetime.now()
        self.created_by = created_by

    @classmethod
    def get(cls, id: int):
        """ Get a users for a given id.
        :param id: the id of the name to retrieve
        :return: the users
        """
        return users.query.get(id)

    @classmethod
    def all(cls, search_data=None):
        """ Get all available users.
        :return: list with all users
        """

        if search_data != None:
            return cls.query.filter_by(
                is_active=True, is_deleted=False).filter(
                    cls.first_name.ilike('%' + search_data + '%')
                    | cls.last_name.ilike('%' + search_data + '%')
                    | cls.address.ilike('%' + search_data + '%')
                    | cls.username.ilike('%' + search_data + '%')
                    | cls.email.ilike('%' + search_data + '%')).order_by(
                        cls.created_at.desc())
        else:
            return cls.query.filter_by(is_active=True,
                                       is_deleted=False).order_by(
                                           cls.created_at.desc())

    def to_json(self):
        """ Convert a name object to JSON
        :return: the name JSON representation
        """
        return json.loads(
            json.dumps(
                {
                    "id": self.id,
                    "first_name": self.first_name,
                    "last_name": self.last_name,
                    "address": self.address,
                    "username": self.username,
                    "mobile": self.mobile,
                    "email": self.email,
                    "created_by": self.created_by,
                    "created_at": self.created_at,
                    "updated_by": self.updated_by,
                    "updated_at": self.updated_at,
                    "is_active": self.is_active
                },
                default=default_proc))

    def save(self):
        db.session.add(self)
        db.session.commit()

    def update(self):
        db.session.commit()

    def exists(self, id):
        return db.session.query(db.exists().where(id == id)).scalar()

    def get_user(self, username):
        query = 'SELECT * FROM users WHERE username ilike :username'.format(
            table_name=self.__tablename__)
        params = {"username": username}
        with db.engine.connect() as con:
            result = con.execute(text(query), **params)
        return result.first()

    def get_email(self, email):
        query = 'SELECT * FROM users WHERE email ilike :email'.format(
            table_name=self.__tablename__)
        params = {"email": email}
        with db.engine.connect() as con:
            result = con.execute(text(query), **params)
        return result.first()

    def delete(self):
        if self.is_deleted:
            return Response.createFailResponse(self,
                                               ResponseMessages.not_exist,
                                               HTTPStatus.NO_CONTENT)
        self.is_deleted = True
        db.session.commit()

    def __repr__(self):
        return "<username: {}>".format(self.username)
Ejemplo n.º 19
0
class TenantSubscription(db.Model):
    __tablename__ = 'tenant_subscription'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    effective_from = db.Column(db.DateTime)
    effective_to = db.Column(db.DateTime)
    auto_renew = db.Column(db.Boolean, default=True)
    status = db.Column(db.Enum("Active", "Inactive", "Suspended"),
                       default='Active')
    created_at = db.Column(db.DateTime)
    created_by = db.Column(db.String(50))
    updated_at = db.Column(db.DateTime)
    updated_by = db.Column(db.String(50))
    is_active = db.Column(db.Boolean, default=True)
    is_deleted = db.Column(db.Boolean, default=False)
    tenant_id = db.Column(db.Integer, ForeignKey('tenant.id'))
    tenant = relationship("Tenant", backref="tenant_subscription")
    membership_plan_id = db.Column(db.Integer,
                                   ForeignKey('membership_plan.id'))
    membershipPlan = relationship("MembershipPlan",
                                  backref="tenant_subscription")

    def __init__(self,
                 id=None,
                 effective_from="",
                 effective_to="",
                 status="",
                 tenant_id=None,
                 membership_plan_id=None,
                 created_by="",
                 created_at="",
                 is_active="",
                 is_deleted=""):

        self.id = id
        self.effective_from = effective_from
        self.effective_to = date.today()
        self.status = status
        self.tenant_id = tenant_id
        self.membership_plan_id = membership_plan_id
        self.created_at = created_at
        self.created_by = created_by

    @classmethod
    def get(cls, id: int):
        return TenantSubscription.query.get(id)

    @classmethod
    def all(cls):
        return cls.query.filter_by(is_active=True,
                                   is_deleted=False).order_by(cls.created_at)

    def to_json(self):
        return json.loads(
            json.dumps(
                {
                    "id": self.id,
                    "effective_from": self.effective_from,
                    "effective_to": self.effective_to,
                    "auto_renew": self.auto_renew,
                    "status": self.status,
                    "tenant_id": self.tenant_id,
                    "membership_plan_id": self.membership_plan_id,
                    "created_by": self.created_by,
                    "created_at": self.created_at,
                    "updated_at": self.updated_at,
                    "updated_by": self.updated_by,
                    "is_active": self.is_active
                },
                default=default_proc))

    def save(self):
        db.session.add(self)
        db.session.commit()

    def update(self):
        db.session.commit()

    def exists(self, id):
        return db.session.query(db.exists().where(id == id)).scalar()

    def delete(self):
        if self.is_deleted:
            return Response.createFailResponse(self,
                                               ResponseMessages.not_found,
                                               HTTPStatus.NO_CONTENT)
        self.is_deleted = True
        db.session.commit()

    def __repr__(self):
        return "<name: {}>".format(self.name)