class Vat_return(SurrogatePK, Model, TimestampMixin): __tablename__ = 'vat_returns' organisation_id = reference_col('organisations', nullable=False) period_key = Column(db.String(4)) vat_due_sales = Column(db.String(10)) vat_due_acquisitions = Column(db.String(10)) total_vat_due = Column(db.String(10)) vat_reclaimed_curr_period = Column(db.String(10)) net_vat_due = Column(db.String(10)) total_value_sales_ex_vat = Column(db.String(10)) total_value_purchases_ex_vat = Column(db.String(10)) total_value_goods_supplied_ex_vat = Column(db.String(10)) total_acquisitions_ex_vat = Column(db.String(10)) finalised = Column(db.Boolean(), default=True) is_submitted = Column(db.Boolean(), default=False) submitted_on = Column(db.DateTime, nullable = True) submitted_by = Column(db.String(50), nullable=True) def __init__(self, organisation_id, period_key, **kwargs): db.Model.__init__(self, organisation_id=organisation_id, period_key=period_key, **kwargs) def is_submitted(self): """Active or non active user (required by flask-login)""" return self.is_submitted
class Comment(Model, SurrogatePK): __tablename__ = 'comment' id = db.Column(db.Integer, primary_key=True) body = Column(db.Text) createdAt = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) updatedAt = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) author_id = reference_col('userprofile', nullable=False) author = relationship('UserProfile', backref=db.backref('comments')) article_id = reference_col('article', nullable=False) def __init__(self, article, author, body, **kwargs): db.Model.__init__(self, author=author, body=body, article=article, **kwargs)
class UserProfile(Model, SurrogatePK): __tablename__ = 'userprofile' # id is needed for primary join, it does work with SurrogatePK class id = db.Column(db.Integer, primary_key=True) user_id = reference_col('users', nullable=False) user = relationship('User', backref=db.backref('profile', uselist=False)) follows = relationship('UserProfile', secondary=followers_assoc, primaryjoin=id == followers_assoc.c.follower, secondaryjoin=id == followers_assoc.c.followed_by, backref='followed_by', lazy='dynamic') def __init__(self, user, **kwargs): db.Model.__init__(self, user=user, **kwargs) def is_following(self, profile): return bool(self.follows.filter(followers_assoc.c.followed_by == profile.id).count()) def follow(self, profile): if self is not profile and not self.is_following(profile): self.follows.append(profile) return True return False def unfollow(self, profile): if self is not profile and self.is_following(profile): self.follows.remove(profile) return True return False @property def following(self): if current_user: return current_user.profile.is_following(self) return False @property def username(self): return self.user.username @property def bio(self): return self.user.bio @property def image(self): return self.user.image @property def email(self): return self.user.email
class Vat_receipt(SurrogatePK, Model): __tablename__ = 'vat_receipts' organisation_id = reference_col('organisations', nullable=False) period_key = Column(db.String(4)) processing_date = Column(db.DateTime, nullable = True) payment_indicator = Column(db.String(10)) form_bundle_number = Column(db.String(12)) charge_ref_number = Column(db.String(12)) def __init__(self, organisation_id, period_key, processing_date, **kwargs): db.Model.__init__(self, organisation_id=organisation_id, period_key=period_key, processing_date=processing_date, **kwargs)
class OptionsContractData(DefaultBase): options_contract_id = reference_col("options_contract") date = Column(db.DateTime, nullable=False) bar_size = Column(db.Enum(BarSizes), default=BarSizes.MIN_1, nullable=False) data_type = Column(db.Enum(HistoricalDataType), nullable=False) open = Column(db.Float, nullable=False) high = Column(db.Float, nullable=False) low = Column(db.Float, nullable=False) close = Column(db.Float, nullable=False) volume = Column(db.Float, nullable=False) bar_count = Column(db.Float, nullable=False) average = Column(db.Float, nullable=False)
class EquityHistoricalData(DefaultBase): equity_id = reference_col("equity") date = Column(db.DateTime, nullable=False) bar_size = Column(db.Enum(BarSizes), default=BarSizes.MIN_1, nullable=False) data_type = Column(db.Enum(HistoricalDataType), nullable=False) open = Column(db.Float, nullable=False) high = Column(db.Float, nullable=False) low = Column(db.Float, nullable=False) close = Column(db.Float, nullable=False) volume = Column(db.Float, nullable=False) bar_count = Column(db.Float, nullable=False) average = Column(db.Float, nullable=False)
class Role(SurrogatePK, Model): """A role for a user.""" __tablename__ = 'roles' name = Column(db.String(80), unique=True, nullable=False) user_id = reference_col('users', nullable=True) user = relationship('User', backref='roles') def __init__(self, name, **kwargs): """Create instance.""" db.Model.__init__(self, name=name, **kwargs) def __repr__(self): """Represent instance as a unique string.""" return '<Role({name})>'.format(name=self.name)
class Role(SurrogatePK, Model): """A role for a user.""" __tablename__ = "roles" name = Column(db.String(80), unique=True, nullable=False) user_id = reference_col("users", nullable=True) user = relationship("User", backref="roles") def __init__(self, name, **kwargs): """Create instance.""" db.Model.__init__(self, name=name, **kwargs) def __repr__(self): """Represent instance as a unique string.""" return f"<Role({self.name})>"
class OptionsContract(DefaultBase): equity_id = reference_col("equity") strike = Column(db.Float, nullable=False) exp = Column(db.Date, nullable=False) type = Column(db.Enum(OptionType), nullable=False)
class Article(SurrogatePK, Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True) slug = Column(db.Text, unique=True) title = Column(db.String(100), nullable=False) description = Column(db.Text, nullable=False) body = Column(db.Text) createdAt = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) updatedAt = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) author_id = reference_col('userprofile', nullable=False) author = relationship('UserProfile', backref=db.backref('articles')) favoriters = relationship('UserProfile', secondary=favoriter_assoc, backref='favorites', lazy='dynamic') tagList = relationship('Tags', secondary=tag_assoc, backref='articles') comments = relationship('Comment', backref=db.backref('article'), lazy='dynamic') def __init__(self, author, title, body, description, slug=None, **kwargs): db.Model.__init__(self, author=author, title=title, description=description, body=body, slug=slug or slugify(title), **kwargs) def favourite(self, profile): if not self.is_favourite(profile): self.favoriters.append(profile) return True return False def unfavourite(self, profile): if self.is_favourite(profile): self.favoriters.remove(profile) return True return False def is_favourite(self, profile): return bool( self.query.filter( favoriter_assoc.c.favoriter == profile.id).count()) def add_tag(self, tag): if tag not in self.tagList: self.tagList.append(tag) return True return False def remove_tag(self, tag): if tag in self.tagList: self.tagList.remove(tag) return True return False @property def favoritesCount(self): return len(self.favoriters.all()) @property def favorited(self): if current_user: profile = current_user.profile return self.query.join(Article.favoriters).filter( UserProfile.id == profile.id).count() == 1 return False
class User(UserMixin, SurrogatePK, Model): """A user of the app.""" __tablename__ = 'users' uuid = Column(db.String(36), unique=True, nullable=False) username = Column(db.String(80), unique=True, nullable=False) email = Column(db.String(80), unique=False, nullable=False) organisation_id = reference_col('organisations', nullable=True,) #role_id = reference_col('roles', nullable=True,) #: The hashed password password_hash = Column(db.String(128), nullable=True) token = Column(db.String(32), index=True, unique=True, nullable=True) token_expiration = Column(db.DateTime, nullable=True) created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) first_name = Column(db.String(30), nullable=True) last_name = Column(db.String(30), nullable=True) active = Column(db.Boolean(), default=True, nullable=True) is_admin = Column(db.Boolean(), default=False, nullable=True) def __init__(self, username, email, active, password=None, **kwargs): """Create instance.""" db.Model.__init__(self, username=username, email=email, active=active, **kwargs) self.uuid = str(uuid.uuid4()) self.username = username self.email = email self.active = active if password: self.set_password(password) else: self.password_hash = None def has_admin(self): """Admin or non admin user (required by flask-login)""" return self.is_admin def is_active(self): """Active or non active user (required by flask-login)""" return self.active def set_password(self, password): """Set password.""" self.password_hash = generate_password_hash(password) def check_password(self, value): """Check password.""" return check_password_hash(self.password_hash, value) def get_reset_password_token(self, expires_in=600): return jwt.encode( {'reset_password': self.id, 'exp': time() + expires_in}, current_app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8') def get_token(self, expires_in=3600): now = datetime.utcnow() if self.token and self.token_expiration > now + timedelta(seconds=60): return self.token self.token = base64.b64encode(os.urandom(24)).decode('utf-8') self.token_expiration = now + timedelta(seconds=expires_in) db.session.add(self) return self.token def revoke_token(self): self.token_expiration = datetime.utcnow() - timedelta(seconds=1) @staticmethod def verify_reset_password_token(token): try: id = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])['reset_password'] except: return return User.query.get(id) @staticmethod def check_token(token): user = User.query.filter_by(token=token).first() if user is None or user.token_expiration < datetime.utcnow(): return None return user @property def full_name(self): """Full user name.""" return '{0} {1}'.format(self.first_name, self.last_name) def __repr__(self): """Represent instance as a unique string.""" return '<User({username!r})>'.format(username=self.username)