Beispiel #1
0
def newProduct():
	user = getCurrentUser()
	# Only logged in users can add a product
	if user is not None:
		categories = session.query(Category).order_by(Category.name).all()
		form = ProductForm(request.form)
		form.category_id.choices = \
			[(category.id, category.name) for category in categories]
		if form.validate_on_submit():
			product = Product()
			form.populate_obj(product)
			if 'image' in request.files and \
					request.files['image'].filename != '':
				image = request.files['image']
				product.imageName = secure_filename(image.filename)
				appDir = flask.config['APP_DIR']
				path = os.path.join(flask.config['APP_DIR'], 'server/static/product_images/%s' % product.imageName)
				image.save(path)
			product.seller = user
			try:
				session.add(product)
				session.commit()
			except:
				session.rollback()
				return 'Failed to add record. Please make sure to pick a unique name.'
			return redirect(url_for('userProfile', user_id = user.id))
		else:
			return render_template('new-product.html', currentUser = user, 
				form = form)
	else:
		return redirect(url_for('home'))
Beispiel #2
0
def newProduct():
    user = getCurrentUser()
    # Only logged in users can add a product
    if user is not None:
        categories = session.query(Category).order_by(Category.name).all()
        form = ProductForm(request.form)
        form.category_id.choices = \
         [(category.id, category.name) for category in categories]
        if form.validate_on_submit():
            product = Product()
            form.populate_obj(product)
            if 'image' in request.files and \
              request.files['image'].filename != '':
                image = request.files['image']
                product.imageName = secure_filename(image.filename)
                appDir = flask.config['APP_DIR']
                path = os.path.join(
                    flask.config['APP_DIR'],
                    'server/static/product_images/%s' % product.imageName)
                image.save(path)
            product.seller = user
            try:
                session.add(product)
                session.commit()
            except:
                session.rollback()
                return 'Failed to add record. Please make sure to pick a unique name.'
            return redirect(url_for('userProfile', user_id=user.id))
        else:
            return render_template('new-product.html',
                                   currentUser=user,
                                   form=form)
    else:
        return redirect(url_for('home'))
Beispiel #3
0
    async def search(cls, params: SearchParams) -> List[Product]:
        response = await cls.get(
            f'https://lacoste.ru/api/catalog.php?q={params.query}&perPage={params.size}'
        )
        items = response.get('list', [])

        result_items: List[Product] = []
        for item in items:
            item_code = item['code']

            response = await cls.get(
                f"https://lacoste.ru/api/catalog.php?ELEMENT_CODE={item_code}")
            description = response['item']['catDesc']

            result_items.append(
                Product(
                    search_query=params.query,
                    title=item['name'],
                    price=parse_float(item['prices']['current']),
                    image_url=f"https:{item['images'][0]}",
                    product_url=
                    f"https://lacoste.ru/catalog/{item['sec_code']}/{item_code}/",
                    description=description,
                    site_logo=cls.logo,
                ))

        return result_items
Beispiel #4
0
    async def search(cls, params: SearchParams) -> List[Product]:
        response = await cls.get(
            f'https://esapi.samsung.com/search/query/v6?start=0&num={params.size}&categoryTab=all&searchValue={params.query}&siteCd=ru'
        )

        items = response['response']['resultData']['resultList']

        if not items:
            return []

        items = list(
            filter(lambda item: item['contentSource'] == 'Products',
                   items[0]['contentList']))

        result_items = []

        for item in items:
            model = item['modelList'][0]

            result_items.append(
                Product(
                    search_query=params.query,
                    title=clean_html(item['title']),
                    price=parse_float(model['priceCurrency']),
                    image_url=
                    f"https://images.samsung.com/is/image/samsung/{model['galleryImage'][0]}",
                    product_url=
                    f"https://www.samsung.com{model['originPdpUrl']}",
                    description=clean_html(item['displaySortTitle']),
                    site_logo=cls.logo))

        return result_items
Beispiel #5
0
    async def search(cls, params: SearchParams) -> List[Product]:
        response = await cls.get(
            f'https://api.apteka.ru/Search/ByPhrase?phrase={params.query}&pageSize={params.size}'
        )
        try:
            items = response.get('result')
        except AttributeError:
            return []

        if not items:
            return []

        result_items: List[Product] = []
        for item in items:
            item_id = item['id']

            response = await cls.get(
                f"https://api.apteka.ru/Item/Info?id={item_id}/")
            description = response.get('genDesc', '')

            result_items.append(
                Product(
                    search_query=params.query,
                    title=clean_html(item['tradeName']),
                    price=item['minPrice'],
                    image_url=item['photos'][0]['original'],
                    product_url=f"https://apteka.ru/product/{item_id}/",
                    description=description,
                    site_logo=cls.logo,
                ))

        return result_items
Beispiel #6
0
    async def search(cls, params: SearchParams) -> List[Product]:
        response = await cls.get(
            f'https://www.auchan.ru/v1/search?merchantId=1&query={params.query}'
        )
        items = response.get('items')

        if not items:
            return []

        items = list(chain(*[value['products'] for value in items.values()]))[:3]

        result_items: List[Product] = []
        for item in items:
            item_code = item['code']

            response = await cls.get(
                f"https://www.auchan.ru/v1/catalog/product-detail?code={item_code}&merchantId=1"
            )
            description = response['description']['content']

            result_items.append(
                    Product(
                    search_query=params.query,
                    title=item['name'],
                    price=item['price']['value'],
                    image_url=f"https://www.auchan.ru/files/compressed/{item['image']['id']}/",
                    product_url=f"https://www.auchan.ru/product/{item['code']}/",
                    description=description,
                    site_logo=cls.logo,
                )
            )

        return result_items
Beispiel #7
0
    def post(self, request):
        ret = {"code": 0, 'next_url': reverse("product_manage")}

        form = ProductForm(request.POST)
        if form.is_valid():
            try:
                product = Product(**form.cleaned_data)
                product.save()

            except Exception as e:
                msg = "用户{} 业务线出错:{}".format(request.user.username, e.args)
                logger.error(msg)
                ret['code'] = 1
                ret['errmsg'] = msg

        else:
            msg = "用户{} 添加业务线验证失败:{}".format(request.user.username,
                                             form.errors)
            logger.error(msg)

            ret['code'] = 1
            ret['errmsg'] = msg

        return render(request, settings.JUMP_PAGE, ret)
Beispiel #8
0
def create_product():
    data = request.json
    try:
        name = data.get("name")
        store = data.get("storeId")
        brand = data.get("brand")
        productExist = Product.query.filter_by(name=name, store=store, brand=brand).first()

        if productExist:
            return jsonify(
                success=False,
                error="This product is alrealy exist"
            )
        else:
            description = data.get("description")
            price = data.get("price")
            quantity = data.get("quantity")
            types = data.get("types")

            try:
                imagesName = f"{len(os.listdir('./images/products'))}.jpg"
                imagesFile = request.files["photo"]
                imagesFile.save(f"./images/products/{imagesName}")
            except:
                imagesName = "default.jpg"
               
            newProduct = Product(name, description, price, quantity, store, imagesName, types, brand)

            try:
                db.session.add(newProduct)
                db.session.commit()

                return jsonify(
                    success=True,
                )
            
            except:
                return jsonify(
                    success=False,
                    error="cannot create this product"
                )
    except:
        return jsonify(
            success=False,
            error="cannot create this product"
        )
Beispiel #9
0
    async def search(cls, params: SearchParams) -> List[Product]:
        r = await cls.get(
            f'https://shop.rivegauche.ru/rg/v1/newRG/products/search?currentPage=0&pageSize={params.size}&text={params.query}'
        )

        items = r['results']

        return [
            Product(search_query=params.query,
                    title=item['name'],
                    price=item['prices'][0]['value'],
                    image_url=
                    f"https://shop.rivegauche.ru{item['listingImage']['url']}",
                    product_url=f"https://shop.rivegauche.ru{item['url']}",
                    description=clean_html(item['description']),
                    site_logo=cls.logo) for item in items
        ]
Beispiel #10
0
    async def search(cls, params: SearchParams) -> List[Product]:
        r = await cls.get(
            f'https://api.hosting.ue0.ru/v5/Catalog/Goods/Search?q={params.query}&take={params.size}'
        )

        items = r['data']['elements']

        return [
            Product(
                search_query=params.query,
                title=item['name'],
                price=item['price']['with_discount'] / 100,
                image_url=item['images']['main'],
                product_url=
                f"https://nikamebelopt.ru/catalog/{item['group']['slug']}/{item['slug']}/",
                description=item['additional_properties']['description'],
                site_logo=cls.logo) for item in items
        ]
Beispiel #11
0
    async def search(cls, params: SearchParams) -> List[Product]:
        response = await cls.get(
            f'https://sort.diginetica.net/search?st={params.query}&apiKey={cls.api_key}&fullData=true&size={params.size}'
        )

        items = response['products']

        return [
            Product(
                search_query=params.query,
                title=item['name'],
                price=parse_float(item['price']),
                image_url=item['image_url'],
                product_url=f"{cls.main_url}{item['link_url']}",
                description=f'Производитель: {brand}' if (
                    brand := item.get('brand')
                ) else '',
                site_logo=cls.logo
            ) for item in items
        ]
Beispiel #12
0
def all_products():
    if request.method == 'POST':
        in_product = request.get_json()
        try:
            p = Product(product_nr=in_product['product_nr'],
                        name=in_product['name'],
                        price=in_product['price'])
        except KeyError:
            abort(500)

        db.session.add(p)
        try:
            db.session.commit()
            return jsonify(p.serialize)
        except IntegrityError:
            db.session.rollback()
            abort(500)
    else:
        ps = Product.query.all()
        return jsonify([p.serialize for p in ps])
Beispiel #13
0
    async def search(cls, params: SearchParams) -> List[Product]:
        response = await cls.get(
            f'https://sik.search.blue.cdtapps.com/ru/ru/search-result-page?q={params.query}&size={params.size}&columns=4'
        )
        search_result = response.get('searchResultPage')

        if not search_result:
            return []

        items = list(
            filter(lambda item: item.get('product'),
                   search_result['products']['main']['items']))
        return [
            Product(
                search_query=params.query,
                title=item['product']['name'],
                price=item['product']['priceNumeral'],
                image_url=item['product']['mainImageUrl'],
                product_url=item['product']['pipUrl'],
                description=item['product']['typeName'],
                site_logo=cls.logo,
            ) for item in items
        ]
Beispiel #14
0
from server import db
from server.models import Product,StockLocation,Transaction

p1 = Product(product_nr="P001",name="jTelefon", price=8900)
p2 = Product(product_nr="P002",name="jPlatta", price=5700)
p3 = Product(product_nr="P003",name="Päronklocka", price=11000)

db.session.add(p1)
db.session.add(p2)
db.session.add(p3)

sl1 = StockLocation(city="Cupertino")
sl2 = StockLocation(city="Norrköping")
sl3 = StockLocation(city="Frankurt")


db.session.add(sl1)
db.session.add(sl2)
db.session.add(sl3)

db.session.commit()

t1 = Transaction(quantity=10000,stock_location=sl3,product=p1, inbound=True)
t2 = Transaction(quantity=5000,stock_location=sl2,product=p3, inbound=True)
t3 = Transaction(product=p1,stock_location=sl2,quantity=5000, inbound=True)
t4 = Transaction(product=p2,stock_location=sl1,quantity=40000, inbound=True)
t5 = Transaction(product=p2,stock_location=sl1,quantity=25000, inbound=False)
t6 = Transaction(product=p1,stock_location=sl2,quantity=3000, inbound=False)
t7 = Transaction(product=p3,stock_location=sl3,quantity=20000, inbound=True)
t8 = Transaction(product=p1,stock_location=sl1,quantity=45000, inbound=True)
Beispiel #15
0
# Product(
#         name="",
#         desc="",
#         price=0.0,
#         img="",
#         sub_category=SubCategory.query.filter(
#         SubCategory.name == 'SUBCAT').all()[0]

#     ),

products = [
    Product(
        name="Fjäderblommor Gammelrosa 12-pack",
        desc=
        "Tre vackra fjädrar som är formade som en blomma i ett knippe. Fina att fästa i påskriset eller annan kvist, i ett blomsterarrangemang eller bukett. Alla fjäderknippen är trådade och lätta att fästa. Fjädrarna är delvis äkta och plockade från döda djur där fjädrarna har lossnat.",
        price=69.9,
        img=
        "https://media.fyndiq.se/product/58/3f/5f/0fc52b5789293ff5c09c533ce1e72e4c9d/original.png",
        sub_category=SubCategory.query.filter(
            SubCategory.name == 'Inredning').all()[0]),
    Product(
        name="Doftljus Världens Bästa Mormor",
        desc=
        "Ingen blir väl lika glad som mormor när hon överraskas med något från barnbarnen! Med detta doftljus kommer hon ständigt påminnas om hur mycket du tycker om henne. Doftljus Världens Bästa Mormor är ett vaxljus i en vacker glasbehållare. Glaset är rosafärgat och locket i trä sitter bra på plats tack vare den förslutande gummiringen. Efter att ljuset brunnit ut kan glasbehållaren sparas och användas till något annat. Ljuset har en god och mild doft som sprider sig när du tänder veken. Höjd: 10 cm",
        price=169,
        img=
        "https://media.fyndiq.se/product/0a/a2/4f/cb4f7a943fac7aa4c618167d7014999d53/original.png",
        sub_category=SubCategory.query.filter(
            SubCategory.name == 'Inredning').all()[0]),
    Product(
        name="Vindspel",