Ejemplo n.º 1
0
    def get(self):
        apiResponse = requests.get('http://sigmatest.sigmastorage.online/')
        productDic = productSchema.load(apiResponse.json())
        inquiredProduct = Product(productDic['id'], productDic['name'],
                                  productDic['image'], productDic['price'],
                                  productDic['tax'])
        oldProduct = Product.get_by_id(inquiredProduct.id)
        if (oldProduct):
            if (not validateProductEquals(inquiredProduct, oldProduct)):
                oldProduct.name = inquiredProduct.name
                oldProduct.image = inquiredProduct.image
                oldProduct.price = inquiredProduct.price
                oldProduct.tax = inquiredProduct.tax
                oldProduct.update()
        else:
            inquiredProduct.save()

        productResponse = ProductResponse(inquiredProduct.id,
                                          inquiredProduct.name,
                                          inquiredProduct.image,
                                          inquiredProduct.price,
                                          inquiredProduct.tax)
        productResponse.tax = calculateTax(inquiredProduct)
        productResponse.discount = calculateDiscount(inquiredProduct)
        return productSchema.dump(productResponse)
Ejemplo n.º 2
0
    def get(self):
        if request.args.get('way') == "bidding":
            products = Product.objects(
                name__icontains=request.args.get('keyword'),
                bid__due_time__gt=datetime.datetime.utcnow() +
                datetime.timedelta(hours=8),
                status=0,
                bidding=True)
            way = "bidding"
        elif request.args.get('way') == "normal":
            products = Product.objects(
                name__icontains=request.args.get('keyword'),
                status=0,
                bidding=False)
            way = "normal"
        else:
            abort(404)

        if request.args.get('keyword') not in ["", None]:
            keyword = Keyword.objects(
                keyword=request.args.get('keyword')).first()
            if keyword == None:
                keyword = Keyword(keyword=request.args.get('keyword'))
            keyword.count += 1
            keyword.save()

        return render_template('search.html',
                               products=products,
                               way=way,
                               now=datetime.datetime.utcnow() +
                               datetime.timedelta(hours=8))
Ejemplo n.º 3
0
    def test_get_all_products(self):
        """ Test All products Can Be Retrieved """
        Product.seed_db()

        products = Product.all()

        self.assertEqual(len(products), 5)
Ejemplo n.º 4
0
    def get(self):
        form = ManagementForm()

        if request.args.get("status") == str(PRODUCT_STATUS["SELLING"]):
            products = Product.objects(status__in=[PRODUCT_STATUS["SELLING"]])
            status = PRODUCT_STATUS["SELLING"]
        elif request.args.get("status") == str(PRODUCT_STATUS["SOLD"]):
            products = Product.objects(status__in=[PRODUCT_STATUS["SOLD"]])
            status = PRODUCT_STATUS["SOLD"]
        elif request.args.get("status") == str(PRODUCT_STATUS["FROZEN"]):
            products = Product.objects(status__in=[PRODUCT_STATUS["FROZEN"]])
            status = PRODUCT_STATUS["FROZEN"]
        elif request.args.get("status") == str(PRODUCT_STATUS["REMOVE"]):
            products = Product.objects(status__in=[PRODUCT_STATUS["REMOVE"]])
            status = PRODUCT_STATUS["REMOVE"]
        else:
            products = Product.objects(status__in=[
                PRODUCT_STATUS["SELLING"], PRODUCT_STATUS["SOLD"],
                PRODUCT_STATUS["FROZEN"], PRODUCT_STATUS["REMOVE"]
            ])
            status = PRODUCT_STATUS["ALL"]

        return render_template('admin/management/product.html',
                               form=form,
                               status=status,
                               products=products,
                               PRODUCT_STATUS=PRODUCT_STATUS)
Ejemplo n.º 5
0
    def __call__(self, request, category_name):

        if request.is_json:

            data = request.get_json()
            owner_email = data['owner_email']
            product_name = data['name']

            owner = User.get_by_email(owner_email)
            category = Category.get_category_by_name(category_name)

            if (owner and category):
                if Product.is_product_on_category(Category, product_name,
                                                  category_name):
                    new_product = Product(name=product_name,
                                          price=data['price'],
                                          units=data['units'],
                                          owner=owner,
                                          category=category)
                    return new_product.save()
                else:
                    return response_message(
                        False,
                        f"Product {product_name} already exists on {category_name}"
                    )
            else:
                return response_message(False,
                                        "Owner or category doesn't exist")
        else:
            return response_message(
                False, "The request payload is not in JSON format")
Ejemplo n.º 6
0
 def addGoods(self, goods):
     different_count = 0
     same_count = 0
     if len(goods) > 0:
         for item in goods:
             items = Product.query.filter_by(
                 productId=item['productId']).order_by(
                     Product.create_time.desc())
             if items is not None and (items.count() > 0) and items.first(
             ) and (items.first().price == item['price']):
                 same_count += 1
             else:
                 different_count += 1
                 product_model = Product()
                 if items.count() > 0:
                     first = items.first()
                     first.latest = False
                     print('上期价格:', first.price, '本期价格:', item['price'])
                     item['compare'] = round(
                         (float(item['price']) - float(first.price)) /
                         float(first.price), 4)
                     item['latest'] = True
                 else:
                     item['compare'] = 1
                     item['latest'] = True
                 product_model.set_attrs(item)
                 db.session.add(product_model)
         db.session.commit()
     return same_count, different_count
Ejemplo n.º 7
0
    def post(self):
        form = BiddingForm()

        print('hello')
        if form.validate_on_submit():
            bid = Bid(per_price=form.per_price.data,
                      low_price=form.low_price.data,
                      now_price=form.low_price.data,
                      due_time=form.due_time.data)

            product = Product(seller_id=current_user.id,
                              name=form.name.data,
                              price=form.price.data,
                              detail=form.detail.data,
                              bid = bid,
                              image="product." + form.image.data.filename[-3:].lower(),
                              bidding=True,
                              status=0)
            product.save()

            image_path = os.path.join(os.getcwd(), 'app/static/image', str(product.id))
            os.makedirs(image_path)
            form.image.data.save(os.path.join(image_path, product.image))

            return redirect(url_for('user.profile'))
        
        return render_template('user/selling/bidding.html', form=form)
Ejemplo n.º 8
0
class ProductView():
    def __init__(self):
        """Class initialization."""

        self.model = Product()

    def display(self):
        """Method used to display page in terminal."""

        self.model.get_page()
        clear()

        print("Sélectionnez le produit:\n")
        for product in self.model.products_list:
            print(product.id, "-", product.name)

        self.footer()

    def footer(self):
        """Method used to display page footer."""

        print(f"\nPage {self.model.page}/{self.model.max_pages}")
        print(f"[p-1 à p-{self.model.max_pages}] Aller à la page")
        print("[n] Page suivante")
        print("[b] Page précédente")
        print("[1-9999] Sélectionner le produit")
        print("[q] Quitter l'application")
Ejemplo n.º 9
0
    def post(self):
        form = NormalForm()

        categories = Category.objects()
        if form.validate_on_submit():

            product = Product(seller_id=current_user.id,
                              name=form.name.data,
                              price=form.price.data,
                              detail=form.detail.data,
                              image="product." +
                              form.image.data.filename.split(".")[1].lower(),
                              categories=request.form.getlist("categories"),
                              bidding=False,
                              status=0)
            product.save()

            image_path = os.path.join(os.getcwd(), 'app/static/image',
                                      str(product.id))
            os.makedirs(image_path)
            form.image.data.save(os.path.join(image_path, product.image))

            return redirect(url_for('user.profile'))

        return render_template('user/selling/normal.html',
                               form=form,
                               categories=categories)
Ejemplo n.º 10
0
    def __init__(self, category_index: int):
        """Initialise."""
        category = Category().get_categories()[category_index]

        self.product_model = Product()
        self.products = self.product_model.get_products(category)

        self.view = ProductView(self.products)
    def get_products_by_user_id(self, user_id, name, page, per_page):
        products = []

        if not name:
            products = Product.objects(user_id=user_id)
        else:
            products = Product.objects(user_id=user_id, name__icontains=name)

        return Pagination(products, page, per_page).items
Ejemplo n.º 12
0
def opinions(product_id):
    print(product_id)
    product = Product(product_id)
    info = {}
    with open(f"app/info/{product_id}_info.json", "r", encoding="UTF-8") as fp:
            r = json.load(fp)
            info = r
    print(", ".join(op.opinion_id for op in product.opinions))
    product.read_from_json()
    return render_template('opinions.html.jinja', info=info, product=str(product))
Ejemplo n.º 13
0
    def post(self):
        form = ManagementForm()

        if form.validate_on_submit():
            user = User.objects(
                id=form.user_id.data,
                status__in=[ACCOUNT_STATUS["ACTIVE"],
                            ACCOUNT_STATUS["LOCK"]]).first()
            if user.status == ACCOUNT_STATUS["ACTIVE"]:
                user.status = ACCOUNT_STATUS["LOCK"]
                orders = Order.objects(product_id__in=Product.objects(
                    seller_id=form.user_id.data),
                                       status__in=[
                                           int(ORDER_STATUS["TRANSFERING"]),
                                           int(ORDER_STATUS["RECEIPTING"])
                                       ])
                for order in orders:
                    if order.product_id.bidding == False:
                        if order.coupon_id == None:
                            order.buyer_id.hicoin += order.product_id.price
                        else:
                            order.buyer_id.hicoin += max(
                                0, order.product_id.price -
                                order.coupon_id.discount)
                    else:
                        order.buyer_id.hicoin += order.product_id.bid.now_price
                    order.product_id.status = PRODUCT_STATUS["REMOVE"]
                    order.status = int(ORDER_STATUS["CANCEL"])
                    order.product_id.save()
                    order.buyer_id.save()
                    order.save()
                normal_products = Product.objects(
                    seller_id=form.user_id.data,
                    bidding=False,
                    status__ne=PRODUCT_STATUS["FROZEN"])
                for product in normal_products:
                    product.status = PRODUCT_STATUS["REMOVE"]
                    product.save()
                bidding_product = Product.objects(seller_id=form.user_id.data,
                                                  bidding=True,
                                                  bid__buyer_id__ne=None)
                for product in bidding_product:
                    product.status = PRODUCT_STATUS["REMOVE"]
                    if product.bid.buyer_id == None:
                        pass
                    else:
                        product.bid.buyer_id.hicoin += product.bid.now_price
                    product.save()
                user.save()
                return "解凍"
            elif user.status == ACCOUNT_STATUS["LOCK"]:
                user.status = ACCOUNT_STATUS["ACTIVE"]
                user.save()
                return "凍結"
        return "error"
Ejemplo n.º 14
0
    def test_serialize_a_product(self):
        product = Product(id=1,
                          name="Test",
                          price=1.0,
                          description="Test Description")
        product = product.serialize()

        self.assertEqual(product['id'], 1)
        self.assertEqual(product['name'], "Test")
        self.assertEqual(product['price'], 1.0)
        self.assertEqual(product['description'], "Test Description")
Ejemplo n.º 15
0
def update(pid):
    form = ProductContent().validate_for_api()
    props = validate_product_props()
    with db.auto_commit():
        Product.edit_model(pid, form.data, commit=False, throw=True)
        if props:
            ProductProperty.edit_properties(pid, props)
        if form.theme_ids.data:
            ThemeProduct.edit_themes(form.theme_ids.data, pid)
        if form.desc_img_ids.data:
            ProductImage.edit_imgs_for_product(pid, form.desc_img_ids.data)
    return Success('商品更新成功')
Ejemplo n.º 16
0
 def edit(cls, member_id, product_id, count, selected):
     models = cls.query.filter_by(member_id=member_id, soft=True).all()
     ids = [item.product_id for item in models]
     if len(models) >= 10 and product_id not in ids:
         raise ParameterException(msg='购物车最多放10种商品')
     Product.check_stock(product_id, count, throw=True)
     model = cls.query.filter_by(product_id=product_id, member_id=member_id, soft=True).first()
     if model:
         model.update(count=count, selected=selected, commit=True)
         return True
     cls.create(member_id=member_id, product_id=product_id, count=count, selected=selected, commit=True)
     return True
	def setUp(self):
		self.BaseSetUp()
		self.fake = Faker()

		self.mock_rating = ProductRating(
			id=1,
			created_at=datetime.now(),
			updated_at=datetime.now(),
			product_id=1,
			user_id=1,
			rating=1.2,
			channel='web'
		)
		self.mock_product_with_dependants = Product(
			id=1,
			created_at=datetime.now(),
			updated_at=datetime.now(),
			is_deleted=False,
			name=self.fake.name(),
			description=self.fake.name(),
			price=34.5,
			discounted_price=23.5,
			display=20,
			sold=10,
			is_active=True,
			ratings=[self.mock_rating, ],
		)
		self.mock_product = Product(
			id=1,
			created_at=datetime.now(),
			updated_at=datetime.now(),
			is_deleted=False,
			name=self.fake.name(),
			description=self.fake.name(),
			price=34.5,
			discounted_price=23.5,
			display=20,
			sold=10,
			is_active=True
		)
		self.mock_deleted_product = Product(
			id=1,
			created_at=datetime.now(),
			updated_at=datetime.now(),
			is_deleted=True,
			name=self.fake.name(),
			description=self.fake.name(),
			price=34.5,
			discounted_price=23.5,
			display=20,
			sold=10,
			is_active=True
		)
Ejemplo n.º 18
0
def handle_message(event):
    if event.message.text == None:
        products = Product.objects(status=0)
    else:
        products = Product.objects(name__icontains=event.message.text,
                                   status=0)

    carouselColumns = []

    count = 0
    for product in products:
        # imagePath ='./app/static/image/' + str(product.id) + '/' + product.image
        # if os.path.isfile(imagePath):
        #   image = imagePath
        # else:
        #   image = "https://miro.medium.com/max/2834/0*f81bU2qWpP51WWWC.jpg"
        filePath = 'image/' + str(product.id) + '/' + product.image
        if (product.bidding):
            price = "Last Bid: NT$" + str(product.bid.now_price)
        else:
            price = "NT$" + str(product.price)
        carouselColumns.append(
            CarouselColumn(
                thumbnail_image_url=request.host_url[:-1] +
                url_for('static', filename=filePath),
                title=product.name,
                text=price,
                actions=[
                    URITemplateAction(
                        label='Take a look!',
                        uri=request.host_url[:-1] +
                        url_for('show_normal', product_id=product.id))
                ]))
        count += 1
        if count > 5:
            break

    if carouselColumns:
        message = TemplateSendMessage(
            alt_text="請到 " + request.url_root[:-1] +
            url_for('search', keyword=event.message.text) + " 或",
            template=CarouselTemplate(columns=carouselColumns))
    else:
        message = TextSendMessage(text="找不到相關商品")
    line_bot_api.reply_message(event.reply_token, message)


# @LineChatbotSearch.handler.add(MessageEvent, message=TextMessage)
# def handle_message(event):
#     line_bot_api.reply_message(
#         event.reply_token,
#         TextSendMessage(text=event.message.text))
Ejemplo n.º 19
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('title',
                            required=True,
                            help='O campo título é obrigatório')
        payload = parser.parse_args()

        product = ProductModel()
        product.title = payload.title

        db.session.add(product)
        db.session.commit()

        return marshal(product, products_schema, 'product')
Ejemplo n.º 20
0
def article_list():
    meta = {
        'title': '文章管理',
        'css_nav_sub_article': 'active',
        'css_nav_article': 'active'
    }
    query = {}
    page = int(request.args.get('page', 1))
    per_page = 100
    status = int(request.args.get('status', 0))
    deleted = int(request.args.get('deleted', 0))
    page_url = url_for('admin.product_list', page="#p#", status=status)
    if status == -1:
        meta['css_disable'] = 'active'
        query['status'] = 0
    elif status == 1:
        query['status'] = 1
        meta['css_verify'] = 'active'
    elif status == 5:
        query['status'] = 5
        meta['css_success'] = 'active'
    else:
        meta['css_all'] = 'active'

    query['deleted'] = deleted

    data = Product.objects(**query).order_by('-created_at').paginate(
        page=page, per_page=per_page)
    total_count = Product.objects(**query).count()

    # 过滤数据
    for i, d in enumerate(data.items):
        if d.site_from == 0:
            data.items[i].site_from_label
            data.items[i].site_type_label
        else:
            label = platform_options(d.site_from)
            data.items[i].site_from_label = label['name']

        data.items[i].site_type_label = platform_type(d.site_type)
        data.items[i].category_tags_s = ','.join(d.category_tags)
        data.items[i].tags_s = ','.join(d.tags)

    meta['data'] = data.items

    pager = Pager(page, per_page, total_count, page_url)
    meta['pager'] = pager.render_view()

    return render_template('admin/article/list.html', meta=meta)
Ejemplo n.º 21
0
    def get(self):
        form = SearchForm()
        
        popular_products = Product.objects(bidding=False, status=0).order_by('-view')[:12]
        normal_products = Product.objects(bidding=False, status=0).order_by('-create_time')[:12]
        bidding_products = Product.objects(bid__due_time__gt=datetime.datetime.utcnow()+datetime.timedelta(hours=8),
                         bidding=True, status=0).order_by('-create_time')[:12]
        discount_products = Product.objects(bidding=False, status=0, discount__lt=1).order_by('-create_time')

        return render_template('index.html', form=form,
        				popular_products=popular_products,
         				normal_products=normal_products,
         				bidding_products=bidding_products,
                        discount_products=discount_products,
                        now=datetime.datetime.utcnow() + datetime.timedelta(hours=8))
Ejemplo n.º 22
0
def get_item_uuid(product_uuid):
    """
    Get the information from cache memory or SQL database of a product using product_uuid
    Parameters
    ----------
    product_uuid : an product uuid

    Returns
    -------
    str:
        item_uuid

    """
    try:
        if product_uuid in __item_cache:
            return __item_cache[product_uuid]
        else:
            product_resultset = Product.get(
                {'product_uuid': product_uuid},
                _cols=['product_uuid', 'item_uuid'],
                limit=1)
            if product_resultset:
                __item_cache[product_uuid] = product_resultset[0]['item_uuid']
                return __item_cache[product_uuid]
            else:
                return None
    except Exception as e:
        logger.error("func=get_item_uuid, msg={}".format(e))
        raise e
Ejemplo n.º 23
0
def get_paginate_by_theme(tid):
    start, count = paginate()
    q = request.args.get('q', None)
    res = Product.get_paginate_models(start, count, q, tid=tid, throw=True)
    for model in res['models']:
        model.hide('img_id', 'delete_time', 'category_id')
    return jsonify(res)
Ejemplo n.º 24
0
def article_view(id):
    meta = {
        'title': '文章管理',
        'css_nav_sub_product': 'active',
        'css_nav_reptile': 'active'
    }
    meta['data'] = None
    if id:
        product = Product.objects(_id=id).first()
        if not product:
            flash('产品不存在或已删除!', 'error')
            return redirect(url_for('admin.article_list'))

        product = product.to_mongo()

        if product['site_from']:
            product['site_from_label'] = platform_options(
                product['site_from'])['name']
        if product['site_type']:
            product['site_type_label'] = platform_type(product['site_type'])

        meta['title'] = product['title']
        meta['data'] = product

    return render_template('admin/article/view.html', meta=meta)
Ejemplo n.º 25
0
    def get(self, product_id):
        form = BiddingForm()
        product = Product.objects(id=product_id, bidding=True).first()
        like = "far fa-heart"

        if product == None:
            abort(404)
        if current_user.is_active:
            #update history
            information = Information.objects(user_id=current_user.id).first()
            history_product = [h['product'] for h in information.history]
            try:
                index = history_product.index(product)
                information.history[
                    index].create_time = datetime.datetime.utcnow()
            except ValueError:
                information.history.append(History(product=product))
            information.save()

            if product in information.like:
                like = "fas fa-heart"

            product.view += 1
            product.save()
        return render_template('product/bidding.html',
                               form=form,
                               product=product,
                               like=like,
                               product_json=product.to_json(),
                               now=datetime.datetime.utcnow() +
                               datetime.timedelta(hours=8))
Ejemplo n.º 26
0
def product_fetch_url():
    url = request.values.get('url', '')
    count = 0
    product = Product.objects(url=url).first()
    if product:
        count = product['grab_count']
    return jsonify(code=0, message='success!', data={ 'count': count })
Ejemplo n.º 27
0
def article_delete():
    meta = {
        'title': '文章管理',
        'css_nav_sub_product': 'active',
        'css_nav_reptile': 'active'
    }

    ids = request.values.get('ids', '')
    type = request.values.get('type', 1)
    if not ids:
        return jsonify(success=False, message='缺少请求参数!')

    try:
        arr = ids.split(',')
        for d in arr:
            product = Product.objects(_id=bson.objectid.ObjectId(d)).first()
            product.mark_delete() if product else None
    except (Exception) as e:
        return jsonify(success=False, message=str(e))

    return jsonify(success=True,
                   message='操作成功!',
                   data={
                       'ids': ids,
                       'type': type
                   },
                   redirect_to=url_for('admin.article_list'))
Ejemplo n.º 28
0
 def test_one_product_object_created_successfully(self):
     "Tests if one product can be added"
     product = Product("Sugar", 2000)
     self.assertListEqual([None, "Sugar", 2000, 1], [
         product.product_id, product.product_name, product.product_price,
         product.product_count
     ])
Ejemplo n.º 29
0
def retrieve_product(product_name):
    release_info = Product.find_by_name(product_name)
    if release_info:
        return release_info, HTTPStatus.OK
    else:
        error = f"{product_name} not found in database."
        abort(HTTPStatus.NOT_FOUND, error, status="fail")
Ejemplo n.º 30
0
 def __init__(self):
     """Init."""
     self.view: ViewSaveSubstitute = ViewSaveSubstitute()
     self.product: Product = Product()
     self.substitutes = self.product.retrieve_substitute()
     self.indexes = [str(index) for index in range(1, len(self.substitutes) + 1)]
     self.possible_commands = ["back-to-menu", s.QUIT_APP]
Ejemplo n.º 31
0
 def list(self):
     try:
         category = self.request.params['category']
     except KeyError:
         category = None
         
     if category is None or not len(Category.get(name=category)):
         category = 'suorittimet'
         
     self.set(category = category)
     self.template_name = 'products/list.html'
     self.set(tuotteet = Product.get(category = Category(name=category)))
Ejemplo n.º 32
0
def get_recent():
	count = Count().validate_for_api().count.data
	products = Product.get_most_recent(count=count)
	return Success(products)
Ejemplo n.º 33
0
def get_all_in_category():
	id = IDMustBePositiveInt().validate_for_api().id.data
	products = Product.get_product_by_category_id(id=id)
	return Success(products)
Ejemplo n.º 34
0
def delete_one(id):
	id = IDMustBePositiveInt().validate_for_api().id.data
	product = Product.get_product_detail(id=id)
	return Success()