class AccountSettingsModel(db.Model):
    __tablename__ = 'account_settings'

    id = db.Column(db.Integer, primary_key=True)
    time_created = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    time_updated = db.Column(db.DateTime(), onupdate=datetime.datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    auto_load_parking_place_gps_location = db.Column(db.Boolean, default=False)
    parking_place_required = db.Column(db.Boolean, default=False)

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

    @staticmethod
    def get_marshaller():
        return {
            'id': fields.Integer,
            'time_created': fields.DateTime,
            'time_updated': fields.DateTime,
            'auto_load_parking_place_gps_location': fields.Boolean,
            'parking_place_required': fields.Boolean
        }

    @classmethod
    def find_by_user_id(cls, user_id):
        return cls.query.filter_by(user_id=user_id).first()
Example #2
0
class EventModel(db.Model):
    __tablename__ = 'events'

    id = db.Column(db.Integer, primary_key=True)
    time_created = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    time_updated = db.Column(db.DateTime(), onupdate=datetime.datetime.utcnow)
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    owner = db.relationship('UserModel', foreign_keys=[owner_id])
    community_id = db.Column(db.Integer,
                             db.ForeignKey('communities.id'),
                             nullable=False)
    community = db.relationship('CommunityModel', foreign_keys=[community_id])
    title = db.Column(db.String(120), nullable=False)
    description = db.Column(db.Text, nullable=True)
    start = db.Column(db.DateTime())
    end = db.Column(db.DateTime())

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

    @staticmethod
    def get_marshaller():
        return {
            'id': fields.Integer,
            'time_created': fields.DateTime,
            'time_updated': fields.DateTime,
            'owner': fields.Nested(UserModel.get_marshaller()),
            'title': fields.String,
            'description': fields.String,
            'start': fields.DateTime,
            'end': fields.DateTime,
        }

    @classmethod
    def delete_by_id(cls, event_id):
        event = db.session.query(cls).filter(cls.id == event_id).first()
        if event:
            db.session.delete(event)
            db.session.commit()
        else:
            raise NoData

    @classmethod
    def find_by_id(cls, id):
        return cls.query.filter_by(id=id).first()

    @classmethod
    def find_by_community(cls, community_id, from_datetime, to_datetime):
        return cls.query.filter_by(community_id=community_id). \
            filter(EventModel.end >= from_datetime, EventModel.start <= to_datetime).all()

    @classmethod
    def find_next_n_by_community(cls, community_id, n):
        return cls.query.filter_by(community_id=community_id). \
            filter(EventModel.end >= datetime.datetime.utcnow()).order_by(EventModel.start.asc()).limit(n).all()
Example #3
0
class CarModel(db.Model):
    __tablename__ = 'cars'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), nullable=False)
    make = db.Column(db.String(120), nullable=False)
    model = db.Column(db.String(120), nullable=False)
    time_created = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    time_updated = db.Column(db.DateTime(), onupdate=datetime.datetime.utcnow)
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    owner = db.relationship('UserModel', back_populates='cars')

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

    @staticmethod
    def get_marshaller():
        return {
            'id': fields.Integer,
            'name': fields.String,
            'make': fields.String,
            'model': fields.String,
            'time_created': fields.DateTime,
            'time_updated': fields.DateTime,
            'owner': fields.Nested(UserModel.get_marshaller())
        }

    @classmethod
    def find_by_id(cls, id):
        return cls.query.filter_by(id=id).first()

    @classmethod
    def return_all(cls):
        return CarModel.query.all()

    @classmethod
    def return_all_for_user(cls, user_id):
        return CarModel.query.filter(cls.owner_id == user_id).all()

    @classmethod
    def delete_all(cls):
        db.session.query(cls).delete()
        db.session.commit()

    @classmethod
    def delete_by_id(cls, id):
        car = db.session.query(cls).filter(cls.id == id).first()
        if car:
            db.session.delete(car)
            db.session.commit()
        else:
            raise NoData
Example #4
0
class Creator(db.Model):
    __tablename__ = 'creator'
    id = db.Column(db.Integer(), primary_key=True)
    firstName = db.Column(db.String(100))
    middleName = db.Column(db.String(100))
    lastName = db.Column(db.String(100))
    suffix = db.Column(db.String(100))
    fullName = db.Column(db.String(100))
    modified = db.Column(db.DateTime())
    comics = db.relationship(Comics,
                             secondary=creator_comics,
                             backref=db.backref('creators', lazy=True))

    def __init__(self, id, firstName, middleName, lastName, suffix, fullName,
                 modified, comics):
        self.id = id
        self.firstName = firstName
        self.middleName = middleName
        self.lastName = lastName
        self.suffix = suffix
        self.fullName = fullName
        self.modified = modified
        self.comics = comics

    def create(self):
        db.session.add(self)
        db.session.commit()
        return self
class TourPassengerLinkModel(db.Model):
    __tablename__ = 'tour_passenger_link'

    tour_id = db.Column(db.Integer,
                        db.ForeignKey('tours.id'),
                        primary_key=True)
    user_id = db.Column(db.Integer,
                        db.ForeignKey('users.id'),
                        primary_key=True)
    tour = db.relationship('TourModel')
    user = db.relationship('UserModel')
    time_created = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    time_updated = db.Column(db.DateTime(), onupdate=datetime.datetime.utcnow)

    def persist(self):
        db.session.add(self)
        db.session.commit()
Example #6
0
class User(UserMixin, db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    role_id = db.Column(db.Integer, db.ForeignKey("roles.id"))
    password_hash = db.Column(db.String(128))
    confirmed = db.Column(db.Boolean, default=False)
    name = db.Column(db.String(64))
    location = db.Column(db.String(64))
    about_me = db.Column(db.Text())
    housemates = db.Column(db.Text())
    significant_others = db.Column(db.Text())
    my_five = db.Column(db.Text())
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
    avatar_hash = db.Column(db.String(32))
    posts = db.relationship("Post", backref="author", lazy="dynamic")
    followed = db.relationship(
        "Follow",
        foreign_keys=[Follow.follower_id],
        backref=db.backref(name="follower", lazy="joined"),
        lazy="dynamic",
        cascade="all, delete-orphan",
    )
    followers = db.relationship(
        "Follow",
        foreign_keys=[Follow.followed_id],
        backref=db.backref(name="followed", lazy="joined"),
        lazy="dynamic",
        cascade="all, delete-orphan",
    )

    @staticmethod
    def add_self_follows():
        # this is used as a script to go back and add self follows if they are missing
        for user in User.query.all():
            if not user.is_following(user):
                user.follow(user)
                db.session.add(user)
                db.session.commit()

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        if not self.role:
            if self.email == current_app.config["MYQ5_ADMIN"]:
                self.role = Role.query.filter_by(name="Administrator").first()
            if not self.role:
                self.role = Role.query.filter_by(default=True).first()
        if not self.email and not self.avatar_hash:
            self.avatar_hash = self.gravatar_hash()
        self.follow(self)

    @property
    def followed_posts(self):
        return Post.query.join(Follow,
                               Follow.followed_id == Post.author_id).filter(
                                   Follow.follower_id == self.id)

    @property
    def followed_users(self):
        return User.query.join(Follow, Follow.followed_id == User.id).filter(
            Follow.follower_id == self.id)

    @property
    def password(self):
        raise AttributeError("password is not a readable attribute")

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

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

    def generate_confirmation_token(self, expiration=3600):
        s = Serializer(current_app.config["SECRET_KEY"], expiration)
        return s.dumps({"confirm": self.id}).decode("utf-8")

    def confirm(self, token):
        s = Serializer(current_app.config["SECRET_KEY"])
        try:
            data = s.loads(token.encode("utf-8"))
        except Exception:
            return False
        if data.get("confirm") != self.id:
            return False
        self.confirmed = True
        db.session.add(self)
        return True

    def generate_reset_token(self, expiration=3600):
        s = Serializer(current_app.config["SECRET_KEY"], expiration)
        return s.dumps({"reset": self.id}).decode("utf-8")

    @staticmethod
    def reset_password(token, new_password):
        s = Serializer(current_app.config["SECRET_KEY"])
        try:
            data = s.loads(token.encode("utf-8"))
        except:
            return False
        user = User.query.get(data.get("reset"))
        if user is None:
            return False
        user.password = new_password
        db.session.add(user)
        return True

    def generate_email_change_token(self, new_email, expiration=3600):
        s = Serializer(current_app.config["SECRET_KEY"], expiration)
        return s.dumps({
            "change_email": self.id,
            "new_email": new_email
        }).decode("utf-8")

    def change_email(self, token):
        s = Serializer(current_app.config["SECRET_KEY"])
        try:
            data = s.loads(token.encode("utf-8"))
        except:
            return False
        if data.get("change_email") != self.id:
            return False
        new_email = data.get("new_email")
        self.avatar_hash = self.gravatar_hash()
        if new_email is None:
            return False
        if self.query.filter_by(email=new_email).first() is not None:
            return False
        self.email = new_email
        db.session.add(self)
        return True

    def can(self, perm):
        return self.role is not None and self.role.has_permission(perm)

    def is_administrator(self):
        return self.can(Permission.ADMIN)

    def ping(self):
        self.last_seen = datetime.utcnow()
        db.session.add(self)

    def gravatar_hash(self):
        return hashlib.md5(self.email.lower().encode("utf-8")).hexdigest()

    def gravatar(self, size=100, default="identicon", rating="g"):
        url = "https://secure.gravatar.com/avatar"
        gravatar_hash = self.avatar_hash or self.gravatar_hash()
        return f"{url}/{gravatar_hash}?s={size}&d={default}&r={rating}"

    def follow(self, user):
        if not self.is_following(user):
            f = Follow(follower=self, followed=user)
            db.session.add(f)

    def unfollow(self, user):
        f = self.followed.filter_by(followed_id=user.id).first()
        if f:
            db.session.delete(f)

    def is_following(self, user):
        if user.id is None:
            return False
        return self.followed.filter_by(followed_id=user.id).first() is not None

    def is_followed_by(self, user):
        if user.id is None:
            return False
        return self.followers.filter_by(
            follower_id=user.id).first() is not None

    def __repr__(self):
        return f"<User {self.username}>"
Example #7
0
class DebtModel(db.Model):
    __tablename__ = 'debts'

    id = db.Column(db.Integer, primary_key=True)
    is_settled = db.Column(db.Boolean, default=False)
    amount = db.Column(db.DECIMAL(10, 2), nullable=False)
    time_created = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    time_updated = db.Column(db.DateTime(), onupdate=datetime.datetime.utcnow)
    debtee_id = db.Column(db.Integer,
                          db.ForeignKey('users.id'),
                          nullable=False)
    debtee = db.relationship('UserModel', foreign_keys=[debtee_id])
    recepient_id = db.Column(db.Integer,
                             db.ForeignKey('users.id'),
                             nullable=False)
    recepient = db.relationship('UserModel', foreign_keys=[recepient_id])
    payoff_id = db.Column(db.Integer,
                          db.ForeignKey('payoffs.id'),
                          nullable=False)
    community_id = db.Column(db.Integer,
                             db.ForeignKey('communities.id'),
                             nullable=False)

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

    @staticmethod
    def get_marshaller():
        return {
            'id': fields.Integer,
            'time_created': fields.DateTime,
            'time_updated': fields.DateTime,
            'debtee': fields.Nested(UserModel.get_marshaller()),
            'recepient': fields.Nested(UserModel.get_marshaller()),
            'is_settled': fields.Boolean,
            'amount': fields.Float
        }

    @classmethod
    def find_by_id(cls, id):
        return cls.query.filter_by(id=id).first()

    @classmethod
    def find_by_community(cls, community_id):
        return cls.query.filter_by(community_id=community_id).all()

    @classmethod
    def find_unsettled_by_community(cls, community_id):
        return cls.query.filter_by(community_id=community_id,
                                   is_settled=False).all()

    @classmethod
    def find_unsettled_by_user(cls, user_id):
        return cls.query.filter(((DebtModel.recepient_id == user_id) |
                                 (DebtModel.debtee_id == user_id)),
                                DebtModel.is_settled == False).all()

    @classmethod
    def find_unsettled_by_payoff(cls, payoff_id):
        return cls.query.filter_by(payoff_id=payoff_id, is_settled=False).all()
Example #8
0
class CommunityModel(db.Model):
    __tablename__ = 'communities'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(120), nullable=False)
    time_created = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    time_updated = db.Column(db.DateTime(), onupdate=datetime.datetime.utcnow)
    users = db.relationship(
        'UserModel',
        secondary='community_user_link',
        secondaryjoin='and_(CommunityUserLinkModel.user_id == UserModel.id, '
        'CommunityUserLinkModel.invitation_accepted == True)')
    car_id = db.Column(db.Integer, db.ForeignKey('cars.id'), unique=True)
    car = db.relationship("CarModel",
                          backref=db.backref("community", uselist=False))
    is_favourite = None

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

    @staticmethod
    def get_marshaller():
        return {
            'id': fields.Integer,
            'name': fields.String,
            'time_created': fields.DateTime,
            'time_updated': fields.DateTime,
            'users': fields.List(fields.Nested(UserModel.get_marshaller())),
            'car': fields.Nested(CarModel.get_marshaller())
        }

    @staticmethod
    def get_detailed_marshaller():
        return {
            'id': fields.Integer,
            'name': fields.String,
            'time_created': fields.DateTime,
            'time_updated': fields.DateTime,
            'users': fields.List(fields.Nested(UserModel.get_marshaller())),
            'car': fields.Nested(CarModel.get_marshaller()),
            'is_deletable': fields.Boolean,
            'is_editable': fields.Boolean
        }

    @staticmethod
    def add_is_fav_to_marshaller(marshaller):
        marshaller['is_favourite'] = fields.Boolean
        return marshaller

    @classmethod
    def find_by_car_id(cls, id):
        return cls.query.filter_by(car_id=id).first()

    @classmethod
    def find_by_id(cls, id):
        return cls.query.filter_by(id=id).first()

    @classmethod
    def return_all(cls):
        return CommunityModel.query.all()

    @classmethod
    def delete_all(cls):
        db.session.query(cls).delete()
        db.session.commit()

    @classmethod
    def delete_by_id(cls, id):
        community = db.session.query(cls).filter(cls.id == id).first()
        if community:
            db.session.delete(community)
            db.session.commit()
        else:
            raise NoData
Example #9
0
class CommunityUserLinkModel(db.Model):
    __tablename__ = 'community_user_link'

    community_id = db.Column(db.Integer,
                             db.ForeignKey('communities.id'),
                             primary_key=True)
    user_id = db.Column(db.Integer,
                        db.ForeignKey('users.id'),
                        primary_key=True)
    is_owner = db.Column(db.Boolean, default=True)
    invitation_accepted = db.Column(db.Boolean, default=True)
    community = db.relationship('CommunityModel')
    user = db.relationship('UserModel')
    is_favourite = db.Column(db.Boolean, default=False, nullable=False)
    time_created = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    time_updated = db.Column(db.DateTime(), onupdate=datetime.datetime.utcnow)

    def add_to_session(self):
        db.session.add(self)

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

    @staticmethod
    def get_marshaller():
        return {
            'community': fields.Nested(CommunityModel.get_marshaller()),
            'time_created': fields.DateTime,
            'time_updated': fields.DateTime,
        }

    @classmethod
    def find_by_user_and_community(cls, user_id, community_id):
        return cls.query.filter_by(user_id=user_id,
                                   community_id=community_id).first()

    @classmethod
    def find_favourite_by_user(cls, user_id):
        return cls.query.filter_by(user_id=user_id, is_favourite=True).first()

    @classmethod
    def find_by_user(cls, user_id):
        return cls.query.filter_by(user_id=user_id).all()

    @classmethod
    def find_by_community(cls, community_id):
        return cls.query.filter_by(community_id=community_id).all()

    @classmethod
    def find_open_invitations_by_user(cls, user_id):
        return cls.query.filter_by(user_id=user_id,
                                   invitation_accepted=False).all()

    @classmethod
    def find_open_invitations_by_community(cls, community_id):
        return cls.query.filter_by(community_id=community_id,
                                   invitation_accepted=False).all()

    def delete(self):
        db.session.delete(self)
        db.session.commit()
Example #10
0
class FeedModel(db.Model, BaseModel):
    """Feed Model"""

    __tablename__ = 'feed'

    # Define crypto symbols
    CRYPTO_SYMBOLS = (CryptoSymbols.ALQO, )

    # Define crypto symbols enum for symbol field
    CRYPTO_SYMBOLS_ENUM = ENUM(*CRYPTO_SYMBOLS, name="symbol")

    id = db.Column(db.Integer, primary_key=True)
    symbol = db.Column(CRYPTO_SYMBOLS_ENUM, index=True, nullable=False)
    data = db.Column(db.JSON())
    totals = db.Column(db.JSON())
    date_added = db.Column(db.DateTime(),
                           default=datetime.datetime.utcnow,
                           index=True)

    # Define our table index
    Index("symbol_date_added_index", symbol, date_added)

    @staticmethod
    def get_custom_date_data(
        crypto_symbol,
        start_date,
        end_date,
    ):
        """ Get custom date data

        :param crypto_symbol:
        :param start_date:
        :param end_date:
        :return feed models:
        """

        # Set date format
        date_format = "%Y-%m-%d"

        # Parse dates
        start_date = datetime.datetime.strptime(start_date, date_format)
        end_date = datetime.datetime.strptime(end_date, date_format)

        # Get start_date and end_date difference in days
        delta = end_date - start_date

        # If 30 days or under the process by day
        if int(delta.days) <= 30:

            # Create subquery
            subquery = db.session.query(SA_FUNC.max(
                FeedModel.date_added)).filter(
                    FeedModel.symbol == crypto_symbol,
                    FeedModel.date_added >= start_date,
                    FeedModel.date_added <= end_date).group_by(
                        SA_FUNC.date_part('day',
                                          FeedModel.date_added)).subquery()

        # If a year or under, then process by month
        elif int(delta.days) < 365:

            # Create subquery
            subquery = db.session.query(SA_FUNC.max(
                FeedModel.date_added)).filter(
                    FeedModel.symbol == crypto_symbol,
                    FeedModel.date_added >= start_date,
                    FeedModel.date_added <= end_date).group_by(
                        SA_FUNC.date_part('month',
                                          FeedModel.date_added)).subquery()

        # If a year or over, then process by year
        elif int(delta.days) >= 365:

            # Create subquery
            subquery = db.session.query(SA_FUNC.max(
                FeedModel.date_added)).filter(
                    FeedModel.symbol == crypto_symbol,
                    FeedModel.date_added >= start_date,
                    FeedModel.date_added <= end_date).group_by(
                        SA_FUNC.date_part('year',
                                          FeedModel.date_added)).subquery()

        # Process query
        feed_models = db.session.query(FeedModel).filter(
            FeedModel.date_added.in_(subquery)).order_by(FeedModel.date_added)

        return feed_models

    @staticmethod
    def get_all_data(crypto_symbol):
        """Get all data limited to 100 rows by default

        :param crypto_symbol:
        :return feed models:
        """

        # Search for earliest date
        feed_model = db.session.query(
            SA_CAST(SA_FUNC.min(FeedModel.date_added),
                    SA_TYPES.Date).label("date_added")).filter(
                        FeedModel.symbol == crypto_symbol).first()

        # Set start date with earliest
        date_start = feed_model.date_added

        # Build subquery
        subquery = db.session.query(SA_FUNC.max(FeedModel.date_added)).filter(
            FeedModel.symbol == crypto_symbol,
            FeedModel.date_added >= date_start).group_by(
                SA_CAST(FeedModel.date_added, SA_TYPES.Date)).subquery()

        # Process query
        feed_models = db.session.query(FeedModel).filter(
            FeedModel.date_added.in_(subquery)).order_by(
                FeedModel.date_added).limit(100)

        # Return models
        return feed_models

    @staticmethod
    def get_last_year_data(crypto_symbol):
        """Get last year data

        :param crypto_symbol:
        :return feed models:
        """

        date_today = datetime.date.today()

        # Set date 1 year ago from date_today
        date_1_year_ago = date_today - datetime.timedelta(year=1)

        # Build subquery
        subquery = db.session.query(SA_FUNC.max(FeedModel.date_added)).filter(
            FeedModel.symbol == crypto_symbol,
            FeedModel.date_added >= date_1_year_ago).group_by(
                SA_CAST(FeedModel.date_added, SA_TYPES.Date)).subquery()

        # Process query
        feed_models = db.session.query(FeedModel).filter(
            FeedModel.date_added.in_(subquery)).order_by(FeedModel.date_added)

        return feed_models

    @staticmethod
    def get_last_30_days_data(crypto_symbol):
        """Get last 30 days data

        :param crypto_symbol:
        :return feed models:
        """

        date_today = datetime.date.today()

        # Set date 30 days from today
        date_30_days_ago = date_today - datetime.timedelta(days=30)

        # Build subquery
        subquery = db.session.query(SA_FUNC.max(FeedModel.date_added)).filter(
            FeedModel.symbol == crypto_symbol,
            FeedModel.date_added >= date_30_days_ago).group_by(
                SA_CAST(FeedModel.date_added, SA_TYPES.Date)).subquery()

        # Process query
        feed_models = db.session.query(FeedModel).filter(
            FeedModel.date_added.in_(subquery)).order_by(FeedModel.date_added)

        return feed_models

    @staticmethod
    def get_last_7_days_data(crypto_symbol):
        """Get last 7 days data

        :param crypto_symbol:
        :return feed models:
        """

        # Set today's date
        date_today = datetime.date.today()
        date_7_days_ago = date_today - datetime.timedelta(days=7)

        # Build subquery
        subquery = db.session.query(SA_FUNC.max(FeedModel.date_added)).filter(
            FeedModel.symbol == crypto_symbol,
            FeedModel.date_added >= date_7_days_ago).group_by(
                SA_CAST(FeedModel.date_added, SA_TYPES.Date)).subquery()

        # Process query
        feed_models = db.session.query(FeedModel).filter(
            FeedModel.date_added.in_(subquery)).order_by(FeedModel.date_added)

        return feed_models

    @staticmethod
    def get_last_24_hours(crypto_symbol):
        """Get last 24 hours

        :param crypto_symbol:
        :return feed models:
        """

        # Get today's date
        date_today = datetime.date.today()

        # Get date 12 hours ago
        date_24_hours_ago = date_today - datetime.timedelta(hours=24)

        # Process query
        result = FeedModel.query.filter(
            FeedModel.symbol == crypto_symbol,
            FeedModel.date_added >= date_24_hours_ago).first()
        feed_models = [result]

        return feed_models
Example #11
0
class TaskModel(db.Model):
    __tablename__ = 'tasks'

    id = db.Column(db.Integer, primary_key=True)
    time_created = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    time_updated = db.Column(db.DateTime(), onupdate=datetime.datetime.utcnow)
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    owner = db.relationship('UserModel', foreign_keys=[owner_id])
    community_id = db.Column(db.Integer, db.ForeignKey('communities.id'), nullable=False)
    community = db.relationship('CommunityModel')
    km_interval = db.Column(db.Integer, nullable=True)
    km_next_instance = db.Column(db.DECIMAL(precision=10, scale=1), nullable=True)
    time_interval = db.Column(db.Interval, nullable=True)
    time_next_instance = db.Column(db.DateTime(), nullable=True)
    name = db.Column(db.String(120))
    description = db.Column(db.String(120))
    instances = db.relationship("TaskInstanceModel", cascade="all, delete")
    is_reocurrent = db.Column(db.Boolean, nullable=False, default=True)

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

    @staticmethod
    def get_marshaller():
        return {
            'id': fields.Integer,
            'time_created': fields.DateTime,
            'time_updated': fields.DateTime,
            'time_next_instance': fields.DateTime,
            'time_interval': TimedeltaDays,
            'owner': fields.Nested(UserModel.get_marshaller()),
            'community': fields.Nested(CommunityModel.get_marshaller()),
            'name': fields.String,
            'description': fields.String,
            'km_interval': fields.Integer,
            'km_next_instance': fields.Float,
            'km_to_next_instance': fields.Float,
            'is_reocurrent': fields.Boolean
        }

    @classmethod
    def delete_by_id(cls, task_id):
        task = db.session.query(cls).filter(cls.id == task_id).first()
        if task:
            db.session.delete(task)
            db.session.commit()
        else:
            raise NoData

    @classmethod
    def find_by_id(cls, task_id):
        return cls.query \
            .filter_by(id=task_id) \
            .first()

    @classmethod
    def return_all(cls):
        return cls.query \
            .filter_by(is_reocurrent=True) \
            .all()

    @classmethod
    def find_by_community(cls, community_id):
        return cls.query \
            .filter_by(community_id=community_id) \
            .filter_by(is_reocurrent=True) \
            .all()
Example #12
0
class TourModel(db.Model):
    __tablename__ = 'tours'

    id = db.Column(db.Integer, primary_key=True)
    time_created = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    time_updated = db.Column(db.DateTime(), onupdate=datetime.datetime.utcnow)
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    owner = db.relationship('UserModel', foreign_keys=[owner_id])
    community_id = db.Column(db.Integer,
                             db.ForeignKey('communities.id'),
                             nullable=False)
    community = db.relationship('CommunityModel')
    start_km = db.Column(db.DECIMAL(precision=(10, 1)), nullable=False)
    end_km = db.Column(db.DECIMAL(precision=(10, 1)))
    start_time = db.Column(db.DateTime(), nullable=False)
    end_time = db.Column(db.DateTime())
    parking_position = db.Column(db.String(120))
    comment = db.Column(db.String(120))
    is_force_finished = db.Column(db.Boolean)
    force_finished_by_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    force_finished_by = db.relationship('UserModel',
                                        foreign_keys=[force_finished_by_id])
    payoff_id = db.Column(db.Integer, db.ForeignKey('payoffs.id'))
    is_open = db.Column(db.Boolean, default=True)
    passengers = db.relationship('UserModel', secondary='tour_passenger_link')

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

    @staticmethod
    def get_marshaller():
        return {
            'id':
            fields.Integer,
            'time_created':
            fields.DateTime,
            'time_updated':
            fields.DateTime,
            'start_time':
            fields.DateTime,
            'end_time':
            fields.DateTime,
            'owner':
            fields.Nested(UserModel.get_marshaller()),
            'community':
            fields.Nested(CommunityModel.get_marshaller()),
            'start_km':
            fields.String,
            'end_km':
            fields.String,
            'parking_position':
            fields.String,
            'comment':
            fields.String,
            'is_force_finished':
            fields.Boolean,
            'force_finished_by':
            fields.Nested(UserModel.get_marshaller(), allow_null=True),
            'is_open':
            fields.Boolean,
            'passengers':
            fields.Nested(UserModel.get_marshaller())
        }

    @classmethod
    def delete_by_id(cls, id):
        tour = db.session.query(cls).filter(cls.id == id).first()
        if tour:
            db.session.delete(tour)
            db.session.commit()
        else:
            raise NoData

    @classmethod
    def find_by_id(cls, id):
        return cls.query.filter_by(id=id).first()

    @classmethod
    def find_finished_by_community(cls, community_id):
        return cls.query \
            .filter_by(community_id=community_id) \
            .filter(TourModel.end_km.isnot(None)) \
            .order_by(TourModel.end_time.desc()) \
            .all()

    @classmethod
    def find_finished_and_open_by_community(cls, community_id):
        return cls.query.filter_by(community_id=community_id,
                                   is_open=True).filter(
                                       TourModel.end_km.isnot(None)).all()

    @classmethod
    def find_finished_by_user(cls, user_id):
        return cls.query.filter_by(owner_id=user_id).filter(
            TourModel.end_km.isnot(None)).all()

    @classmethod
    def find_running_by_community(cls, community_id):
        return cls.query.filter_by(community_id=community_id).filter(
            TourModel.end_km.is_(None)).all()

    @classmethod
    def find_running_by_user(cls, user_id):
        return cls.query.filter_by(owner_id=user_id).filter(
            TourModel.end_km.is_(None)).all()

    @classmethod
    def find_newest_tour_for_community(cls, community_id):
        return cls.query.filter_by(community_id=community_id).order_by(
            TourModel.end_km.desc()).first()
Example #13
0
class UserModel(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(120), nullable=False)
    email = db.Column(db.String(120), nullable=False)
    time_created = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    time_updated = db.Column(db.DateTime(), onupdate=datetime.datetime.utcnow)
    cars = db.relationship("CarModel", back_populates="owner")
    communities = db.relationship("CommunityModel", secondary='community_user_link')
    tours = db.relationship("TourModel", secondary='tour_passenger_link')
    reset_password_hash = db.Column(db.String(120), nullable=True, default=None)
    reset_password_hash_created = db.Column(db.DateTime(timezone=True), default=None, nullable=True)

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

    @staticmethod
    def get_marshaller():
        return {
            'id': fields.Integer,
            'username': fields.String,
            'email': fields.String,
            'time_created': fields.DateTime,
            'time_updated': fields.DateTime
        }

    @staticmethod
    def generate_hash(password):
        return sha256.hash(password)

    @staticmethod
    def verify_hash(password, hash):
        return sha256.verify(password, hash)

    @classmethod
    def find_by_username(cls, username):
        return cls.query.filter_by(username=username).first()

    @classmethod
    def find_by_email(cls, email):
        return cls.query.filter_by(email=email).first()

    @classmethod
    def find_by_id(cls, id):
        return cls.query.filter_by(id=id).first()

    @classmethod
    def find_by_reset_password_hash(cls, hash):
        return cls.query.filter_by(reset_password_hash=hash).first()

    @classmethod
    def return_all(cls):
        return UserModel.query.all()

    @classmethod
    def delete_all(cls):
        db.session.query(cls).delete()
        db.session.commit()

    @classmethod
    def search_by_username(cls, username, excluded_username):
        return cls.query \
            .filter(UserModel.username.like('%' + username + '%')) \
            .filter(UserModel.username != excluded_username) \
            .order_by(UserModel.username) \
            .limit(10) \
            .all()
Example #14
0
class TaskInstanceModel(db.Model):
    __tablename__ = 'task_instances'

    id = db.Column(db.Integer, primary_key=True)
    time_created = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    time_updated = db.Column(db.DateTime(), onupdate=datetime.datetime.utcnow)
    task_id = db.Column(db.Integer, db.ForeignKey('tasks.id'), nullable=False)
    task = db.relationship('TaskModel', foreign_keys=[task_id])
    km_created_at = db.Column(db.DECIMAL(precision=10, scale=1), nullable=True)
    is_open = db.Column(db.Boolean)
    community_id = db.Column(db.Integer,
                             db.ForeignKey('communities.id'),
                             nullable=False)
    community = db.relationship('CommunityModel')
    time_finished = db.Column(db.DateTime(), nullable=True)
    finished_by = db.relationship('UserModel')
    finished_by_id = db.Column(db.Integer,
                               db.ForeignKey('users.id'),
                               nullable=True)

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

    @staticmethod
    def get_marshaller():
        return {
            'id':
            fields.Integer,
            'time_created':
            fields.DateTime,
            'time_updated':
            fields.DateTime,
            'time_finished':
            fields.DateTime,
            'task':
            fields.Nested(TaskModel.get_marshaller()),
            'is_open':
            fields.Boolean,
            'km_created_at':
            fields.Float,
            'finished_by':
            fields.Nested(UserModel.get_marshaller(), allow_null=True)
        }

    @classmethod
    def delete_by_id(cls, task_instance_id):
        task = db.session.query(cls).filter(cls.id == task_instance_id).first()
        if task:
            db.session.delete(task)
            db.session.commit()
        else:
            raise NoData

    @classmethod
    def find_by_id(cls, task_instance_id):
        return cls.query.filter_by(id=task_instance_id).first()

    @classmethod
    def find_by_task(cls, task_id):
        return cls.query \
            .filter_by(task_id=task_id) \
            .all()

    @classmethod
    def find_by_community(cls, community_id):
        return cls.query \
            .filter_by(community_id=community_id) \
            .all()