Пример #1
0
class ManufacturerLogo(db.Model):
    __tablename__ = ProdTables.ManufacturerLogoTable
    logo_id = db.Column(db.String, primary_key=True)
    product_id = db.Column(
        db.Integer,
        db.ForeignKey(ProdTables.MarketProductTable + '.' + Labels.ProductId))
    soft_deleted = db.Column(db.Boolean, default=False)
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())

    def __init__(self, product_id):
        self.product_id = product_id
        self.logo_id = ManufacturerLogo.generateLogoId()
        db.Model.__init__(self)

    @staticmethod
    def generateLogoId():
        new_logo_id = ENVIRONMENT + "/" + IdUtil.id_generator()
        missing = ManufacturerLogo.query.filter_by(logo_id=new_logo_id).first()
        while missing is not None:
            new_logo_id = ENVIRONMENT + "/" + IdUtil.id_generator()
            missing = ManufacturerLogo.query.filter_by(
                logo_id=new_logo_id).first()
        return new_logo_id

    def toPublicDict(self):
        public_dict = {}
        public_dict['product_id'] = self.product_id
        public_dict['logo_id'] = self.logo_id
        return public_dict
Пример #2
0
class Feedback(db.Model):
	__tablename__ = ProdTables.FeedbackTable
	feedback_id = db.Column(db.Integer, primary_key = True, autoincrement = True)
	email = db.Column(db.String, nullable = False)
	name = db.Column(db.String, nullable = False)
	feedback_content = db.Column(db.String)
	category = db.Column(db.String)
	account_id = db.Column(db.String, nullable = True)
	order_id = db.Column(db.String)
	date_created  = db.Column(db.DateTime,  default=db.func.current_timestamp())
	date_modified = db.Column(db.DateTime,  default=db.func.current_timestamp(),
										   onupdate=db.func.current_timestamp())


	def __init__(self, email, name, feedback_content, category, order_id = None):
		self.name = name
		self.email = email
		self.feedback_content = feedback_content
		self.category = category
		self.order_id = order_id
		db.Model.__init__(self)
		

	def toPublicDict(self):
		public_dict = {}
		public_dict[Labels.Name] = self.name
		public_dict[Labels.Email] = self.email
		public_dict[Labels.FeedbackContent] = self.feedback_content
		public_dict[Labels.Category] = self.category
		return public_dict
Пример #3
0
class ProductVariant(db.Model):
	__tablename__ = ProdTables.ProductVariantTable
	variant_id = db.Column(db.Integer, primary_key = True, autoincrement = True)
	product_id = db.Column(db.Integer, db.ForeignKey(ProdTables.MarketProductTable + '.' + Labels.ProductId))
	inventory = db.Column(db.Integer, default = 0)
	variant_type = db.Column(db.String)
	active = db.Column(db.Boolean, default = False)
	price = db.Column(db.Integer)
	date_created  = db.Column(db.DateTime,  default=db.func.current_timestamp())
	date_modified = db.Column(db.DateTime,  default=db.func.current_timestamp(),
										   onupdate=db.func.current_timestamp())


	def __init__(self, product_id, variant_type, price, inventory = 0):
		self.product_id = product_id
		self.variant_type = variant_type
		self.price = price
		self.inventory = inventory
		db.Model.__init__(self)
		
	def updateVariant(self, variant):
		
		new_inventory = variant.get(Labels.Inventory)
		if new_inventory:
			self.inventory = new_inventory
		new_price = variant.get(Labels.Price)
		if new_price:
			self.price = new_price
		new_type = variant.get(Labels.VariantType)
		if new_type:
			self.variant_type = new_type

		db.session.commit()

	def delete(self):
		 db.session.delete(self)
		 db.session.commit()

	@staticmethod
	def activateVariant(variant_id):
		this_variant = ProductVariant.query.filter_by(variant_id = variant_id).first()
		this_variant.active = True
		db.session.commit()

	@staticmethod
	def deactivateVariant(variant_id):
		this_variant = ProductVariant.query.filter_by(variant_id = variant_id).first()
		this_variant.active = False
		db.session.commit()

	def toPublicDict(self):
		public_dict = {}
		public_dict[Labels.Inventory] = self.inventory
		public_dict[Labels.VariantType] = self.variant_type
		public_dict[Labels.ProductId] = self.product_id
		public_dict[Labels.VariantId] = self.variant_id
		public_dict[Labels.Active] = self.active
		public_dict[Labels.Price] = self.price
		return public_dict
Пример #4
0
class EmailList(db.Model):
	__tablename__ = ProdTables.EmailListTable
	email_list_id = db.Column(db.Integer, autoincrement = True, primary_key = True)
	email_list_name = db.Column(db.String, unique = True)

	def __init__(self, email_list_name):
		self.email_list_name = email_list_name
		db.Model.__init__(self)
		
	@staticmethod
	def addNewEmailList(email_list_name):
		new_email_list = EmailList(email_list_name)
		db.session.add(new_email_list)
		db.session.commit()

	@staticmethod
	def getEmailListNameById(email_list_id):
		this_list = EmailList.query.filter_by(email_list_id = email_list_id).one()
		if this_list:
			return this_list.email_list_name
		return None

	@staticmethod
	def getAllEmailListData():
		email_lists = EmailList.query.filter_by().all()
		return [email_list.toPublicDict() for email_list in email_lists]

	@staticmethod
	def getEmailListInfo(email_list_id):
		if email_list_id == None:
			return None
		return EmailList.query.filter_by(email_list_id = email_list_id).one()



	def toPublicDict(self):
		public_dict = {}
		public_dict[Labels.EmailListName] = self.email_list_name
		public_dict[Labels.EmailListId] = self.email_list_id
		subscriber_list  = EmailSubscription.getEmailListSubscribers(self.email_list_name)
		public_dict[Labels.SubscribedUsers] = subscriber_list
		public_dict[Labels.NumSubscribers] = len(subscriber_list)
		return public_dict
Пример #5
0
class LaunchListEmail(db.Model):
    __tablename__ = ProdTables.LaunchListEmailTable
    launch_list_email_id = db.Column(db.Integer,
                                     primary_key=True,
                                     autoincrement=True)
    email = db.Column(db.String)
    ip = db.Column(db.String)
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())

    # name,email, password all come from user inputs
    # email_confirmation_id, stripe_customer_id will be generated with try statements
    def __init__(self, email, ip):
        self.ip = ip
        self.email = email
        db.Model.__init__(self)

    @staticmethod
    def AddToLaunchList(email, ip):
        new_entry = LaunchListEmail(email, ip)
        db.session.add(new_entry)
        db.session.commit(new_entry)
Пример #6
0
class EmailSubscription(db.Model):
	__tablename__ = ProdTables.EmailSubscriptionTable
	email_subscription_id = db.Column(db.Integer, primary_key = True, autoincrement = True)

	email = db.Column(db.String, nullable = False)
	unsubscribe_id = db.Column(db.String, unique = True)
	email_list_name = db.Column(db.String, db.ForeignKey(ProdTables.EmailListTable + '.' + Labels.EmailListName))
	email_list_id = db.Column(db.Integer, db.ForeignKey(ProdTables.EmailListTable + '.' + Labels.EmailListId))
	date_created  = db.Column(db.DateTime,  default=db.func.current_timestamp())
	date_modified = db.Column(db.DateTime,  default=db.func.current_timestamp(),
										   onupdate=db.func.current_timestamp())


	def __init__(self, email, email_list_id, email_list_name):
		self.email = email
		self.email_list_id = email_list_id
		self.email_list_name = email_list_name
		db.Model.__init__(self)


	@staticmethod
	def generateUnsubscribeKey():
		new_unsubscribe_id = IdUtil.id_generator()
		missing = EmailSubscription.query.filter_by(unsubscribe_id = new_unsubscribe_id).one()
		while missing is not None:
			new_unsubscribe_id = IdUtil.id_generator()
			missing = User.query.filter_by(unsubscribe_id = new_unsubscribe_id).one()
		return new_unsubscribe_id

	@staticmethod
	def getEmailListSubscribers(email_list_name):
		subscribers_query = EmailSubscription.query.filter_by(email_list_name = email_list_name).all()
		return [subscriber.email for subscriber in subscribers_query]
		
	@staticmethod
	def addEmailSubscription(email, email_list_id):
		email_list_name = EmailList.getEmailListNameById(email_list_id)
		if not email_list_name:
			return None
		new_sub = EmailSubscription(email, email_list_id)
		db.session.add(new_sub)
		db.session.commit(new_sub)
		return new_sub.toPublicDict()

	def toPublicDict(self):
		public_dict = {}
		public_dict[Labels.Email] = self.email
		public_dict[Labels.EmailListId] = self.email_list_id
		public_dict[Labels.EmailListName] = self.email_list_name
		public_dict[Labels.UnsubscribeId] = self.unsubscribe_id
		return public_dict
Пример #7
0
class RelatedProductTag(db.Model):
    __tablename__ = ProdTables.RelatedProductTagTable
    product_tag_id = db.Column(db.Integer,
                               primary_key=True,
                               autoincrement=True)
    tag = db.Column(db.String)
    product_id = db.Column(
        db.Integer,
        db.ForeignKey(ProdTables.MarketProductTable + '.' + Labels.ProductId))
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())

    def __init__(self, product_id, tag):
        self.product_id = product_id
        self.tag = tag
        db.Model.__init__(self)

    def toPublicDict(self):
        public_dict = {}
        public_dict['product_id'] = self.product_id
        public_dict['tag'] = self.tag
        return public_dict
Пример #8
0
class DiscountCode(db.Model):
	__tablename__ = ProdTables.DiscountTable
	discount_id = db.Column(db.String, primary_key = True)
	discount_code = db.Column(db.String, unique = True)
	date_limit  = db.Column(db.DateTime)
	usage_limit = db.Column(db.Integer)
	free_shipping = db.Column(db.Boolean)

	# this discount should come as an integers as a percent (we'll do whole numbers)
	item_discount = db.Column(db.Integer)


	def __init__(self, discount_code, date_limit, usage_limit, free_shipping):
		self.discount_code = discount_code
		self.date_limit = date_limit
		self.usage_limit = usage_limit
		self.free_shipping = free_shipping
		db.Model.__init__(self)
Пример #9
0
class AdminUser(db.Model):
    __tablename__ = ProdTables.AdminUserTable
    admin_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String, unique=True)
    password_hash = db.Column(db.String)
    name = db.Column(db.String)
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())

    def __init__(self, username, password, name):
        self.username = username
        self.password_hash = AdminUser.argonHash(pre_hash)
        self.name = name
        db.Model.__init__(self)

    @staticmethod
    def argonHash(pre_hash):
        return argon2.using(rounds=4).hash(pre_hash)

    @staticmethod
    def argonCheck(pre_hash, post_hash):
        return argon2.verify(pre_hash, post_hash)

    @staticmethod
    def checkLogin(username, password):
        admin_user = AdminUser.query.filter_by(username=username).first()
        if not admin_user:
            return False

        return AdminUser.argonCheck(password, admin_user.password_hash)

    @staticmethod
    def getRecentLoginAttemps():
        return 0

    def toPublicDict(self):
        public_dict = {}
        public_dict[Labels.Username] = self.username
        public_dict[Labels.DateCreated] = self.date_created
        public_dict[Labels.Name] = self.name
        public_dict[Labels.IsAdmin] = True
        return public_dict
Пример #10
0
class HttpRequest(db.Model):
    __tablename__ = ProdTables.HttpRequestTable
    request_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    request_path = db.Column(db.String)
    time_spent = db.Column(db.Float)
    ip = db.Column(db.String)
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())

    # name,email, password all come from user inputs
    # email_confirmation_id, stripe_customer_id will be generated with try statements
    def __init__(self, request_path, time_spent, ip):
        self.request_path = request_path
        self.time_spent = time_spent
        self.ip = ip
        db.Model.__init__(self)

    @staticmethod
    def recordHttpRequest(request_path, time_spent, ip):
        new_request = HttpRequest(request_path, time_spent, ip)
        db.session.add(new_request)
        db.session.commit()
Пример #11
0
class Request(db.Model):
    __tablename__ = ProdTables.UserRequestTable
    request_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String, nullable=False)
    name = db.Column(db.String, nullable=False)
    description = db.Column(db.String)
    price_range = db.Column(db.String)
    phone_number = db.Column(db.String)
    completed = db.Column(db.Boolean, default=False)
    confirmed = db.Column(db.Boolean, default=False)
    confirmation_id = db.Column(db.String, unique=True)
    account_id = db.Column(db.String, nullable=True)
    soft_deleted = db.Column(db.Boolean)
    date_completed = db.Column(db.DateTime)
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())

    def __init__(self,
                 email,
                 name,
                 description,
                 price_range,
                 phone_number,
                 account_id=None):
        self.confirmation_id = Request.generateConfirmationId()
        self.name = name
        self.email = email
        self.description = description
        self.price_range = price_range
        self.phone_number = phone_number
        self.account_id = account_id
        db.Model.__init__(self)

    @staticmethod
    def generateConfirmationId():
        new_confirmation_id = IdUtil.id_generator()
        missing = Request.query.filter_by(
            confirmation_id=new_confirmation_id).first()
        while missing is not None:
            new_confirmation_id = IdUtil.id_generator()
            missing = Request.query.filter_by(
                confirmation_id=new_confirmation_id).first()
        return new_confirmation_id

    def toPublicDict(self):
        public_dict = {}
        public_dict[Labels.Name] = self.name
        public_dict[Labels.Email] = self.email
        public_dict[Labels.Description] = self.description
        public_dict[Labels.PriceRange] = self.price_range
        public_dict[Labels.Confirmed] = self.confirmed
        public_dict[Labels.Completed] = self.completed
        public_dict[Labels.DateCreated] = self.date_created
        public_dict[Labels.RequestId] = self.request_id
        public_dict[Labels.DateCompleted] = self.date_completed
        return public_dict
Пример #12
0
class OrderItem(db.Model):
    __tablename__ = ProdTables.OrderItemTable
    primary_key = db.Column(db.Integer, primary_key=True, autoincrement=True)

    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())
    price = db.Column(db.Integer)
    num_items = db.Column(db.Integer)
    variant_id = db.Column(db.Integer)
    name = db.Column(db.String)
    main_image = db.Column(db.String)
    product_id = db.Column(
        db.Integer,
        db.ForeignKey(ProdTables.MarketProductTable + '.' + Labels.ProductId))
    account_id = db.Column(
        db.Integer,
        db.ForeignKey(ProdTables.UserInfoTable + '.' + Labels.AccountId))
    # order_id = db.Column(db.String)
    order_id = db.Column(
        db.String, db.ForeignKey(ProdTables.OrderTable + "." + Labels.OrderId))

    # name,email, password all come from user inputs
    # email_confirmation_id, stripe_customer_id will be generated with try statements
    def __init__(self,
                 order_id,
                 user,
                 product,
                 num_items=1,
                 variant_id=None,
                 variant_type=None):
        self.order_id = order_id
        self.price = product.price

        self.num_items = num_items

        if variant_type:
            self.name = product.name + " - " + variant_type
        else:
            self.name = product.name
        self.product_id = product.product_id
        self.account_id = user.account_id
        self.variant_id = variant_id
        self.main_image = product.main_image
        this_order = Order.query.filter_by(order_id=order_id).first()
        if this_order:
            self.date_created = this_order.date_created
        db.Model.__init__(self)

    def toPublicDict(self):
        public_dict = {}
        public_dict[Labels.OrderId] = self.order_id
        public_dict[Labels.NumItems] = self.num_items
        public_dict[Labels.Price] = self.price
        public_dict[Labels.TotalPrice] = self.price * self.num_items
        public_dict[Labels.DateCreated] = self.date_created
        public_dict[Labels.ProductId] = self.product_id
        public_dict[Labels.VariantId] = self.variant_id
        public_dict[Labels.Name] = self.name
        public_dict[Labels.MainImage] = self.main_image

        return public_dict
Пример #13
0
class Order(db.Model):
    __tablename__ = ProdTables.OrderTable
    order_id = db.Column(db.String, primary_key=True)
    items_price = db.Column(db.Integer)
    order_shipping = db.Column(db.Integer)
    sales_tax_price = db.Column(db.Integer, default=0)
    total_price = db.Column(db.Integer)
    refund_date = db.Column(db.DateTime)
    stripe_customer_id = db.Column(db.String, nullable=False)
    stripe_charge_id = db.Column(db.String)
    lob_address_id = db.Column(db.String)
    address_line1 = db.Column(db.String)
    address_line2 = db.Column(db.String)
    address_zip = db.Column(db.String)
    address_country = db.Column(db.String)
    address_city = db.Column(db.String)
    address_name = db.Column(db.String)
    address_description = db.Column(db.String)
    address_state = db.Column(db.String)
    card_last4 = db.Column(db.String)
    card_brand = db.Column(db.String)
    discounts = db.Column(db.Integer)

    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())

    account_id = db.Column(
        db.Integer,
        db.ForeignKey(ProdTables.UserInfoTable + '.' + Labels.AccountId))

    def __init__(self, user, cart, address):
        self.order_id = self.generateOrderId()
        self.items_price = cart.getCartItemsPrice()
        self.order_shipping = cart.getCartShippingPrice(address)
        self.account_id = user.account_id
        self.stripe_customer_id = user.stripe_customer_id
        self.lob_address_id = address.id
        self.sales_tax_price = cart.getCartSalesTaxPrice(address)
        self.address_name = address.name
        self.address_description = address.description
        self.address_city = address.address_city
        self.address_country = address.address_country
        self.address_line1 = address.address_line1
        self.address_line2 = address.address_line2
        self.address_zip = address.address_zip
        self.address_state = address.address_state
        self.total_price = self.items_price + self.order_shipping + self.sales_tax_price
        self.discounts = cart.toPublicDict().get(Labels.Discounts)
        db.Model.__init__(self)

    @staticmethod
    def getOrderById(order_id):
        this_order = Order.query.filter_by(order_id=order_id).first()
        if this_order:
            return this_order
        else:
            return None

    def addItems(self, this_user, this_cart, address):
        # record this transaction for each product (enabling easier refunds), but group by quantity
        for cart_item in this_cart.items:
            # update the inventory
            this_product = MarketProduct.query.filter_by(
                product_id=cart_item.product_id).first()
            if cart_item.variant_type:
                this_variant = ProductVariant.query.filter_by(
                    variant_id=cart_item.variant_id).first()
                if this_variant:
                    new_inventory = this_variant.inventory - cart_item.num_items
                    if new_inventory < 0:
                        error_message = str(this_product.name) + " " + str(cart_item.variant_type) + " is out of stock. You can only purchase " \
                         + str(this_variant.inventory) + ". Please adjust your quantity and try again"
                        return {
                            Labels.Error: error_message,
                            Labels.Inventory: this_variant.inventory,
                            Labels.CartItem: cart_item
                        }
                    else:
                        this_variant.inventory = new_inventory

                else:
                    return {
                        Labels.Error:
                        "Seems like you tried to order a type that doesn't exist. Check your cart and try again."
                    }
            else:
                new_inventory = this_product.inventory - cart_item.num_items
                if new_inventory < 0:
                    error_message = str(this_product.name) + " is out of stock. You can only purchase " + str(this_product.inventory) \
                     + ". Please adjust your quantity and try again"
                    return {
                        Labels.Error: error_message,
                        Labels.Inventory: this_product.inventory,
                        Labels.CartItem: cart_item
                    }

                else:
                    this_product.inventory = new_inventory

            order_shipping = this_cart.getCartShippingPrice(address)
            new_order_item = OrderItem(self.order_id, this_user, this_product,
                                       cart_item.num_items,
                                       cart_item.variant_id,
                                       cart_item.variant_type)
            db.session.add(new_order_item)
        return None

    @staticmethod
    def generateOrderId():
        new_order_id = IdUtil.id_generator()
        missing = Order.query.filter_by(order_id=new_order_id).first()
        while missing:
            new_order_id = IdUtil.id_generator()
            missing = OrderItem.query.filter_by(order_id=new_order_id).first()
        return new_order_id

    def updateCharge(self, charge):
        self.stripe_charge_id = charge[Labels.Id]
        self.card_last4 = charge[Labels.Source][Labels.Last4]
        self.card_brand = charge[Labels.Source][Labels.Brand]
        db.session.commit()

    def toPublicDict(self):
        public_dict = {}
        public_dict[Labels.OrderId] = self.order_id

        order_items = OrderItem.query.filter(
            OrderItem.order_id == self.order_id,
            OrderItem.num_items > 0).all()
        public_dict[Labels.Items] = [
            item.toPublicDict() for item in order_items
        ]
        public_dict[Labels.ItemsPrice] = self.items_price
        public_dict[Labels.OrderShipping] = self.order_shipping
        public_dict[Labels.TotalPrice] = self.total_price
        public_dict[Labels.DateCreated] = self.date_created
        address = {
            Labels.AddressName: self.address_name,
            Labels.AddressDescription: self.address_description,
            Labels.AddressCity: self.address_city,
            Labels.AddressCountry: self.address_country,
            Labels.AddressLine1: self.address_line1,
            Labels.AddressLine2: self.address_line2,
            Labels.AddressZip: self.address_zip,
            Labels.AddressState: self.address_state
        }
        public_dict[Labels.Address] = address
        public_dict[Labels.CardLast4] = self.card_last4
        public_dict[Labels.CardBrand] = self.card_brand
        public_dict[Labels.SalesTaxPrice] = self.sales_tax_price
        public_dict[Labels.Discounts] = self.discounts
        # public_dict[Labels.Card] = StripeManager.getCardFromChargeId(self.stripe_charge_id)

        return public_dict
Пример #14
0
class AdminAction(db.Model):
    __tablename__ = ProdTables.AdminActionTable
    admin_action_id = db.Column(db.Integer,
                                primary_key=True,
                                autoincrement=True)
    username = db.Column(db.String)
    ip = db.Column(db.String)
    success = db.Column(db.Boolean)
    request_path = db.Column(db.String)
    error_message = db.Column(db.String)
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())

    # name,email, password all come from user inputs
    # email_confirmation_id, stripe_customer_id will be generated with try statements
    def __init__(self,
                 username,
                 request_path,
                 ip,
                 success,
                 error_message=None):
        self.username = username
        self.ip = ip
        self.success = success
        self.request_path = request_path
        self.error_message = error_message
        db.Model.__init__(self)

    @staticmethod
    def addAdminAction(admin_user,
                       request_path,
                       ip,
                       success,
                       error_message=None):
        if admin_user:
            username = admin_user.get(Labels.Username)
        else:
            username = None
        admin_action = AdminAction(username, request_path, ip, success,
                                   error_message)
        db.session.add(admin_action)
        db.session.commit()

    @staticmethod
    def getRecentAttempts(ip):
        now = datetime.datetime.now()
        before = now - timedelta(minutes=MINUTE_THRESHOLD)

        return 0

    def toPublicDict(self):
        public_dict = {}
        public_dict[Labels.ActionId] = self.action_id
        public_dict[Labls.Username] = self.username
        public_dict[Labels.DateCreated] = self.date_created
        public_dict[Labels.Ip] = self.ip
        public_dict[Labels.Success] = self.success
        public_dict[Labels.RequestPath] = self.request_path
        public_dict[Labels.ErrorMessage] = self.error_message
        return public_dict
Пример #15
0
class CartItem(db.Model):
    __tablename__ = ProdTables.ShoppingCartTable
    cart_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    account_id = db.Column(
        db.Integer,
        db.ForeignKey(ProdTables.UserInfoTable + '.' + Labels.AccountId))
    product_id = db.Column(
        db.Integer,
        db.ForeignKey(ProdTables.MarketProductTable + '.' + Labels.ProductId))
    num_items = db.Column(db.Integer)
    num_items_limit = db.Column(db.Integer)
    variant_id = db.Column(db.String)
    variant_type = db.Column(db.String)
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())

    def __init__(self,
                 account_id,
                 product_id,
                 num_items,
                 variant_id=None,
                 variant_type=None):
        self.account_id = account_id
        self.product_id = product_id
        self.num_items = num_items
        self.variant_id = variant_id
        self.variant_type = variant_type
        self.num_items_limit = MarketProduct.query.filter_by(
            product_id=product_id).first().num_items_limit
        db.Model.__init__(self)

    # called with a try statement
    def updateCartQuantity(self, new_num_items):
        # confirm num_items is an integer
        assert (new_num_items >= 0)
        assert (new_num_items % 1 == 0)
        if new_num_items == 0:
            self.deleteItem()
        elif new_num_items > self.num_items_limit:
            raise Exception("You've reached your limit for this product (" +
                            str(self.num_items_limit) +
                            "). You are now at your limit.")
        else:
            self.num_items = new_num_items
        db.session.commit()

    def deleteItem(self):
        CartItem.query.filter_by(cart_id=self.cart_id).delete()
        db.session.commit()

    def toPublicDict(self):
        public_dict = {}
        public_dict[Labels.CartId] = self.cart_id
        public_dict[Labels.NumItems] = self.num_items
        public_dict[Labels.ProductId] = self.product_id
        public_dict[Labels.AccountId] = self.account_id
        public_dict[Labels.NumItemsLimit] = min(self.num_items_limit,
                                                self.num_items)
        public_dict[Labels.VariantId] = self.variant_id
        return public_dict
Пример #16
0
class MarketProduct(db.Model):
	__tablename__ = ProdTables.MarketProductTable
	INTEGER_INPUTS = [Labels.Price, Labels.Inventory, Labels.NumItemsLimit, Labels.ProductTemplate]
	product_id = db.Column(db.Integer, primary_key = True, autoincrement = True)
	name = db.Column(db.String, default = "Sample Name")
	price = db.Column(db.Integer, default = 0)
	category = db.Column(db.String, default = "Sample Category")
	description = db.Column(db.String, default = "Sample Description")
	num_images = db.Column(db.Integer, nullable = False, default = 0)
	main_image = db.Column(db.String)
	inventory = db.Column(db.Integer, default = 0)
	active = db.Column(db.Boolean, default = False)
	manufacturer = db.Column(db.String, default = "Sample Manufacturer")
	manufacturer_email = db.Column(db.String, default = "*****@*****.**")
	num_items_limit = db.Column(db.Integer, default = 50)
	has_variants = db.Column(db.Boolean, default = False)
	variant_type_description = db.Column(db.String, default = "type")
	live = db.Column(db.Boolean, default = False)
	product_template = db.Column(db.Integer, default = 2)

	second_tab_name = db.Column(db.String)
	second_tab_text = db.Column(db.String)
	
	quadrant1 = db.Column(db.String)
	quadrant2 = db.Column(db.String)
	quadrant3 = db.Column(db.String)
	quadrant4 = db.Column(db.String)

	show_manufacturer_logo = db.Column(db.Boolean, default = False)
	manufacturer_logo_id = db.Column(db.String)

	sale_text_product = db.Column(db.String)
	sale_text_home = db.Column(db.String)

	# this value is stored in ten thousands
	# so 500 => 5%
	manufacturer_fee = db.Column(db.Integer)

	sale_end_date = db.Column(db.DateTime)
	date_created  = db.Column(db.DateTime,  default=db.func.current_timestamp())
	date_modified = db.Column(db.DateTime,  default=db.func.current_timestamp(),
										   onupdate=db.func.current_timestamp())

	# add relationships 
	search_tag = db.relationship("ProductSearchTag", backref = ProdTables.ProductSearchTagTable, lazy='dynamic')
	listing_tag = db.relationship("ProductListingTag", backref = ProdTables.ProductListingTagTable, lazy='dynamic')
	related_product_tag = db.relationship("RelatedProductTag", backref = ProdTables.RelatedProductTagTable, lazy='dynamic')
	image_id = db.relationship("ProductImage", backref = ProdTables.ImageTable, lazy='dynamic')


	def __init__(self, name):
		self.name = name
		db.Model.__init__(self)
		
	def getProductImages(self):
		images = ProductImage.query.filter_by(product_id = self.product_id).all()
		image_list = list()
		for image in images:
			if not image.soft_deleted:
				image_dict = image.toPublicDict()
				image_list.append(image_dict)
		return image_list

	@staticmethod
	def getAllProducts():
		products = MarketProduct.query.filter_by().all()
		return [product.toPublicDict() for product in products]

	@staticmethod
	def getActiveProducts():
		åctive_products = MarketProduct.query.filter_by(active = True).all()
		return [product.toPublicDict() for product in active_products]

	def addProductImage(self, image_decoded, set_as_main_image = False):
		# record the image_id in the database
		image_record = ProductImage(self.product_id)
		# sets this image to main image if does not exist
		if len(self.getProductImages()) == 0:
			self.main_image = image_record.image_id
		# upload the image to S3
		S3.uploadProductImage(image_record.image_id, image_decoded)
		db.session.add(image_record)
		db.session.commit()

	def addManufacturerLogo(self, image_decoded):
		# record the image_id in the database
		manufacturer_logo = ManufacturerLogo(self.product_id)
		self.manufacturer_logo_id = manufacturer_logo.logo_id
		db.session.add(manufacturer_logo)
		db.session.commit()

		# upload the image to S3
		S3.uploadManufacturerLogo(manufacturer_logo.logo_id, image_decoded)

	def activateProduct(self):
		self.active = True
		db.session.commit()

	def deactivateProduct(self):
		self.active = False
		db.session.commit()

	def addProductVariant(self, variant_type, price, inventory = 0):
		new_variant = ProductVariant(self.product_id, variant_type, price, inventory)
		db.session.add(new_variant)
		db.session.commit()

	
	def addProductVariants(self, variant_types):
		# we can either check if it is a product that has variants
		# or we can automatically make it one through this process
		assert(self.has_variants)
		assert(variant_types)
		for variant_type in variant_types:
			self.addProductVariant(variant_type)

	def getProductVariants(self):
		variants = ProductVariant.query.filter_by(product_id = self.product_id).all()
		return variants

	def getProductVariant(self, variant_id):
		variant = ProductVariant.query.filter_by(product_id = self.product_id, variant_id = variant_id).first()
		return variant

	@staticmethod
	def getProductById(product_id):
		return MarketProduct.query.filter_by(product_id = product_id).first()

	@staticmethod
	def getProductsByListingTag(tag):
		tag_matches = ProductListingTag.query.filter_by(tag = tag).all()
		product_matches = []
		for match in tag_matches:
			matching_product = MarketProduct.query.filter_by(active = True, product_id = match.product_id).first()
			if matching_product:
				product_matches.append(matching_product)
		return product_matches

	@staticmethod
	def getProductsBySearchTag(tag):
		tag_matches = ProductSearchTag.query.filter_by(tag = tag).all()
		product_matches = []
		for match in tag_matches:
			matching_product = MarketProduct.query.filter_by(active = True, product_id = match.product_id).first()
			if matching_product:
				product_matches.append(matching_product)
		return product_matches

	@staticmethod
	def getProductsByRelatedProductsTag(tag):
		tag_matches = RelatedProductTag.query.filter_by(tag = tag).all()
		product_matches = []
		for match in tag_matches:
			matching_product = MarketProduct.query.filter_by(active = True, product_id = match.product_id).first()
			if matching_product:
				product_matches.append(matching_product)
		return product_matches

	def getRelatedProductsByTag(self):
		this_product_tags = RelatedProductTag.query.filter_by(product_id = self.product_id).all()
		if len(this_product_tags) == 0:
			return []
			
		merged_list = list()
		for tag in this_product_tags:
			product_matches = MarketProduct.getProductsByRelatedProductsTag(tag.tag)
			merged_list = merged_list + product_matches 
		hit_product_ids = list()
		all_matches = list()
		# remove duplicates from the merged list
		for product in merged_list:
			if product.product_id != self.product_id:
				if product.product_id not in hit_product_ids:
					all_matches.append(product)
					hit_product_ids.append(product.product_id)

		random.shuffle(all_matches)
		# this 0:5 is hard coded as a limit for now, will discuss limits 
		# and filters moving forward
		return all_matches[0:5]


	# tags input taken as a list of tags
	def updateProductSearchTags(self, tags):
		old_tags = ProductTag.query.filter_by(product_id = self.product_id).all()
		for old_tag in old_tags:
			db.session.delete(old_tag)
		db.session.commit()

		for tag in tags:
			new_tag = ProductTag(self.product_id, tag)
			db.session.add(new_tag)
		db.session.commit()

	# tags input taken as a list of tags
	def updateProductSearchTags(self, tags):
		old_tags = ProductSearchTag.query.filter_by(product_id = self.product_id).all()
		for old_tag in old_tags:
			db.session.delete(old_tag)
		db.session.commit()

		for tag in tags:
			new_tag = ProductSearchTag(self.product_id, tag)
			db.session.add(new_tag)
		db.session.commit()

	# tags input taken as a list of tags
	def updateProductListingTags(self, tags):
		old_tags = ProductListingTag.query.filter_by(product_id = self.product_id).all()
		for old_tag in old_tags:
			db.session.delete(old_tag)
		db.session.commit()

		for tag in tags:
			new_tag = ProductListingTag(self.product_id, tag)
			db.session.add(new_tag)
		db.session.commit()

	# tags input taken as a list of tags
	def updateRelatedProductTags(self, tags):
		old_tags = RelatedProductTag.query.filter_by(product_id = self.product_id).all()
		for old_tag in old_tags:
			db.session.delete(old_tag)
		db.session.commit()

		for tag in tags:
			new_tag = RelatedProductTag(self.product_id, tag)
			db.session.add(new_tag)
		db.session.commit()


	def toPublicDict(self):
		public_dict = {}
		public_dict[Labels.Name] = self.name
		public_dict[Labels.Price] = self.price
		public_dict[Labels.Category] = self.category
		public_dict[Labels.Description] = self.description
		public_dict[Labels.Manufacturer] = self.manufacturer
		public_dict[Labels.Inventory] = self.inventory
		if self.sale_end_date:
			public_dict[Labels.SaleEndDate] = self.sale_end_date.strftime("%Y-%m-%dT%H:%M")
		else:
			public_dict[Labels.SaleEndDate] = None
		public_dict[Labels.DateCreated] = self.date_created
		
		public_dict[Labels.ProductId] = self.product_id
		images = self.getProductImages()
		public_dict[Labels.Images] = images
		public_dict[Labels.NumImages] = len(images)
		public_dict[Labels.MainImage] = self.main_image
		public_dict[Labels.ProductTemplate] = self.product_template
		public_dict[Labels.NumItemsLimit] = self.num_items_limit
		public_dict[Labels.Active] = self.active
		public_dict[Labels.HasVariants] = self.has_variants
		public_dict[Labels.Live] = self.live
		public_dict[Labels.ManufacturerLogoId] = self.manufacturer_logo_id
		public_dict[Labels.ShowManufacturerLogo] = self.show_manufacturer_logo
		public_dict[Labels.SaleTextProduct] = self.sale_text_product
		public_dict[Labels.SaleTextHome] = self.sale_text_home
		public_dict[Labels.ManufacturerEmail] = self.manufacturer_email
		public_dict[Labels.ManufacturerFee] = self.manufacturer_fee
		public_dict[Labels.Quadrant1] = self.quadrant1
		public_dict[Labels.Quadrant2] = self.quadrant2
		public_dict[Labels.Quadrant3] = self.quadrant3
		public_dict[Labels.Quadrant4] = self.quadrant4
		
		product_search_tags = ProductSearchTag.query.filter_by(product_id = self.product_id).all()
		related_product_tags = RelatedProductTag.query.filter_by(product_id = self.product_id).all()
		product_listing_tags = ProductListingTag.query.filter_by(product_id = self.product_id).all()
		public_dict[Labels.RelatedProductTags] = ",".join([tag.tag for tag in related_product_tags])
		public_dict[Labels.ProductSearchTags] = ",".join([tag.tag for tag in product_search_tags])
		public_dict[Labels.ProductListingTags] = ",".join([tag.tag for tag in product_listing_tags])

		public_dict[Labels.VariantTypeDescription] = self.variant_type_description
		variants = ProductVariant.query.filter_by(product_id = self.product_id).all()
		public_dict[Labels.Variants] = [variant.toPublicDict() for variant in variants]
		return public_dict
Пример #17
0
class LoginAttempt(db.Model):
    __tablename__ = ProdTables.LoginAttemptTable
    attempt_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String)
    ip = db.Column(db.String)
    success = db.Column(db.Boolean)
    is_admin = db.Column(db.Boolean)
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())

    # name,email, password all come from user inputs
    # email_confirmation_id, stripe_customer_id will be generated with try statements
    def __init__(self, username, ip, success, is_admin):
        self.username = username
        self.ip = ip
        self.success = success
        self.is_admin = is_admin
        db.Model.__init__(self)

    @staticmethod
    def getRecentLoginAttempts(ip):
        interval_start = datetime.datetime.utcnow() - datetime.timedelta(
            minutes=MINUTE_LIMIT)
        login_query = LoginAttempt.query.filter_by(ip=ip, success=False).all()
        num_recent_logins = 0
        for login in login_query:
            if login.date_created > interval_start:
                num_recent_logins = num_recent_logins + 1
        return num_recent_logins

    @staticmethod
    def getUnblockedLoginTime(ip):
        last_logins = LoginAttempt.query.filter_by(ip=ip, success=False).all()
        sorted_logins = sorted(last_logins,
                               key=lambda x: x.date_created,
                               reverse=True)
        if len(sorted_logins) > LOGIN_LIMIT:
            return sorted_logins[LOGIN_LIMIT].date_created + datetime.timedelta(
                minutes=MINUTE_LIMIT)
        else:
            return None

    @staticmethod
    def blockIpAddress(ip):
        num_recent_logins = LoginAttempt.getRecentLoginAttempts(ip)
        return (num_recent_logins > LOGIN_LIMIT)

    @staticmethod
    def addLoginAttempt(username, ip, success, is_admin):
        login_attempt = LoginAttempt(username, ip, success, is_admin)
        db.session.add(login_attempt)
        db.session.commit()

    def toPublicDict(self):
        public_dict = {}
        public_dict[Labels.AttemptId] = self.attempt_id
        public_dict[Labls.Username] = self.username
        public_dict[Labels.DateCreated] = self.date_created
        public_dict[Labels.Ip] = self.ip
        public_dict[Labels.Success] = self.success
        public_dict[Labels.IsAdmin] = self.is_admin
        return public_dict