class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) # User authentication information (required for Flask-User) email = db.Column(db.Unicode(255), nullable=False, server_default=u'', unique=True) password = db.Column(db.String(255), nullable=False, server_default='') actiu = db.Column(db.Boolean(), nullable=False, server_default='0') # User information actiu = db.Column('is_active', db.Boolean(), nullable=False, server_default='0') nom = db.Column(db.Unicode(50), nullable=False, server_default=u'') # Relationships roles = db.relationship('Role', secondary='users_roles', backref=db.backref('users', lazy='dynamic')) def __str__(self): return u"Nom : {name}; Email: {email})".format(name=self.nom, email=self.email)
class File(db.Model): __bind_key__ = 'wehomeproperty' id = db.Column(db.Integer(), index=True, primary_key=True) # 0 => s3 file type = db.Column(db.Integer()) is_active = db.Column(db.Boolean(), default=True, index=True) foreign_id = db.Column(db.Integer(), nullable=False, index=True) # like report's item id and itme id item_id = db.Column(db.Integer(), nullable=False, index=True) filename = db.Column(db.String(255)) # the raw name of upload raw_name = db.Column(db.String(255)) created_at = db.Column(db.DateTime(), default=datetime.datetime.now) updated_at = db.Column(db.DateTime(), default=datetime.datetime.now, onupdate=datetime.datetime.now) __table_args__ = ( db.Index("idx_foreign_id_item_id_type_is_active", "foreign_id", 'item_id', 'type', 'is_active'), ) def __init__(self, type, foreign_id, item_id, filename, raw_name, is_active=True): self.type = type self.foreign_id = foreign_id self.item_id = item_id self.filename = filename self.is_active = is_active self.raw_name = raw_name
class User(db.Model): __tablename__ = "user" id = db.Column(db.Integer(), primary_key=True) email = db.Column(db.String(255), unique=True) username = db.Column(db.String(255), unique=True) password = db.Column(db.Binary(60), nullable=False) bodyweight = db.Column(db.Integer()) one_rep_max = db.relationship("OneRepMax") imperial = db.Column(db.Boolean()) sessions = db.relationship("UserSession", lazy="dynamic") def __init__(self, email, password, imperial=True, bodyweight=-1): self.email = email self.active = True self.password = User.hashed_password(password) self.imperial = imperial self.bodyweight = bodyweight @staticmethod def hashed_password(password): return bcrypt.generate_password_hash(password) @staticmethod def get_user_with_email_and_password(email, password): user = User.query.filter_by(email=email).first() if user and bcrypt.check_password_hash(user.password, password): return user else: return None
class Room(db.Model): id = db.Column(db.Integer(), primary_key=True, nullable=False) office_id = db.Column(db.Integer(), db.ForeignKey('office.id'), primary_key=True, nullable=False) room_name = db.Column(db.String(100)) elevator_accessible = db.Column(db.Boolean())
class Product(db.Model): id = db.Column(db.Integer(), primary_key=True) product_name = db.Column(db.String(255)) product_description = db.Column(db.Text()) category_id = db.Column(db.Integer(), db.ForeignKey('category.id'), nullable=False) pre_approved = db.Column(db.Boolean())
class UserSet(db.Model): __tablename__ = "user_set" id = db.Column(db.Integer(), primary_key=True) workout_id = db.Column(db.Integer(), db.ForeignKey("user_session.id")) reps = db.relationship("UserRep") rest = db.Column(db.Integer()) ordinal = db.Column(db.Integer()) completed = db.Column(db.Boolean()) effort_level = db.Column(db.Integer())
class Game(db.Model): __tablename__ = 'game' id = db.Column(db.Integer(), primary_key=True) age = db.Column(db.Integer(), default=0) round = db.Column(db.Integer(), default=1) started = db.Column(db.Boolean(), default=False) complete = db.Column(db.Boolean(), default=False) single_player = db.Column(db.Boolean(), default=False) waiting_for_discard = db.Column(db.Boolean(), default=False) def serialise(self): return { 'id': self.id, 'age': self.age, 'round': self.round, 'started': self.started, 'complete': self.complete, 'single_player': self.single_player, 'waiting_for_discard': self.waiting_for_discard }
class Rule(db.Model): __bind_key__ = 'wehomeproperty' id = db.Column(db.Integer(), index=True, primary_key=True) users = relationship("User", secondary=user_rule_association, back_populates="rules") api_id = db.Column(db.String(255)) throttle_day = db.Column(db.String(255)) throttle_hour = db.Column(db.String(255)) throttle_min = db.Column(db.String(255)) includes = db.Column(db.Text()) excludes = db.Column(db.Text()) statistics = db.Column(db.Boolean(), default=False) notes = db.Column(db.String(255)) extra = db.Column(db.Text())
class Event(db.Model, DictSerializable): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(255)) start_date = db.Column(db.DateTime()) guid = db.Column(db.String(255), unique=True, index=True) is_open = db.Column(db.Boolean()) outcomes = db.relationship('Outcome', backref='event', lazy='joined') def __init__(self, name, start_date, guid): self.name = name self.start_date = start_date self.is_open = True self.guid = guid def close_outcomes(self): for outcome in self.outcomes: outcome.close_date = datetime.datetime.now() outcome.is_open = False @staticmethod def get_events(): events = Event.query.filter(Event.start_date >= datetime.datetime.now()) \ .outerjoin(Event.outcomes) \ .order_by(Event.start_date).all() serialized_events = [] for event in events: outcomes = [] for outcome in event.outcomes: outcome_serialized = outcome.full_serialize() # del outcome_serialized['event'] outcomes.append(outcome_serialized) serialized = Event.serialize(event) serialized['outcomes'] = outcomes serialized_events.append(serialized) return serialized_events @staticmethod def get_outcomes(event_id): event = Event.query.get(event_id) if event: return event.outcomes else: return None
class Document(db.Model, BlobMixin): __tablename__ = 'documents' id = db.Column(db.Integer, primary_key=True) creat = db.Column(db.DateTime, server_default=db.func.now()) nom = db.Column(db.Unicode(length=255), nullable=False, unique=True) compartit = db.Column(db.Boolean(), nullable=False, server_default='0') clients = db.relationship('User', secondary='users_documents', backref=db.backref('documents', lazy='dynamic')) tipus_id = db.Column(db.Integer(), db.ForeignKey('tipus_document.id')) tipus = db.relationship('TipusDocument', foreign_keys=tipus_id) def __str__(self): return u"nom: {name}; document: {filename})".format( name=self.nom, filename=self.filename) def __lt__(self, other): return self.creat > other.creat
class ExtraFile(db.Model): __bind_key__ = 'wehomeproperty' '''for user or property extra file''' id = db.Column(db.Integer(), index=True, primary_key=True) # user_id or property_id foreign_id = db.Column(db.Integer(), nullable=False, index=True) file_id = db.Column(db.Integer()) # 0 => user inspection report 1 => user contract file type = db.Column(db.Integer()) url = db.Column(db.String(255)) # 0 => discard 1 => used is_active = db.Column(db.Boolean(), default=True, index=True) created_at = db.Column(db.DateTime(), default=datetime.datetime.now) updated_at = db.Column(db.DateTime(), default=datetime.datetime.now, onupdate=datetime.datetime.now) def __init__(self, foreign_id, file_id, type, url, is_active=1): self.foreign_id = foreign_id self.file_id = file_id self.type = type self.url = url self.is_active = is_active
class Variable(db.Model): id = db.Column(db.Integer, primary_key=True) variable_name = db.Column(db.String(120), nullable=False) variable_type = db.Column(db.String(20), nullable=True) variable_writable = db.Column(db.Boolean(), nullable=False) variable_address = db.Column(db.String(120), nullable=False) variable_value = db.Column(db.String(100), nullable=True) variable_object_id = db.Column(db.Integer, db.ForeignKey('object.id', ondelete='CASCADE'), nullable=False) @staticmethod def validate(obj_id, address): allvarrs = Object.query.get(obj_id).object_variables.all() for var in allvarrs: if var.variable_address == address: return False return True def __repr__(self): return "Variable: {}".format(self.variable_name)
class Escrow(db.Model, DictSerializable): id = db.Column(db.Integer(), primary_key=True) offer_id = db.Column(db.Integer(), db.ForeignKey('offer.id')) bid_id = db.Column(db.Integer(), db.ForeignKey("bid.id")) wallet_id = db.Column(db.Integer(), db.ForeignKey('wallet.id')) comission = db.Column( db.Numeric(precision=BTC_PRECISION, scale=(BTC_PRECISION - BTC_NUMERAL))) value = db.Column( db.Numeric(precision=BTC_PRECISION, scale=(BTC_PRECISION - BTC_NUMERAL))) active = db.Column(db.Boolean()) payout_date = db.Column(db.DateTime()) incoming_hash = db.Column(db.String(255)) def __init__(self, offer_id, wallet_id, bid_id, comission, value): self.offer_id = offer_id self.wallet_id = wallet_id self.bid_id = bid_id self.comission = comission self.value = value self.active = True
class Outcome(db.Model, DictSerializable): id = db.Column(db.Integer(), primary_key=True) event_id = db.Column(db.Integer(), db.ForeignKey('event.id'), index=True) type_id = db.Column(db.Integer(), index=True) name = db.Column(db.String(255)) open_date = db.Column(db.DateTime()) close_date = db.Column(db.DateTime()) is_open = db.Column(db.Boolean()) average_odds = db.Column(db.Numeric(precision=4, scale=2)) total_riding = db.Column( db.Numeric(precision=BTC_PRECISION, scale=(BTC_PRECISION - BTC_NUMERAL))) offers = db.relationship('Offer', backref='outcome', lazy='joined') def __init__(self, event_id, name, open_date, close_date, is_open, type_id): self.event_id = event_id self.name = name self.open_date = open_date self.close_date = close_date self.is_open = is_open self.type_id = type_id def get_valid_offers(self): offers = [] for offer in self.offers: if offer.tx_hash != None: offers.append(offer) return offers def get_valid_bids(self): bids = [] for offer in self.offers: if offer.tx_hash != None: for bid in offer.bids: if bid.tx_hash != None: bids.append(bid) return bids @staticmethod def get_spread(outcome_id): outcome_obj = Outcome.query.filter_by(id=outcome_id) \ .outerjoin(Outcome.offers) \ .outerjoin(Bid).first() if not outcome_obj: return None else: event_db = Event.query.get(outcome_obj.event_id) event_obj = Event.serialize(event_db) del event_obj['outcomes'] outcome_dict = outcome_obj.full_serialize(True, True) return {'event': event_obj, 'outcome': outcome_dict} def full_serialize(self, with_offers=False, with_bids=False, prune_invalid=True): offers = [] if with_offers: for offer in self.offers: if offer.tx_hash == None: continue bids = [] if with_bids: for bid in offer.bids: if bid.tx_hash == None: continue bid_serialized = Bid.serialize(bid) del bid_serialized['user'] del bid_serialized['offer'] bids.append(bid_serialized) offer_dict = Offer.serialize(offer) del offer_dict['user'] del offer_dict['outcome'] offer_dict['bids'] = bids offers.append(offer_dict) outcome_dict = Outcome.serialize(self) del outcome_dict['event'] outcome_dict['offers'] = offers return outcome_dict @staticmethod def filter_outcome_optionals(results, is_open, with_offers, with_bids): if is_open != None: results = results.filter_by(is_open=is_open) if with_offers: results.outerjoin(Outcome.offers) \ .filter(Offer.tx_hash != None) if with_bids: results.outerjoin(Bid) \ .filter(Bid.tx_hash != None) outcomes = results.all() returned = [] for outcome_obj in outcomes: serialized_outcome = outcome_obj.full_serialize( with_offers, with_bids) returned.append(serialized_outcome) return returned @staticmethod def filter_outcomes_range(start_date, end_date, is_open, with_offers, with_bids): results = Outcome.query.filter(Outcome.close_date >= start_date) \ .filter(Outcome.close_date <= end_date) return Outcome.filter_outcome_optionals(results, is_open, with_offers, with_bids) @staticmethod def filter_outcomes_day(on_date, is_open, with_offers, with_bids): results = Outcome.query.filter(Outcome.close_date == on_date) return Outcome.filter_outcome_optionals(results, is_open, with_offers, with_bids) @staticmethod def filter_outcomes_bisect(start_date, before, is_open, with_offers, with_bids): if before: results = Outcome.query.filter(Outcome.close_date < start_date) else: results = Outcome.query.filter(Outcome.close_date >= start_date) return Outcome.filter_outcome_optionals(results, is_open, with_offers, with_bids) @staticmethod def get_offers(outcome_id): outcome = Outcome.query.get(outcome_id) if outcome: return outcome.offers else: return None
class User(db.Model): __tablename__ = "user" id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(255)) email = db.Column(db.String(255), unique=True) active = db.Column(db.Boolean()) role = db.Column(db.Enum("responder", "verifier", "admin", name='roles')) password = db.Column(db.String(255)) phone = db.Column(db.String(15)) last_msg = db.Column(db.Integer(), ForeignKey('message.id')) tags = relationship('UserTags', primaryjoin="and_(User.id==UserTags.user_id)", backref="user") def __init__(self, email="", password="", phone="", name="", role="responder"): self.name = name self.email = email self.role = role self.active = True self.password = User.hashed_password(password) if password else None self.phone = phone def as_dict(self): return { 'id': self.id, 'name': self.name, 'phone': self.phone, 'role': self.role, 'email': self.email, 'tags': [tag.tag_id for tag in self.tags], 'last_msg': self.last_msg, 'active': self.active } def update(self, values): for key, value in values.iteritems(): if key == 'tags': # remove existing tags before updating UserTags.query.filter_by(user_id=self.id).delete() db.session.commit() # add all tags selected for tag_id in value: tag = UserTags(user_id=self.id, tag_id=tag_id) db.session.add(tag) else: self.__setattr__(key, value) try: db.session.add(self) db.session.commit() return self except IntegrityError: return None def mark_last_msg(self, last_msg): self.__setattr__('last_msg', last_msg) db.session.add(self) db.session.commit() def subscribe(self, subscribed=True): self.__setattr__('active', subscribed) db.session.add(self) db.session.commit() @staticmethod def hashed_password(password): return bcrypt.generate_password_hash(password) @staticmethod def get_user_with_email_and_password(email, password): user = User.query.filter_by(email=email).first() if user and bcrypt.check_password_hash(user.password, password): return user else: return None @staticmethod def get_all(): return db.session.query(User, UserTags, Tag).join(Usertags).join(Tag) @staticmethod def from_number(lookup_number): user = User.query.filter_by(phone=lookup_number).first() if not user: user = User(None, None, lookup_number) db.session.add(user) db.session.commit() return user
class Bid(db.Model, DictSerializable): id = db.Column(db.Integer(), primary_key=True) offer_id = db.Column(db.Integer(), db.ForeignKey('offer.id'), index=True) user_id = db.Column(db.Integer(), db.ForeignKey('user.id'), index=True) value = db.Column( db.Numeric(precision=BTC_PRECISION, scale=(BTC_PRECISION - BTC_NUMERAL))) is_win = db.Column(db.Boolean()) is_paid = db.Column(db.Boolean()) hash = db.Column(db.String(255), unique=True) tx_hash = db.Column(db.String(255)) def __init__(self, offer_id, user_id, value): self.offer_id = offer_id self.user_id = user_id self.value = value self.is_paid = False self.hash = bcrypt.generate_password_hash("{0}{1}{2}".format( user_id, offer_id, datetime.datetime.now())) @staticmethod def aggregate_offers(outcome_id, odds, coverage): found_offers = Offer.query.filter_by(odds=odds, outcome_id=outcome_id) \ .filter(Offer.remaining_coverage > 0) \ .filter(Offer.tx_hash != None) \ .order_by(Offer.id) \ .all() selected_offers = [] satisfied_coverage = 0 for offer in found_offers: if satisfied_coverage == coverage: break else: this_offer_coverage = min(coverage - satisfied_coverage, \ offer.remaining_coverage) satisfied_coverage += this_offer_coverage selected_offers.append({ 'id': offer.id, 'tx_hash': offer.tx_hash, 'amount': this_offer_coverage }) print satisfied_coverage, coverage if satisfied_coverage != coverage: raise AssertionError('Not enough coverage.') return selected_offers @staticmethod def make_bid(bid_object): if Offer.can_bid(bid_object.offer_id): # offer.total_riding += bid_object.value # if offer.outcome.total_riding is None: # offer.outcome.total_riding = bid_object.value # else: # offer.outcome.total_riding += bid_object.value offer = Offer.query.get(bid_object.offer_id) offer.remaining_coverage -= Decimal(bid_object.value) outcome = Outcome.query.get(offer.outcome_id) if not outcome.total_riding: outcome.total_riding = Decimal(bid_object.value) else: outcome.total_riding += Decimal(bid_object.value) db.session.add(bid_object) else: raise AttributeError("Cannot bid on that offer") @staticmethod def confirm(hash, tx_hash, user_id): bid = Bid.query.filter_by(hash=hash).first() if not bid: return None if bid.tx_hash: raise AssertionError('Hash already assigned') if bid.user_id != user_id: raise AssertionError('User does not own this bid') bid.tx_hash = tx_hash return bid
class Offer(db.Model, DictSerializable): id = db.Column(db.Integer(), primary_key=True) user_id = db.Column(db.Integer(), db.ForeignKey('user.id'), index=True) outcome_id = db.Column(db.Integer(), db.ForeignKey('outcome.id'), index=True) odds = db.Column(db.Numeric(precision=4, scale=2)) coverage = db.Column( db.Numeric(precision=BTC_PRECISION, scale=(BTC_PRECISION - BTC_NUMERAL))) remaining_coverage = db.Column( db.Numeric(precision=BTC_PRECISION, scale=(BTC_PRECISION - BTC_NUMERAL))) hash = db.Column(db.String(255), unique=True) tx_hash = db.Column(db.String(255)) is_win = db.Column(db.Boolean()) bids = db.relationship('Bid', backref='offer', lazy='joined') def __init__(self, user_id, outcome_id, odds, coverage): self.user_id = user_id self.outcome_id = outcome_id self.odds = odds self.coverage = coverage self.remaining_coverage = coverage self.hash = bcrypt.generate_password_hash("{0}{1}{2}".format( user_id, outcome_id, datetime.datetime.now())) @staticmethod def find_by_hash(hash): return Offer.query.filter_by(hash=hash).first() @staticmethod def confirm(hash, tx_hash, user_id): offer = Offer.find_by_hash(hash) if not offer: return None if offer.tx_hash: raise AssertionError('Hash already assigned') if offer.user_id != user_id: raise AssertionError('User does not own this offer') offer.tx_hash = tx_hash return offer @staticmethod def get_bids(offer_id): offer = Offer.query.get(offer_id) if offer and offer.outcome.is_open: return offer.bids else: return None @staticmethod def max_bid(offer_id): offer = Offer.query.get(offer_id) if offer and offer.outcome.is_open: remaining_coverage = Offer.remaining_coverage_with_offer(offer) return remaining_coverage / offer.odds else: return 0 @staticmethod def can_bid(offer_id): offer = Offer.query.filter_by(id=offer_id) \ .join(Outcome) \ .outerjoin(Bid) \ .first() return Offer.can_bid_with_offer(offer) @staticmethod def can_bid_with_offer(offer): if offer: return offer.outcome.is_open and offer.remaining_coverage > 0 else: return False