Esempio n. 1
0
    def get(self):

        product = Product()
        cart = Cart()
        cart.product_id = self.get_argument("product_id", "")
        cart.quantity = int(self.get_argument("quantity", 0))

        if cart.quantity > 0:

            if cart.product_id != "":

                response_obj = product.InitById(cart.product_id)

                if "success" in response_obj:

                    if product.promotion_price != 0:
                        subtotal = int(product.promotion_price) * cart.quantity
                        cart.price = product.promotion_price
                    else:
                        subtotal = int(product.sell_price) * cart.quantity
                        cart.price = product.sell_price

                    if self.current_user:
                        if self.current_user["type_id"] == 4:
                            subtotal = int(product.bulk_price) * cart.quantity
                            cart.price = product.bulk_price

                    size_id = self.get_argument("size", "")

                    size = Size()
                    size.id = size_id
                    res_name = size.initById()

                    if "error" in res_name:
                        self.write(res_name["error"])
                    else:
                        cart.size = size.name

                    cart.date = datetime.now(
                        pytz.timezone('Chile/Continental')).isoformat()
                    cart.subtotal = subtotal
                    cart.user_id = self.get_argument("user_id", -1)

                    if self.current_user:
                        cart.user_id = self.current_user["id"]

                    response_obj = cart.Save()

                    product.updateAdded(product.sku)

                    if "success" in response_obj:
                        self.write("ok")
                    else:
                        self.write(response_obj["error"])
                else:
                    self.write(response_obj["error"])
            else:
                self.write("Product ID is empty")
        else:
            self.write("ok")
Esempio n. 2
0
    def moveStock(self, lista, carro, id_bodega, order_id):

        for l in lista:

            if len(carro) > 0:
                cart = Cart()
                cart.id = l["id"]
                cart.Remove()

                kardex = Kardex()

                producto = Product()
                response = producto.InitById(l["product_id"])

                if "success" in response:

                    kardex.product_sku = producto.sku
                    kardex.cellar_identifier = id_bodega
                    kardex.operation_type = Kardex.OPERATION_MOV_OUT
                    kardex.sell_price = l['price']
                    kardex.order_id = order_id

                    _s = Size()
                    _s.name = l["size"]
                    res_name = _s.initByName()

                    if "success" in res_name:
                        kardex.size_id = _s.id
                    elif debugMode:
                        print res_name["error"]

                    kardex.date = str(
                        datetime.now(
                            pytz.timezone('Chile/Continental')).isoformat())
                    kardex.user = "******"
                    kardex.units = l["quantity"]
                    kardex.price = producto.price

                    kardex.Insert()

                    c = Cellar()
                    res_reservation = c.GetReservationCellar()

                    reservation_cellar = shipping_cellar

                    if "success" in res_reservation:
                        reservation_cellar = res_reservation["success"]
                    elif debugMode:
                        print res_reservation["error"]

                    kardex.cellar_identifier = reservation_cellar
                    kardex.operation_type = Kardex.OPERATION_MOV_IN

                    res_kardex = kardex.Insert()

                    if debugMode and "error" in res_kardex:
                        print res_kardex["error"]

                elif debugMode:
                    print response["error"]
Esempio n. 3
0
    def get(self, tags=""):

        cellar_id = None

        cellar = Cellar()
        res_web = cellar.GetWebCellar()

        if "success" in res_web:
            cellar_id = res_web["success"]

        page = int(self.get_argument("page", "1"))
        ajax = int(self.get_argument("ajax", 0))

        tags = tags.replace("_", " ").lower()

        tags_arr = tags.split(",")

        items = 0

        tallas = []

        tag = Tag()

        res = tag.GetItemsByTags(cellar_id, tags_arr)

        if "success" in res:
            items = int(res["success"])

        res = tag.GetProductsByTags(cellar_id, tags_arr, page, 16)

        tags_visibles = tag.ListVisibleTags(tags_arr)

        if "success" in tags_visibles:
            tags = tags_visibles["success"]

        product = Product()

        tallas_res = product.getAllSizes()

        if "success" in tallas_res:
            tallas = tallas_res["success"]

        if "success" in res:
            if ajax == 0:
                self.render("store/index.html",
                            data=res["success"],
                            items=items,
                            page=page,
                            tags=tags,
                            tags_arr=tags_arr,
                            tag=",".join(tags_arr),
                            tallas=tallas)
            else:
                self.render("store/ajax_productos.html",
                            data=res["success"],
                            items=items,
                            tag=",".join(tags_arr),
                            page=page)
        else:
            self.render("beauty_error.html", message=res["error"])
Esempio n. 4
0
    def get(self):
        """ metodo get"""

        categories = self.get_arguments("categories")
        sizes = self.get_arguments("size")
        page = int(self.get_argument("page", "1"))

        items = 0
        cellar_id = ""

        cellar = Cellar()
        res_cellar = cellar.GetWebCellar()

        if "success" in res_cellar:
            cellar_id = res_cellar["success"]

        product = Product()
        res = product.filter(categories, sizes, cellar_id, page)
        res_items = product.getFilterItems(categories, sizes, cellar_id)

        if "success" in res_items:
            items = res_items["success"]

        if "success" in res:
            self.write(
                self.render_string("store/ajax_productos.html",
                                   data=res["success"],
                                   items=items,
                                   page=page,
                                   canonical_url=self.canonical_url,
                                   url_bodega=url_bodega,
                                   tag='filtro',
                                   money_format=self.money_format))
        else:
            self.write(res["error"])
def test_bundle_type(software_photo, storefront_prod):
    prod = Product(software_photo)
    not_bundle_prod = Product(storefront_prod)
    assert prod.category == 'bundle'
    assert prod.bundle_type == 'softwarebundle'
    assert not_bundle_prod.category == 'storefront'
    assert not_bundle_prod.bundle_type == None
Esempio n. 6
0
 def get(self):
     """
     Obtains a Product given the corresponding filters on the JSON
     json example:
     {
         "product_name":"book",
         "product_cost":300
     }
     :returns example:
     {
         "success": true,
         "products":[
             {
                 "product_id":1,
                 "product_name":"Book",
                 "product_description": "It's a book",
                 "product_cost":100
             },
             ...
         ]
     }
     """
     try:
         product = Product()
         json = request.json
         ans = []
         if json is not None:
             conditions = conditions_builder(json)
             ans = product.get_product(conditions)
         return {'success': True, 'products': ans}
     except Exception as e:
         return {'success': False, 'Error': str(e)}
Esempio n. 7
0
 def insertproducts(self, data):
     print("Saving data", end="\n\t\t\t\t\t")
     for rawproduct in data:
         product = Product(self.sqlmng, data=rawproduct)
         product.insertproduct()
         catmng = Categoriemanager(self.sqlmng)
         catmng.updatecategoriesfromproductdata(product)
     print("Done")
Esempio n. 8
0
def test_insert_product():
    product = Product()
    product_to_db = {
        'product_name': 'Book 40',
        'product_description': 'its as good as Book 6',
        'product_cost': 90
    }
    ans = product.insert_product(product_to_db)
    assert ans['success']
Esempio n. 9
0
    def __importCSVFile(self, filename):
        file = QtCore.QFile(filename)
        if not file.open(QtCore.QIODevice.ReadOnly):
            log.error(f'There is invalid file to read {filename}')
            return False
        title = True
        productList = DictList()
        try:
            while not file.atEnd():
                line = str(file.readLine().data(), encoding='ISO 8859-9')
                line = line.upper().replace('İ', 'I')
                line = line.replace('\n', '')
                if title:
                    title = False
                else:
                    productInList = line.split(',')
                    if self.__checkRowValid(productInList):

                        product = Product(
                            ProductType.convertWeighableBarcode(
                                productInList[1]),
                            productInList[3].strip(),
                            float(productInList[9]),
                            float(productInList[5]),
                            float(productInList[11]),
                            int(productInList[-1]),
                            datetime.datetime.now(),
                        )
                        if product.barcode() not in productList:
                            productList.setItem(product.barcode(), product)

            # add all products to database
            productListNotInModel = []
            for barcode in productList:
                product = self.mainWidget.productModel.getProductWithBarcode(
                    barcode)
                if product is None:
                    productListNotInModel.append(productList[barcode])
            if productListNotInModel:
                for product in productListNotInModel:
                    self.databaseService().add(product)

                # commit all changes
                if self.databaseService().commit() is True:
                    self.mainWidget.productModel.setProductList(
                        self.__dataBaseToProductList())
            else:
                log.warning('No new item is added to product model')
        except Exception as e:
            log.error(
                f'Error occurred reading CSV file {filename}. Error is => {e}')
            return False

        return True
Esempio n. 10
0
    def update_product(self, product_id, name, price):
        data = self.__product_db.get()
        list_index = 0

        for index, item in enumerate(data):
            if item['id'] == product_id:
                list_index = index

        product = Product(product_id, name, price)
        product = product.serialize()

        self.__product_db.update(list_index, product)
        return product
Esempio n. 11
0
    def post(self):

        cellar = Cellar()
        res_web = cellar.GetWebCellar()
        cellar_id = None

        if "success" in res_web:
            cellar_id = res_web["success"]

        product = Product()
        page = int(self.get_argument("page", "1"))
        ajax = int(self.get_argument("ajax", 0))
        lista = product.GetList(cellar_id, page, 16)

        items = 0
        tags = {}
        tallas = []

        response = product.GetItems(cellar_id)
        if "success" in response:
            items = response["success"]

        tag = Tag()
        tags_visibles = tag.ListVisibleTags()

        if "success" in tags_visibles:
            tags = tags_visibles["success"]

        tallas_res = product.getAllSizes()

        if "success" in tallas_res:
            tallas = tallas_res["success"]

        banners = {}
        banners["nuevo"] = self.jsonToObject(self.get_argument("nuevo", ""))
        banners["sale"] = self.jsonToObject(self.get_argument("sale", ""))
        banners["tienda"] = self.jsonToObject(self.get_argument("tienda", ""))
        banners["background"] = self.jsonToObject(
            self.get_argument("background", ""))

        tag = self.get_argument("tag", "")

        self.render("preview/index.html",
                    data=lista,
                    items=items,
                    page=page,
                    tags=tags,
                    tags_arr=[tag],
                    tag=tag,
                    tallas=tallas,
                    banners=banners)
Esempio n. 12
0
    def get(self):
        cellar = Cellar()
        res_web = cellar.GetWebCellar()
        cellar_id = None

        if "success" in res_web:
            cellar_id = res_web["success"]

        product = Product()
        page = int(self.get_argument("page", "1"))
        ajax = int(self.get_argument("ajax", 0))
        lista = product.GetList(cellar_id, page, 16)

        items = 0
        tags = {}
        tallas = []

        response = product.GetItems(cellar_id)
        if "success" in response:
            items = response["success"]

        tag = Tag()
        tags_visibles = tag.ListVisibleTags()

        if "success" in tags_visibles:
            tags = tags_visibles["success"]

        tallas_res = product.getAllSizes()

        if "success" in tallas_res:
            tallas = tallas_res["success"]

        if ajax == 0:
            self.render("store/index.html",
                        data=lista,
                        items=items,
                        page=page,
                        tags=tags,
                        tags_arr=None,
                        tag="tienda",
                        tallas=tallas)
        else:
            self.render("store/ajax_productos.html",
                        data=lista,
                        items=items,
                        page=page,
                        tags=tags,
                        tags_arr=None,
                        tag="tienda",
                        tallas=tallas)
Esempio n. 13
0
    def _substitution_menu(self):
        """Manage the substitute menu of the app."""
        self._page = 1

        with Manager() as manager:
            manager.set_db()
            substitutions = manager.select(Substitution)

        # If there is some data in database:
        if substitutions:
            substitutions_to_show = self._paging(substitutions)
            self._vue.sub_menu(substitutions_to_show, sub=True)

            sub_choosed = self._navigation(substitutions,
                                           self._main_menu,
                                           sub=True,
                                           )

            old_product = Product()
            old_product.get(id=sub_choosed.id_to_substitute)
            new_product = Product()
            new_product.get(id=sub_choosed.id_substitute)

            # Display substitutions
            self._vue.details_menu(old_product, new_product)

            self._substitution_menu()

        else:
            self._vue.empty_menu()
            self._main_menu()
Esempio n. 14
0
 def putProduct(self, item):
     data = Product(
         self.view.listview.itemWidget(item).data.id,
         self.window.name(),
         self.getCategoryID(),
         self.window.price(),
         self.window.stock(),
     )
     headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
     r = requests.put("http://localhost:8080/api/v1/products",
                      data=data.toJson(),
                      headers=headers)
     print(r.text)
     if r.status_code == 204:
         self.updateProduct()
Esempio n. 15
0
def toProduct(tupl):
    # print(tupl)
    if type(tupl) == tuple:
        prod = Product(
            tupl[0],
            tupl[1],
            tupl[2],
            tupl[3],
            tupl[4],
            tupl[5],
            tupl[6],
            tupl[7],
            tupl[8],
            tupl[9],
            tupl[10],
            tupl[11],
            tupl[12],
            tupl[13],
            database.retrieve_properties("product_prices",
                                         {"product_id": f"{tupl[0]}"},
                                         ("selling_price", ))[0][0],
            database.retrieve_properties("product_prices",
                                         {"product_id": f"{tupl[0]}"},
                                         ("discount", ))[0][0],
        )

        return prod
Esempio n. 16
0
def createPackage():
    if validUser() != '':
        return validUser()
    db = DBManager()
    packageId = 0

    if request.form['packageId'] is not None:
        packageId = request.form['packageId']
    productIds = []
    products = []
    for productId in request.values.getlist('productId'):
        productIds.append(productId)

    if len(productIds) > 0:
        products = Product.getList(db, ",".join(productIds))
        if len(products) > 0:
            for p in products:
                if request.form['productQuantity-' + str(p.id)] is '':
                    p.quantity = 0
                else:
                    p.quantity = int(request.form['productQuantity-' + str(p.id)])

    package = PackageDelivery(products, session['userId'])
    package.id = int(packageId)
    if package.id > 0:
        package.saveChilds(db)
    else:
        package.save(db, True)

    return redirect("/manage-package/" + str(package.id))
Esempio n. 17
0
    def get_product_details_from_pdp(self):
        driver = self.app.driver
        # PDP - product details page
        product_name_pdp = driver.find_element_by_css_selector(
            '#box-product .title').text
        # price locators
        regular_price_pdp = driver.find_element_by_css_selector(
            'div.price-wrapper > s')
        campaign_price_pdp = driver.find_element_by_css_selector(
            '.campaign-price')
        # regular price
        regular_price_pdp_value = regular_price_pdp.text
        regular_price_pdp_strikethrough = regular_price_pdp.value_of_css_property(
            "text-decoration-line")
        # campaign price
        campaign_price_pdp_value = campaign_price_pdp.text
        campaign_price_pdp_colour = campaign_price_pdp.value_of_css_property(
            "Color")

        return Product(
            product_name=product_name_pdp,
            regular_price_value=regular_price_pdp_value,
            campaign_price_value=campaign_price_pdp_value,
            campaign_price_colour=campaign_price_pdp_colour,
            regular_price_line_through=regular_price_pdp_strikethrough)
Esempio n. 18
0
    def get_first_campaign_product_details_store_front(self):
        driver = self.app.driver
        product_name = driver.find_element_by_css_selector(
            '#box-campaigns > div > ul > li > a.link .name').text
        # price locators
        regular_price_front = driver.find_element_by_css_selector(
            '#box-campaigns > div > ul > li > a.link > div.price-wrapper > s')
        campaign_price_front = driver.find_element_by_css_selector(
            '#box-campaigns > div > ul > li > a.link > div.price-wrapper > strong'
        )
        # regular price details
        regular_price_value = regular_price_front.text
        regular_price_front_strikethrough = regular_price_front.value_of_css_property(
            "text-decoration-line")

        # campagin price details
        campaign_price_value = campaign_price_front.text
        campaign_price_colour = campaign_price_front.value_of_css_property(
            "Color")

        return Product(
            product_name=product_name,
            regular_price_value=regular_price_value,
            campaign_price_value=campaign_price_value,
            campaign_price_colour=campaign_price_colour,
            regular_price_line_through=regular_price_front_strikethrough)
Esempio n. 19
0
def test_buy_product(app):
    '''
    Buy the specified item from a current shopping list
    :param app:
    :return:
    '''
    app.buy_product(Product.product_test())
 def post(self):
     name = request.json.get("name")
     quantity = request.json.get("quantity")
     product = Product(name=name, quantity=quantity)
     db.session.add(product)
     db.session.commit()
     return jsonify({"product": product})
Esempio n. 21
0
 def get_product(self):
     parsed_html = html.fromstring(self.html_source_code.decode('utf8'))
     return Product(
         name=parsed_html.xpath(self.crawlable.get_product_name())[0],
         title=parsed_html.xpath(self.crawlable.get_product_title())[0],
         url=self.url,
     )
Esempio n. 22
0
 def get_product_details(self, product):
     wd = self.app.wd
     wd.get(product.link)
     name = wd.find_element_by_css_selector("h1.title").text
     price = wd.find_element_by_css_selector("s.regular-price").text
     price_color = re.search(
         r'\((.*?)\)',
         wd.find_element_by_css_selector("s.regular-price").
         value_of_css_property("color")).group(1).replace(" ",
                                                          "").split(',')
     price_decoration = wd.find_element_by_css_selector(
         "s.regular-price").value_of_css_property("text-decoration-line")
     price_size = wd.find_element_by_css_selector(
         "s.regular-price").value_of_css_property("font-size")[:-2]
     auc_price = wd.find_element_by_css_selector(".campaign-price").text
     auc_price_color = re.search(
         r'\((.*?)\)',
         wd.find_element_by_css_selector(".campaign-price").
         value_of_css_property("color")).group(1).replace(" ",
                                                          "").split(',')
     auc_price_decoration = wd.find_element_by_css_selector(
         ".campaign-price").value_of_css_property("font-weight")
     auc_price_size = wd.find_element_by_css_selector(
         ".campaign-price").value_of_css_property("font-size")[:-2]
     return Product(name=name,
                    price=price,
                    price_color=price_color,
                    price_decoration=price_decoration,
                    price_size=price_size,
                    auc_price=auc_price,
                    auc_price_color=auc_price_color,
                    auc_price_decoration=auc_price_decoration,
                    auc_price_size=auc_price_size)
Esempio n. 23
0
def test_add_product(app):
    '''
    Add the specified item to a current shopping list
    :param app:
    :return:
    '''
    app.add_product(Product.product_test())
Esempio n. 24
0
	def __addOrUpdateProduct(self):
		try:
			barcode = self.barcodeLineEdit.text()
			index = self.__model.getIndexWithBarcode(barcode)
			if index.isValid() is True:
				index.model().setData(index, self.__updateProductValue)
				Toast.success('Product Edit', 'Product is updated successfully')
			else:
				barcode = self.barcodeLineEdit.text()
				name = self.productNameLineEdit.text()
				purchasePrice = float(self.purchasePriceLineEdit.text())
				sellingPrice = float(self.sellingPriceLineEdit.text())
				secondSellingPrice = float(self.secondSellingPriceLineEdit.text())
				valueTaxAdded = int(self.vatLineEdit.text())
				product = Product(ProductType.convertWeighableBarcode(barcode), name, purchasePrice, sellingPrice,
								  secondSellingPrice,
								  valueTaxAdded, datetime.datetime.now())
				self.databaseService().add(product)
				if self.databaseService().commit() is True:
					self.__model.addProduct(product)
					Toast.success('Product Add', 'New product is added successfully')
				else:
					Toast.error('Product Add', 'New product is not added successfully')
		except Exception as e:
			print(f'Product is not added or updated successfully. Exception is {e}')
			Toast.error('Update Error', 'Product is not added or updated successfully')

		self.setProduct(None)
Esempio n. 25
0
    def get_bad_products(category: str, session: Session) -> List[Product]:
        """
        Get bad products from given category in user database.

        :param category: Category to filter on
        :param session: Session
        :return: List[Product]
        """
        stmt = """
        SELECT
            p.brands,
            '',
            p.id,
            p.nutriscore_grade,
            p.packaging_tags,
            p.product_name_fr,
            '',
            p.url
        FROM Product_Category_Association as pca
        INNER JOIN Products as p
            ON pca.product_id = p.id
        INNER JOIN Categories as c
            ON pca.category_id = c.id
        WHERE
            pca.category_id = (SELECT id FROM Categories WHERE name = %s)
        AND 'D' <= p.nutriscore_grade
        """

        products = session.select(stmt, (category, ))

        bad_products: List[Product] = choices(
            [Product(*args) for args in products], k=ITEM_DISPLAYED)

        return bad_products
Esempio n. 26
0
def product():
    if validUser() != '':
        return validUser()

    db = DBManager()
    if request.method == 'POST':
        product = Product(request.form['name'], request.form['code1'],
                          request.form['quantity'])
        product.save(DBManager())
        return redirect("/product")
    else:
        products = Product.getList(db)
        return render_template('products.html', my_string="Bar",
                               title="Products",
                               current_time=datetime.datetime.now(),
                               products=products, userMenu=getUserRoles())
Esempio n. 27
0
 def get_products(self):
     products_list = []
     for pr in self.products:
         name = pr.find_element_by_class_name("name").text
         link = pr.find_element_by_class_name("link").get_attribute("href")
         products_list.append(Product(name=name, link=link))
     return products_list
Esempio n. 28
0
    def search(self, query):
        filter = Q()

        if query is not None:
            filter = filter & (Q(name__icontains=query) | Q(short_description__icontains=query) | Q(long_description__icontains=query))

        return Product.objects(filter)
Esempio n. 29
0
 def post(self):
     try:
         """
         inserts a product on the DB given by the JSON, for more information of the model refer to this project on
         model/product
         :returns example:
         {
             "success": True,
             "product": model_of_product
         }
         """
         product = Product()
         json = request.json
         product.insert_product(json)
         return {'success': True, 'product': json}
     except Exception as e:
         return {'success': False, 'Error': str(e)}
Esempio n. 30
0
    def test_write(self):
        exporter = CSVExporter()
        product = Product(name='pname', title='ptitle', url='purl')
        writer, stream = self.get_writer()
        exportable_list = [product]
        exporter.__write__(writer, exportable_list)

        self.assertEquals('pname,ptitle,purl\r\n', stream.getvalue())
Esempio n. 31
0
    def saveOrderDetail(self, lista, order):

        # guardar el detalle
        for l in lista:

            detail = OrderDetail()
            detail.order_id = order.id
            detail.quantity = l["quantity"]
            detail.subtotal = l["subtotal"]
            detail.product_id = l["product_id"]
            detail.size = l["size"]
            detail.price = l['price']
            detail.Save()

            product = Product()
            product.InitById(l["product_id"])
            product.updateSold(product.sku)
Esempio n. 32
0
 def on_buttonApply_clicked(self, widget):
     entryName = self.builder.get_object("entryName")
     name = entryName.get_text()
     entryCIF = self.builder.get_object("entryCIF")
     cif = entryCIF.get_text()
     newProduct = Product(None, name, cif)
     self.addProduct(newProduct)
     self.window_edit.destroy()
Esempio n. 33
0
 def get_products_by_user_key(cls,user_key):
     return  Product.get_products_by_user_key(user_key)