class MessageQueue(db.Model): __tablename__ = 'message_queue' id = db.Column(db.Integer, primary_key=True) receiver_id = db.Column(db.Integer, db.ForeignKey('contact.id')) msg_id = db.Column(db.Integer, db.ForeignKey('message.id')) status = db.Column(db.Enum(MessageStatus)) timestamp = db.Column(db.DateTime, default=datetime.utcnow) receiver = db.relationship("Contact") message = db.relationship("Message") def save(self): if not self.id: db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def update(self, **kwargs): for key, value in kwargs.items(): if hasattr(self, key): setattr(self, key, value) self.save() # If all queued messages of a message id had been send we edit the message status to DISPATCHED queued_messages = MessageQueue.query.filter_by( msg_id=self.msg_id, status=MessageStatus.QUEUED ).all() if len(queued_messages) == 0: message = Message.query.get(self.msg_id) message.update(status=MessageStatus.DISPATCHED)
class Message(db.Model): __tablename__ = 'message' id = db.Column(db.Integer, primary_key=True) sender_address = db.Column(db.String, db.ForeignKey('contact.address')) sender_nickname = db.Column(db.String, nullable=False) room_hash = db.Column(db.String, db.ForeignKey('room.hash')) msg = db.Column(db.String, nullable=False) status = db.Column(db.Enum(MessageStatus)) timestamp = db.Column(db.DateTime, default=datetime.utcnow) sender = db.relationship("Contact") # room = db.relationship("Room") room = db.relationship("Room", back_populates="messages") def save(self): if not self.id: db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def update(self, **kwargs): for key, value in kwargs.items(): if hasattr(self, key): setattr(self, key, value) self.save()
class Room(db.Model): __tablename__ = 'room' id = db.Column(db.Integer, primary_key=True) hash = db.Column(db.String, unique=True) name = db.Column(db.String, nullable=False) private = db.Column(db.Boolean, default=False) admin_address = db.Column(db.String, nullable=True) members = db.relationship("Contact", secondary=rooms_contacts_association) messages = db.relationship( "Message", back_populates="room", cascade="all, delete" ) def save(self): if not self.id: db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def update(self, **kwargs): for key, value in kwargs.items(): if hasattr(self, key): setattr(self, key, value) self.save()
class Appointment(db.Model): __tablename__ = 'appointments' id = db.Column(db.Integer, primary_key=True) patient_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) doctor_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) description = db.Column(db.String(120)) doctor_notes = db.Column(db.String(120)) date = db.Column(db.Date, nullable=False) start = db.Column(db.Time, nullable=False) status = db.Column(db.Enum(AppointmentStatus), nullable=False) patient = db.relationship('User', foreign_keys=[patient_id], backref='p_appointments') doctor = db.relationship('User', foreign_keys=[doctor_id], backref='d_appointments') def __init__(self, description, date, start, status=AppointmentStatus.PENDING): self.description = description self.date = date self.start = start self.status = status def serialize(self, user_type): payload = { "id": self.id, "description": self.description, "doctor_notes": self.doctor_notes, "date": self.date.strftime("%Y-%m-%d"), "start": self.start.strftime("%H:%M"), "status": self.status.name } if user_type == UserType.DOCTOR: payload['patient'] = self.patient.serialize() elif user_type == UserType.PATIENT: payload['doctor'] = self.doctor.serialize() else: payload['patient'] = self.patient.serialize() payload['doctor'] = self.doctor.serialize() return payload
class User(db.Model, JSONStripped): __tablename__ = 'user' def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) id = \ db.Column(db.Integer, primary_key=True) login = \ db.Column(db.String(50), unique=True, nullable=False) password_hash = \ db.Column(db.String(255), nullable=False) creation_time = \ db.Column(db.DateTime, index=True, default=datetime.utcnow) st_login = \ db.Column(db.String(10), unique=True, nullable=True) course = \ db.Column(db.String(255), index=True, nullable=True) username = \ db.Column(db.String(50), index=True, nullable=False) is_public = \ db.Column(db.Boolean, default=True) score_second_lang = \ db.Column(db.Boolean, default=False) gpa = \ db.Column(db.Float, default=0) scores = \ db.relationship('UserSubject', lazy='subquery', cascade='all, delete-orphan') priorities = \ db.relationship('UserTrack', lazy='subquery', cascade='all, delete-orphan') def __repr__(self): return '<User %r>' % self.login @staticmethod def insert(**kwargs): user = User(**kwargs) db.session.add(user) db.session.commit() return user @staticmethod def get_all(**kwargs): return User.query.filter_by(**kwargs) @staticmethod def get_one(**kwargs): return User.query.filter_by(**kwargs).first()
class Prescription(db.Model): __tablename__ = 'prescriptions' id = db.Column(db.Integer, primary_key=True) patient_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) doctor_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) drug = db.Column(db.String(50), nullable=False) dosage = db.Column(db.String(50), nullable=False) date = db.Column(db.Date, nullable=False) status = db.Column(db.Enum(PrescriptionStatus), nullable=False) patient = db.relationship('User', foreign_keys=[patient_id], backref='p_prescriptions') doctor = db.relationship('User', foreign_keys=[doctor_id], backref='d_prescriptions') def __init__(self, drug, dosage, date, status=PrescriptionStatus.ACTIVE): self.drug = drug self.date = date self.dosage = dosage self.status = status def serialize(self, user_type): payload = { "id": self.id, "drug": self.drug, "date": self.date.strftime("%Y-%m-%d"), "dosage": self.dosage, "status": self.status.name } if user_type == UserType.DOCTOR: payload['patient'] = self.patient.serialize() elif user_type == UserType.PATIENT: payload['doctor'] = self.doctor.serialize() else: payload['patient'] = self.patient.serialize() payload['doctor'] = self.doctor.serialize() return payload
class Employee(db.Model): __tablename__ = "employee" id = db.Column(UUIDType(), db.ForeignKey(User.id), primary_key=True) user = db.relationship('User') name = db.Column(db.String(45), nullable=False) gender = db.Column(db.String(45), nullable=False) tel = db.Column(db.String(45), nullable=False) # stat = db.Column(db.Integer, nullable=False) level = db.Column(db.Integer, nullable=False) @staticmethod def new_employee(id, name, gender, tel, level=0) -> "Employee": # Test that employee id exists in user table user = User.get_by_id(id) return Employee( id=id, name=name, gender=gender, tel=tel, level=level, # stat = stat ) @staticmethod def get_by_id(id) -> "Employee": if type(id) != UUID: try: id = UUID(id) except: raise AttributeError("Invalid UUID") query = Employee.query.filter_by(id=id) if query.count() == 0: raise ValueError(f"Employee {str(id)} not found.") return query.first() @staticmethod def id_exists(id) -> bool: id = to_uuid(id) query = Employee.query.filter_by(id=id) if query.count() > 0: return True return False def json(self) -> dict: return { "id": str(self.id), "name": self.name, "gender": self.gender, "tel": self.tel, "level": self.level, }
class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(120), unique=True, nullable=False) username = db.Column(db.String(120), unique=True, nullable=False) password = db.Column(db.String(200), nullable=False) first_name = db.Column(db.String(30), nullable=False) last_name = db.Column(db.String(30), nullable=False) dob = db.Column(db.Date) phone_number = db.Column(db.String(20)) created_at = db.Column(db.DateTime, server_default=func.current_timestamp()) user_type = db.Column(db.Enum(UserType), nullable=False) user_status = db.Column(db.Enum(UserStatus), nullable=False) specialization_id = db.Column(db.Integer, db.ForeignKey('specializations.id')) specialization = db.relationship('Specialization', backref='doctors') def __init__(self, email, username, first_name, last_name, dob, phone_number, user_type, user_status): self.email = email self.username = username self.first_name = first_name self.last_name = last_name self.dob = dob self.phone_number = phone_number self.user_type = user_type self.user_status = user_status def set_password(self, password): self.password = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password, password) def serialize(self): payload = { "id": self.id, "email": self.email, "username": self.username, "first_name": self.first_name, "last_name": self.last_name, "user_type": self.user_type.name, "user_status": self.user_status.name } if self.user_type == UserType.PATIENT: payload['dob'] = self.dob.strftime("%Y-%m-%d") payload['phone_number'] = self.phone_number elif self.user_type == UserType.DOCTOR: payload['dob'] = self.dob.strftime("%Y-%m-%d") payload['phone_number'] = self.phone_number payload['specialization'] = self.specialization.spec return payload
class Session(db.Model): __tablename__ = 'session' id = db.Column(UUIDType(), primary_key=True) uid = db.Column(UUIDType(), db.ForeignKey('user.id'), nullable=False) user = db.relationship('User', backref=db.backref('sessions', lazy=True)) expire = db.Column(db.DateTime(), nullable=False) @staticmethod def new_session(username, expire=None) -> 'Session': if expire == None: expire = datetime.now() + timedelta(hours=3) if type(expire) in (int, float): expire = datetime.fromtimestamp(expire) user = User.get_by_username(username) return Session( id=uuid4(), user=user, expire=expire, ) @staticmethod def get_by_id(id) -> 'Session': if type(id) != UUID: try: id = UUID(id) except: raise AttributeError("Invalid UUID") query = Session.query.filter_by(id=id) if query.count() == 0: raise ValueError(f"Session {str(id)} not found.") session = query.first() if session.expired(): db.session.delete(session) db.session.commit() raise ValueError(f"Session {str(id)} not found.") return session def json(self) -> dict: return { "id": str(self.id), "user": self.user.json(), "expire": int(self.expire.timestamp()), } def expired(self) -> bool: return self.expire < datetime.now()
class UserTrack(db.Model, JSONStripped): __tablename__ = '$user$track' def __init__(self, *args, **kwargs): super(UserTrack, self).__init__(*args, **kwargs) user_id = \ db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True) track_id = \ db.Column('track_id', db.Integer, db.ForeignKey('track.id'), primary_key=True) priority = \ db.Column('priority', db.Integer, nullable=False) track = db.relationship('Track', lazy='subquery') def __repr__(self): return '<UserTrack %r %r>' % self.user_id % self.track_id
class UserSubject(db.Model, JSONStripped): __tablename__ = '$user$subject' def __init__(self, *args, **kwargs): super(UserSubject, self).__init__(*args, **kwargs) user_id = \ db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True) subject_id = \ db.Column('subject_id', db.Integer, db.ForeignKey('subject.id'), primary_key=True) mark = \ db.Column('mark', db.String(2), nullable=False) is_relevant = \ db.Column('is_relevant', db.Boolean, default=True) subject = db.relationship('Subject', lazy='subquery') def __repr__(self): return '<UserSubject %r %r>' % self.user_id % self.subject_id
class Order(db.Model): __tablename__ = "orders" id = db.Column(UUIDType(), primary_key=True) item = db.Column(db.String(45), nullable=False) customer_id = db.Column(UUIDType(), db.ForeignKey(Customer.id), nullable=False) employee_id = db.Column(UUIDType(), db.ForeignKey(Employee.id), nullable=False) customer = db.relationship('Customer', backref=db.backref('orders', lazy=True)) employee = db.relationship('Employee', backref=db.backref('orders', lazy=True)) order_time = db.Column(db.String(45), nullable=False) star_rating = db.Column(db.Integer, nullable=True) stat = db.Column(db.Integer, nullable=False) @staticmethod def new_order(id, item, customer_id, employee_id, order_time, stat=0, star_rating=None) -> "Order": # Test that customer & employee ids are valid customer = Customer.get_by_id(customer_id) employee = Employee.get_by_id(employee_id) return Order(id=id, item=item, customer_id=customer_id, employee_id=employee_id, order_time=order_time, star_rating=star_rating, stat=stat) @staticmethod def get_by_id(id) -> "Order": id = to_uuid(id) query = Order.query.filter_by(id=id) if query.count() == 0: raise ValueError(f"Order {str(id)} not found.") return query.first() def json(self) -> dict: return { "id": str(self.id), "item": self.item, "customer": self.customer, "employee": self.employee, "order_time": self.order_time, "star_rating": self.star_rating, "stat": self.stat, } @staticmethod def get_by_participant_id(role, id) -> list: id = to_uuid(id) if role == 'customer': query = Order.query.filter_by(customer_id=id) elif role == 'employee': query = Order.query.filter_by(employee_id=id) else: raise AttributeError(f"Role {role} not valid for order {str(id)}") return query.all()
class User(db.Model): __tablename__ = 'User' id = db.Column(db.String(100), primary_key=True) username = db.Column(db.String(80)) password = db.Column(db.String(100)) email = db.Column(db.String(100)) photoURL = db.Column(db.String, default=_photoURL) allowed_usage = db.Column(db.Integer) ftl = db.Column(db.Boolean, default=True) created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) deleted_at = db.Column(db.DateTime, nullable=True) files = db.relationship('File', backref='uploader') badges = db.relationship('Badges', backref='creator') permissions = db.relationship('Permissions', backref=db.backref('user_permissions'), lazy='dynamic') siteAdmin = db.Column(db.Boolean, default=False) last_login_ip = db.Column(db.String, nullable=True) last_login_date = db.Column(db.DateTime, nullable=True) def __init__(self, id_, username, password, email, photoURL=None): self.id = id_ self.username = username self.allowed_usage = 200 if password: self.password = generate_password_hash(password) self.email = email if photoURL: self.photoURL = photoURL def create_site_admin(self): self.siteAdmin = True self.save_to_db() def save_to_db(self): db.session.add(self) try: db.session.commit() except Exception as e: db.session.rollback() db.session.flush() print(e) def delete_user(self): db.session.delete(self) try: db.session.commit() except Exception as e: db.session.rollback() db.session.flush() print(e) @classmethod def getUser(cls, user_id=None, username=None, email=None): if user_id: return cls.query.filter_by(id=user_id).first() if username: return cls.query.filter_by(username=username).first() if email: return cls.query.filter_by(email=email).first()