class FoodHistory(db.Model): __tablename__ = 'food_history' id = db.Column(db.Integer, primary_key=True) food_id = db.Column(db.Integer, db.ForeignKey('food.id')) user_detail_id = db.Column(db.Integer, db.ForeignKey('user_detail.id')) action_name = db.Column(db.String(255)) time_created = db.Column(db.DateTime, default=datetime.now())
class Comment(db.Model): __tablename__ = 'comment' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) post_id = db.Column(db.Integer, db.ForeignKey('post.id')) content = db.Column(db.TEXT) status = db.Column(db.SmallInteger)
class UserDetail(db.Model): __tablename__ = 'user_detail' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) desc = db.Column(db.TEXT) photo = db.Column(db.TEXT) linkedin = db.Column(db.TEXT)
class WikiPageVersion(db.Model): __tablename__ = 'wiki_page_version' ( STATUS_NOT_CURRENT, STATUS_CURRENT, ) = range(2) id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255)) text = db.Column(db.Text) status = db.Column(db.Integer, default=STATUS_CURRENT, index=True) wiki_page_id = db.Column(db.Integer, db.ForeignKey('wiki_page.id'), index=True) def __repr__(self): return '<WikiPageVersion %s>' % self.id @classmethod def condition_status_current(cls): return cls.status == WikiPage.STATUS_CURRENT @classmethod def condition_status_not_current(cls): return cls.status == WikiPage.STATUS_NOT_CURRENT
class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True, nullable=False, autoincrement=True) name = db.Column(db.String(64), nullable=False, unique=True)
class JobHistory(db.Model): __tablename__ = 'job_history' id = db.Column(db.Integer, primary_key=True) job_id = db.Column(db.Integer, db.ForeignKey('job.id')) user_detail_id = db.Column(db.Integer, db.ForeignKey('user_detail.id')) name = db.Column(db.String(255)) time_created = db.Column(db.DateTime, default=datetime.now())
class RideAccepted(Notification): _nid = db.Column('nid', db.Integer, db.ForeignKey('notification.nid'), primary_key=True) _user = db.relationship('User') _user_id = db.Column(db.ForeignKey('user.uid')) _ride = db.relationship('Ride') _ride_id = db.Column(db.ForeignKey('ride.rid')) __tablename__ = 'notification$ride_accepted' __mapper_args__ = { 'polymorphic_identity': 'ride_accepted' } def __init__(self, ride, user): Notification.__init__(self) self._ride = ride self._user = user def get_type(self): return 'RIDE_ACCEPTED' def get_data(self): return { 'user': self._user.get_public_view(), 'ride': self._ride.get_view() }
class Currency(db.Model): __tablename__: str = 'currency' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), unique=True, nullable=False) denote = db.Column(db.String(100), unique=True, nullable=False) foods = db.relationship('Food', backref='currency', lazy=True) created_timestamp = db.Column(db.DateTime, default=datetime.now())
class Cart(db.Model): # relationship with order __tablename__: str = 'cart' id = db.Column(db.Integer, primary_key=True) order_id = db.Column(db.Integer, db.ForeignKey('order.id')) cart_items = db.relationship('CartItem', backref='cart', lazy=True) created_timestamp = db.Column(db.DateTime, default=datetime.now())
class UserRole(db.Model): __tablename__ = 'user_roles' user_id = db.Column(db.String(36), db.ForeignKey('users.id', ondelete='CASCADE'), primary_key=True) role_id = db.Column(db.Integer(), db.ForeignKey('roles.id', ondelete='CASCADE'), primary_key=True)
class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.String(36), primary_key=True, nullable=False) password = db.Column(db.String(), nullable=False) email = db.Column(db.String(255), nullable=False, unique=True) roles = db.relationship('Role', secondary='user_roles', lazy='subquery', backref=db.backref('users', lazy=True))
class Certificate(db.Model): id = db.Column(db.Integer, primary_key=True) __tablename__: str = 'certificate' issuer_id = db.Column(db.Integer, db.ForeignKey('certificate_giver.id'), nullable=False) date = db.Column(db.DateTime, default=datetime.now()) number = db.Column(db.Integer, nullable=False) foods = db.relationship('Food', backref='certificate', lazy=True)
class Order(db.Model): __tablename__: str = 'order' id = db.Column(db.Integer, primary_key=True) payment_method_id = db.Column(db.Integer, db.ForeignKey('payment_method.id')) total = db.Column(db.Float, default=0.0) paid = db.Column(db.Boolean, default=False) state = db.Column(db.String(30), default="In Progress") notes = db.Column(db.Text) user_detail_id = db.Column(db.Integer, db.ForeignKey('user_detail.id')) driver_id = db.Column(db.Integer, db.ForeignKey('driver.id')) order_time = db.Column(db.DateTime, default=datetime.now()) cart = db.relationship('Cart', uselist=False, backref='order') order_loc = db.relationship('OrderLocationTracked', uselist=False, backref='order_loc') deliver_to = db.relationship('OrderLocationTracked', uselist=False, backref='deliver_to') created_timestamp = db.Column(db.DateTime, default=datetime.now()) def get(self, detail=False): carts = [] if detail: for cart in self.cart.cart_items: carts.append({ "item": cart.food.__serialize__(with_img=True), "count": cart.qty, "note": cart.note }) else: for cart in self.cart.cart_items: carts.append({ "item": cart.food.name, "count": cart.qty, "note": cart.note }) data = { "id": self.id, "orders": carts, "payment": self.payment_method_id, "total": self.total, "paid": self.paid, "state": self.state, "driver": "belum ada driver" } if self.driver: drv = { "id": self.driver, "name": self.driver.user_detail.fullname, "image": self.driver.user_detail.image, "phone": self.driver.user_detail.phone_number, "rating": self.driver.ratting } data.update({"driver": drv}) return data
class CertificateGiver(db.Model): __tablename__: str = 'certificate_giver' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False, unique=True) certificates = db.relationship('Certificate', uselist=False, backref='certificate_giver', lazy=True) time_created = db.Column(db.DateTime, default=datetime.now())
class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(90), unique=True, nullable=False) email = db.Column(db.String(100), unique=True, nullable=False) password = db.Column(db.String(255), nullable=False) level = db.Column(db.SMALLINT, nullable=False, default=0) user_detail = db.relationship(UserDetail, uselist=False, backref='user') posts = db.relationship(Post, uselist=False, backref='user')
class Device(db.Model): device_id = db.Column(db.String(36), primary_key=True) last_query = db.Column(db.DateTime, nullable=False, default=db.func.current_timestamp()) def __init__(self, device_id=''): if device_id: self.device_id = device_id # set date to the year beginning for new devices self.last_query = datetime(2017, 1, 1)
class Notification(db.Model): _nid = db.Column('nid', db.Integer, primary_key=True) _owner = db.Column(db.ForeignKey('user.uid')) _date = db.Column(db.DateTime) _seen = db.Column(db.Boolean) _type = db.Column(db.String(30)) __tablename__ = 'notification' __mapper_args__ = { 'polymorphic_on': _type, 'polymorphic_identity': 'base' } def __init__(self): self._date = datetime.now() self._seen = False def __eq__(self, other): if not isinstance(other, Notification): return False return abs(self.get_date() - other.get_date()) < timedelta(seconds=10) def __hash__(self): return self._nid def get_nid(self): return self._nid def get_date(self): return self._date def get_seen(self): return self._seen def set_seen(self): self._seen = True def get_timestamp(self): return mktime(self._date.timetuple()) def get_view(self): return { 'nid': self.get_nid(), 'data': self.get_data(), 'type': self.get_type(), 'seen': self.get_seen(), 'timestamp': int(self.get_timestamp() * 1000) }
class Addresses(db.Model): __tablename__: str = 'addresses' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100)) latitude = db.Column(db.Float, default=0.0) longitude = db.Column(db.Float, default=0.0) address = db.Column(db.Text) note = db.Column(db.Text) accuracy = db.Column(db.Float, default=0.0) user_id = db.Column(db.Integer, db.ForeignKey('user_detail.id')) store_id = db.Column(db.Integer, db.ForeignKey('store.id')) created_timestamp = db.Column(db.DateTime, default=datetime.now())
class Citizen(db.Model): __tablename__ = "citizen" # Keys citizen_id = db.Column(db.Integer, primary_key=True) import_id = db.Column(db.Integer, db.ForeignKey('import.import_id'), primary_key=True) # Demographics town = db.Column(db.String(256)) street = db.Column(db.String(256)) building = db.Column(db.String(256)) apartment = db.Column(db.Integer) name = db.Column(db.String(256)) birth_date = db.Column(db.DateTime) gender = db.Column(db.String(6)) as_left_edges = db.relationship( "Relative", cascade="save-update, merge, delete, delete-orphan", backref='left_citizen', primaryjoin=(Relative.left_id == citizen_id) & (Relative.import_id == import_id)) as_right_edges = db.relationship( "Relative", cascade="save-update, merge, delete, delete-orphan", backref='right_citizen', primaryjoin=(Relative.right_id == citizen_id) & (Relative.import_id == import_id)) __mapper_args__ = {"polymorphic_identity": "citizen"} # left_id = db.Column(db.Integer, db.ForeignKey('citizen.citizen_id', name="a"), primary_key=True) # left_import_id = db.Column(db.Integer, db.ForeignKey('citizen.import_id', name="a"), primary_key=True) # right_id = db.Column(db.Integer, db.ForeignKey('citizen.citizen_id', name="b"), primary_key=True) # right_import_id = db.Column(db.Integer, db.ForeignKey('citizen.import_id', name="b"), primary_key=True) #right_import_id = db.Column(db.Integer, primary_key=True) #left_citizen = db.relationship(Citizen, # primaryjoin=(left_id==Citizen.citizen_id) & (import_id == Citizen.import_id), # back_populates='as_left_edges') #right_citizen = db.relationship(Citizen, # primaryjoin=(right_id==Citizen.citizen_id) & (import_id == Citizen.import_id), # back_populates='as_right_edges') # def __init__(self, c1, c2): # if (c1.citizen_id < c2.citizen_id): # self.left_citizen = n1 # self.right_citizen = n2 # else: # self.left_citizen = n2 # self.right_citizen = n1
class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) # category_access_id = db.Column(db.Integer, db.ForeignKey("category_access.id")) username = db.Column(db.String(90), unique=True, nullable=False) email = db.Column(db.String(100), unique=True) password = db.Column(db.String(255), nullable=False) user_detail = db.relationship('UserDetail', uselist=False, backref='user') food_feed_backs = db.relationship('FoodFeedBack', backref='user', lazy=True) created_time = db.Column(db.DateTime, default=datetime.now()) def __serialize__(self, detail=False): if detail: social_medias = [] for social_media in self.user_detail.social_medias: social_medias.append({ "provider": social_media.provider, "uid": social_media.uid, "image": social_media.image }) addresses = [] for address in self.user_detail.addresses: addresses.append({ "name": address.name, "latitude": address.latitude, "longitude": address.longitude, "address": address.address, "note": address.note }) data = { "id": self.id, "username": self.username, "fullname": self.user_detail.fullname, "email": self.email, "phone": self.user_detail.phone_number, "rating": self.user_detail.ratting, "image": self.user_detail.image, "social": social_medias, "addresses": addresses } else: data = { "id": self.id, "username": self.username, "email": self.email, "driver_id": self.user_detail.driver_id } return data
class Order(db.Model): id = db.Column(db.Integer, primary_key=True) owner_id = db.Column(db.Integer) beers = db.relationship('OrderBeer', backref='order') is_open = db.Column(db.Boolean, default=True) time_created = db.Column(db.DateTime, default=datetime.utcnow) time_modified = db.Column(db.DateTime, onupdate=datetime.utcnow) @staticmethod def get_opened_order(owner_id): order = Order.query.filter_by(owner_id=owner_id, is_open=True).first() if order is None: order = Order() order.owner_id = owner_id order.is_open = True db.session.add(order) db.session.commit() return order def checkout(self): if len(self.beers) == 0: return self.is_open = False db.session.add(self) db.session.commit() def add_beer(self, sku, quantity): found = False for beer in self.beers: if beer.sku == sku: beer.quantity += quantity found = True break if not found: beer = OrderBeer() beer.sku = sku beer.quantity = quantity self.beers.append(beer) db.session.add(self) db.session.commit() def remove_beer(self, sku): OrderBeer.query.filter_by(order_id=self.id, sku=sku).delete() db.session.commit()
class ImagemPublicacao(db.Model): __tablename__ = 'publicacao_imagem' guid_imagem = db.Column(db.String(36), primary_key=True) guid_publicacao = db.Column(db.String(36), db.ForeignKey('publicacao.guid_publicacao', ondelete='CASCADE'), nullable=False) caminho = db.Column(db.String(64)) def __init__(self): self.guid_imagem = str(uuid.uuid1()) def __repr__(self): return '<ImagemPublicacao: %s>' % (self.caminho)
class BaseModel(): """ Generalize __init__, __repr__ and to_json Based on the models columns """ _created_at = db.Column(db.DateTime, nullable=False, default=datetime.now) _updated_at = db.Column(db.DateTime, nullable=True, onupdate=datetime.now) def save(self): db.session.add(self) db.session.commit() return self def delete(self): db.session.delete(self) db.session.commit()
class WikiPage(db.Model): __tablename__ = 'wiki_page' id = db.Column(db.Integer, primary_key=True) created = db.Column(db.TIMESTAMP, server_default=text('CURRENT_TIMESTAMP')) versions = db.relationship("WikiPageVersion") def __repr__(self): return '<WikiPage %s>' % self.id def get_current(self): return next( iter([ version for version in self.versions if version.status == WikiPageVersion.STATUS_CURRENT ]), None)
class Import(db.Model): __tablename__ = "import" import_id = db.Column(db.Integer, primary_key=True) citizens = db.relationship( "Citizen", cascade="save-update, merge, delete, delete-orphan") __mapper_args__ = {"polymorphic_identity": "import"}
class Cidade(db.Model): id_cidade = db.Column(db.Integer, primary_key=True) nome = db.Column(db.String(64), nullable=False) uf = db.Column(db.String(2), nullable=False) categorias = db.relationship(Categoria, backref='cidade', cascade='delete') def __init__(self, nome=None, uf=None): self.nome = nome self.uf = uf def __repr__(self): return '%s - %s' % (self.nome, self.uf) @property def serialize(self): return {'id_cidade': self.id_cidade, 'nome': self.nome, 'uf': self.uf}
class Relative(db.Model): __tablename__ = "relative" __table_args__ = ( db.ForeignKeyConstraint( ['left_id', 'import_id'], ['citizen.citizen_id', 'citizen.import_id'], ), db.ForeignKeyConstraint( ['right_id', 'import_id'], ['citizen.citizen_id', 'citizen.import_id'], ), ) left_id = db.Column(db.Integer, primary_key=True) import_id = db.Column(db.Integer, primary_key=True) right_id = db.Column(db.Integer, primary_key=True) __mapper_args__ = {"polymorphic_identity": "relative"}
class Publicacao(db.Model): guid_publicacao = db.Column(db.String(36), primary_key=True) guid_anunciante = db.Column(db.String(36), db.ForeignKey('anunciante.guid_anunciante'), nullable=False) id_categoria = db.Column(db.Integer, db.ForeignKey('categoria.id_categoria'), nullable=False) titulo = db.Column(db.Text, nullable=False) descricao = db.Column(db.Text, nullable=False) data_publicacao = db.Column(db.DateTime, nullable=False, default=db.func.current_timestamp()) data_validade = db.Column(db.DateTime, nullable=False) publicado = db.Column(db.Boolean, unique=False, default=False) anunciante = db.relationship('Anunciante') imagens = db.relationship('ImagemPublicacao', cascade='delete') def add_image(self, image_filename): image = ImagemPublicacao() image.guid_publicacao = self.guid_publicacao image.caminho = image_filename db.session.add(image) def __init__(self): self.guid_publicacao = str(uuid.uuid1()) def __repr__(self): return '<Publicacao: %s>' % (self.titulo) @property def serialize(self): return { 'guid_publicacao': self.guid_publicacao, 'guid_anunciante': self.guid_anunciante, 'id_categoria': self.id_categoria, 'titulo': self.titulo, 'descricao': self.descricao, 'data_publicacao': self.data_publicacao.strftime('%Y-%m-%d %H:%M:%S'), 'data_validade': self.data_validade.strftime('%Y-%m-%d %H:%M:%S'), 'publicado': self.publicado, 'anunciante': { 'guid_anunciante': self.guid_anunciante, 'razao_social': self.anunciante.razao_social, 'nome_fantasia': self.anunciante.nome_fantasia, 'logradouro': self.anunciante.logradouro, 'numero': self.anunciante.numero, 'telefone': self.anunciante.telefone, 'celular': self.anunciante.celular, 'email': self.anunciante.email, 'id_categoria': self.anunciante.id_categoria }, 'imagens': [imagem.caminho for imagem in self.imagens] }
class Beer(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) sku = db.Column(db.String(255), unique=True, nullable=False) price = db.Column(db.DECIMAL(precision=8, scale=2), nullable=False) image = db.Column(db.String(255), unique=False, nullable=True) time_created = db.Column(db.DateTime, default=datetime.utcnow) time_modified = db.Column(db.DateTime, onupdate=datetime.utcnow) def __repr__(self): return '<Beer %r>' % (self.username, ) @staticmethod def create(name, sku, price, image): if isinstance(image, str): image = image.strip() if not image: image = None beer = Beer() beer.name = name beer.sku = sku beer.price = price beer.image = image db.session.add(beer) db.session.commit() return beer def modify(self, name, price, image): if isinstance(image, str): image = image.strip() if not image: image = None self.name = name self.price = price self.image = image db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() @staticmethod def seed(db): Beer.create( 'Бургаско', 123456, 1.19, 'https://cdncloudcart.com/15635/products/images/206/bira-burgasko-svetlo-500-ml-ken-image_5e24491fc2a15_800x800.jpeg?1579436338' ) Beer.create( 'Загорка', 123457, 2.00, 'https://shami.bg/uploads/2019/06/38b3674a0aaee5a32c1193d8cab7104b.png' ) Beer.create( 'Tuborg', 123458, 1.50, 'https://cdn.nokovandson.com/crop/276/490/480//I0/I0pLF5nGwJ.png')
class SocialMedia(db.Model): __tablename__ = 'social_media' id = db.Column(db.Integer, primary_key=True) uid = db.Column(db.TEXT) image = db.Column(db.TEXT) provider = db.Column(db.String(90)) link = db.Column(db.TEXT) user_id = db.Column(db.Integer, db.ForeignKey('user_detail.id')) created_time = db.Column(db.DateTime, default=datetime.now())