Exemplo n.º 1
0
def Addproduct(request):
    form=ProductForm(request.POST or None)
    if form.is_valid():
        ModelName = form.cleaned_data['ModelName']
        description = form.cleaned_data['description']
        photo = form.cleaned_data['photo']
        manufacturer = form.cleaned_data['manufacturer']
        price_in_dollars = form.cleaned_data['price_in_dollars']
        Quantity = form.cleaned_data['Quantity']
        Serial_No =form.cleaned_data['Serial_No']
        product=Product()
        product.ModelName=ModelName
        product.description=description
        product.photo=photo
        product.manufacturer=manufacturer
        product.price_in_dollars=price_in_dollars
        product.Quantity=Quantity
        product.Serial_No=Serial_No  
        product.save()
        return HttpResponseRedirect(reverse('ecom:product'))
        
        
        #return HttpResponseRedirect(reverse('ecom:product'))
    else:
        return render(request,"ItemMaster.html",{"form":form})    
Exemplo n.º 2
0
def AddProduct(request):
    if request.POST.has_key('display_name'):
        NewDisplayName = request.POST['display_name']
    if request.POST.has_key('detail_name'):
        NewDetailName = request.POST['detail_name']
    if request.POST.has_key('material'):
        NewMaterial = request.POST['material']
    if request.POST.has_key('series'):
        NewSeries = request.POST['series']
    if request.POST.has_key('function'):
        NewFunction = request.POST['function']
    if request.POST.has_key('origin'):
        NewOrigin = request.POST['origin']
    AlreadyExist = Product.objects.filter(
        display_name=NewDisplayName,
        detail_name=NewDetailName,
        material=NewMaterial,
        series=NewSeries,
        function=NewFunction,
        origin=NewOrigin
    )
    if len(AlreadyExist) != 0:
        #该产品已存在
        result="AlreadyExist"
        return HttpResponse(result, mimetype="application/text")
    productToAdd = Product(
        display_name=NewDisplayName,
        detail_name=NewDetailName,
        material=NewMaterial,
        series=NewSeries,
        function=NewFunction,
        origin=NewOrigin
    )
    productToAdd.save()
    return HttpResponse(productToAdd.id, mimetype="application/text")
Exemplo n.º 3
0
def create(request):
    if request.method != "POST":
        raise Http404("Invalid HTTP method!")
    go_back = False
    if len(request.POST["name"]) < 1:
        messages.add_message(request, messages.INFO, "Product Name cannot be blank!")
        go_back = True
    elif len(request.POST["name"]) < 8:
        messages.add_message(request, messages.INFO, "Product Name must be at least 8 characters!")
        go_back = True
    if len(request.POST["price"]) < 1:
        messages.add_message(request, messages.INFO, "Price cannot be blank!")
        go_back = True
    elif float(request.POST["price"]) < 0:
        messages.add_message(request, messages.INFO, "Price cannot be less than $0!")
        go_back = True
    if len(request.POST["description"]) < 1:
        messages.add_message(request, messages.INFO, "Description cannot be blank!")
        go_back = True
    elif len(request.POST["description"]) > 50:
        messages.add_message(request, messages.INFO, "Description cannot be more than 50 characters!")
        go_back = True
    if go_back:
        return redirect("/products")
    else:
        prod = Product(
            name=request.POST["name"],
            manufacturer=request.POST["manufacturer"],
            price=float(request.POST["price"]),
            description=request.POST["description"],
        )
        prod.save()
        return redirect("/products")
Exemplo n.º 4
0
    def manage_settings(self, product):
        product_data = self.retrieve_product(product)
        if type(product_data) is str:
            title = "%s Manage Settings" % product.title()
            product_data = None
            form = forms.ManageProduct()
        else:
            title = "%s Manage Settings" % product_data.title
            form = forms.ManageProduct(obj=product_data)

        if request.method == "POST" and form.validate_on_submit():
            to_save = Product(request.form.to_dict())
            if product_data and product_data.db_name:
                to_save.db_name = product_data.db_name
                to_save.groups = product_data.groups
            else:
                to_save.set_db_name()

            g.db.api_settings.update({}, {"$set": {product: to_save.__dict__}})
            if to_save.active:
                g.db.api_settings.update({}, {"$addToSet": {"active_products": product}})
            else:
                g.db.api_settings.update({}, {"$pull": {"active_products": product}})

            flash("Product was successfully updated", "success")
            return redirect("/%s/manage" % product)
        else:
            if request.method == "POST":
                flash("Form was not saved successfully", "error")

            return render_template("manage/manage_product.html", title=title, form=form, product=product_data)
Exemplo n.º 5
0
class ProductTests(TestCase):
    def setUp(self):
        stuff = FoodStuff(name='some stuff 2')
        stuff.save()

        recipe = Recipe(name='some recipe 2')
        recipe.save()

        ingredient = RecipeIngredient(stuff=stuff, recipe=recipe, count=1.5)
        ingredient.save()

        self.product = Product(name='some product 2', recipe=recipe)
        self.product.save()

    def test_str(self):
        self.assertEqual('some product 2', str(self.product))

    def test_prepare_price(self):
        check = self.product.prepare_price(100)
        self.assertEqual(100, check)

        self.product.markup = 2
        check = self.product.prepare_price(100)
        self.assertEqual(200, check)

        self.product.markup = 1.44
        check = self.product.prepare_price(100)
        self.assertEqual(150, check)
Exemplo n.º 6
0
 def set_data_for(self, value=None):
     products = [(Product.get(id=rpt.product_id).name) for rpt in
                 Report.select(fn.Distinct(Report.product))]
     if value:
         products = [(prod.name) for prod in Product.select().where(Product.name.contains(value))
                     .where(Product.name << products).order_by(Product.name.desc())]
     self.data = [(prd, "") for prd in products]
Exemplo n.º 7
0
 def post(self, subdomain):
     namespace_manager.set_namespace(subdomain)
     visible = False
     if self.request.get('visible') == 'yes':
         visible = True
     name = self.request.get('name')
     categories = self.request.get('category').split(',')
     logging.info(categories)
     cat_refs = []
     for category in categories:
         logging.info(category)
         if Category.get_by_key_name(category):
             cat_refs.append(Category.get_by_key_name(category).key())
     logging.info(cat_refs)
     entity = Product(key_name=name,
                       name=name,
                       shop_id=Shop.get_by_key_name(subdomain),
                       stock=int(self.request.get('qty')),
                       description=self.request.get('description'),
                       price=float(self.request.get('price')),
                       tags=self.request.get('tags').split(','),
                       video=self.request.get('video'),
                       visible=visible,
                       categories=cat_refs
                           )
     entity.put()
     self.redirect(webapp2.uri_for('addproducts'))
Exemplo n.º 8
0
    def post(self, request):
        url = request.POST['url']
        try:
            response = urllib2.urlopen(url, timeout=300)
        except urllib2.HTTPError as e:
            if e.code == 404:
                raise Http404('Product not found')
            raise e
        except ValueError as e:
            return HttpResponseBadRequest('Invalid url')
        except urllib2.URLError as e:
            return HttpResponseBadRequest('Site is not available')

        html = response.read()
        response.close()
        soup = BeautifulSoup(html)
        image = soup.find('img', {'id': 'base_image'})
        image_src = image['src']
        image_name = image['src'].split('/')[-1]
        title = image['title']
        my_image_path = os.path.join('media', image_name)
        image_my_src = os.path.join(BASE_DIR, my_image_path)
        urllib.urlretrieve(image_src, image_my_src)
        price = soup.find('div', {'name': 'prices_active_element_original'}).find('span', {'itemprop': 'price'}).text

        product = Product(title=title, image='/{0}'.format(my_image_path), price=float(price))
        product.save()

        return HttpResponseRedirect('/list/')
Exemplo n.º 9
0
def product(request):
    """ Get list of products ordered with the cheapest first.
    Create product if method `POST`
    """

    if request.method == 'GET':

        sql = 'SELECT * FROM products_product order by CAST(price AS DECIMAL(6,2))'

        arg = QueryDict(request.GET.urlencode()).dict()
        slc = int(arg.get('page', 1)) * 10

        inst_list = Product.objects.raw(sql)[slc - 10: slc]

        return json_response({'result': [to_dict(ins) for ins in inst_list]})

    # create product
    elif request.method == 'POST':
        data = json.loads(request.body)
        if not data.get('name'):
            return json_response(FIELD_REQUIRED)

        p = Product(**data)
        p.save()
        return json_response({'id': p.id}, status=201)

    return HttpResponse(status=405)
Exemplo n.º 10
0
 def click_item(self, row, column, *args):
     if column != 2:
         self.choix = Product.filter(name=self.data[row][1]).get()
         self.parent.table_info.refresh_(self.choix.id)
     if column == 2:
         # self.removeRow(row)
         self.choix = Product.filter(name=self.data[row][1]).get()
         self.parent.table_invoice.refresh_(self.choix)
def save_products(data):
    for key, value in data.iteritems():
        if type(key) is unicode:
            key = int(key)
        product = Product(
            product_id=key, mpn=value["mpn"], image=value["image"], link=value["link"], name=value["name"]
        )
        product.save()
Exemplo n.º 12
0
 def setUp(self):
     self.products = []
     for i in range(1,10):
         product = Product(product_id=i, key_name="test_product_"+str(i),price=round(random.uniform(1,10),2),tax_percent=18.00)
         product.put()
         product.add_stock("test_product_"+str(i),10)
         self.products.append("test_product_"+str(i))
     self.cart = Cart()
     random.shuffle(self.products)
Exemplo n.º 13
0
 def test_reserved(self):
     qty = random.randint(1,10)
     print ' To reserve: ',qty,
     if Product.reserve(self.name,qty):
         p = Product.get_by_key_name(self.name)
         print ' AVAILABLE: ',p.available
         self.assertEqual(p.available, p.stock - qty, 'Not reserving correctly')
     else:
         p = Product.get_by_key_name(self.name)
         print ' Not enough stock', p.available
         self.assertGreater(qty, p.available, 'Not reserving correctly')
Exemplo n.º 14
0
def create_product(request):
  kwargs = {}
  for k in request.POST:
    if k != 'csrfmiddlewaretoken':
      kwargs[k] = request.POST[k]
  product =  Product(**kwargs)
  product.save()
  for k in request.FILES:
    filename = img_utils.thumb_image('main_image', str(product.pk), request.FILES[k], (300, 273))
    setattr(product, k, filename)
  product.save()
Exemplo n.º 15
0
 def create_product(self,request):
     u = self.current_user(request)
     e = json.load(open('%s/json/elements.json'%settings.STATIC_ROOT))
     c = request.REQUEST['category']
     category = e['locale_cat'].index(c)
     credit = request.REQUEST['credit']
     name = request.REQUEST['name']
     description = request.REQUEST['description']
     product = Product(category=category,credit=credit,visual='',
     name='$$%s'%name,description=description,user=u)
     product.save()
     return redirect('productimage')
Exemplo n.º 16
0
class SaleOfferTests(TestCase):
    def setUp(self):
        self.stuff = FoodStuff(name='some stuff 3')
        self.stuff.save()

        recipe = Recipe(name='some recipe 3')
        recipe.save()

        ingredient = RecipeIngredient(
            stuff  = self.stuff,
            recipe = recipe,
            count  = 1.5
        )
        ingredient.save()

        self.product = Product(
            name   = 'some product 3',
            recipe = recipe,
            markup = 1.5
        )
        self.product.save()

        provider = FoodProvider(name='some provider')
        provider.save()

        purchase = Purchase(
            provider   = provider,
            stuff      = self.stuff,
            cost       = 200,
            unit_count = 10,
            unit_size  = 1,
        )
        purchase.save()

        self.offer = SaleOffer(product=self.product)
        self.offer.save()

    def test_str(self):
        self.assertEqual('some product 3', str(self.offer))

    def test_save_change_actual(self):
        self.assertEqual(True, self.offer.is_actual)

        offer_2 = SaleOffer(product=self.product)
        offer_2.save()

        self.offer.refresh_from_db()
        self.assertEqual(False, self.offer.is_actual)

    def test_save(self):
        self.assertEqual(30, self.offer.cost)
        self.assertEqual(50, self.offer.price)
Exemplo n.º 17
0
    def manage_settings(self, product):
        product_data = self.retrieve_product(product)
        if type(product_data) is str:
            title = "%s Manage Settings" % product.title()
            product_data = None
            form = forms.ManageProduct()
        else:
            title = "%s Manage Settings" % product_data.title
            form = forms.ManageProduct(obj=product_data)

        if request.method == 'POST' and form.validate_on_submit():
            to_save = Product(request.form.to_dict())
            if product_data and product_data.db_name:
                to_save.db_name = product_data.db_name
                to_save.groups = product_data.groups
            else:
                to_save.set_db_name()

            g.db.api_settings.update(
                {}, {
                    '$set': {
                        product: to_save.__dict__
                    }
                }
            )
            if to_save.active:
                g.db.api_settings.update(
                    {}, {
                        '$addToSet': {'active_products': product}
                    }
                )
            else:
                g.db.api_settings.update(
                    {}, {
                        '$pull': {'active_products': product}
                    }
                )

            flash('Product was successfully updated', 'success')
            return redirect('/%s/manage' % product)
        else:
            if request.method == 'POST':
                flash('Form was not saved successfully', 'error')

            return render_template(
                'manage/manage_product.html',
                title=title,
                form=form,
                product=product_data,
            )
Exemplo n.º 18
0
def upload_xml(xml):

    doc = parseString(xml)
    products = doc.getElementsByTagName("product")

    for prod in products:
        mongoProduct = Product()

        for node in prod.childNodes:
            if (node.nodeType == node.ELEMENT_NODE
                    and node.firstChild != None
                    and node.firstChild.nodeType == node.TEXT_NODE):
                nodeVal = parse_value(node.firstChild.nodeValue)
                mongoProduct.attr[node.nodeName] = nodeVal
        mongoProduct.save()
Exemplo n.º 19
0
def top_products():
    products = [str(product) for product in Product.get_top_products()]
    if products:
        return make_response(jsonify(products), 200)
    else:
        err = {"message" : "internal server error"}
        return make_response(jsonify(err), 500)
Exemplo n.º 20
0
    def test_0a_1_2_1_get_dict(self):
        product = Product(name="Cheese",
                          price=50.4,
                          quantity=7.89,
                          code=789456611)

        class tst(object):
            def __init__(self):
                self.Id = 41
                self.paSSword = "******"
                self.username = "******"
                self.bool1 = True
                self.bool2 = False
                self.nr = NotReceived()
                self.unsupported1 = {}
                self.unsupported2 = product

        validation_obj = tst()
        the_dict = get_dict(validation_obj)
        self.assertEqual(the_dict, {
            "username": "******",
            "bool1": True,
            "bool2": False
        })
        the_dict = get_dict(validation_obj, id=True, dangerous=True)
        self.assertEqual(
            the_dict, {
                "username": "******",
                "bool1": True,
                "bool2": False,
                "paSSword": "******",
                "Id": 41
            })
        print("Test 0a_1_2_1 : get_dict: with object")
Exemplo n.º 21
0
    def fetch_product_detail(product_id):

        query = Product.query.join(
            Category, Product.category_id == Category.id
        ).with_entities(
            Product.id,
            Product.reference,
            Product.name,
            Product.category_id,
            Category.name.label('category_name'),
            Product.short_description,
            Product.long_description,
            Product.price,
            Product.tags,
            Product.image_link,
            Product.active
        ).filter(
            Product.id == product_id,
            Product.active == 'Y'
        ).first()
        app.logger.info(query)

        if query is None:
            abort(404)

        product = Product.format([query])

        return jsonify({
            'success': True,
            'product': product
        })
Exemplo n.º 22
0
 def test_create_a_product(self):
     """ Create a product and assert that it exists """
     p = Product(0, 'Asus2500', 'Laptop', '34', 'laptop', 'blue', 4)
     self.assertTrue(p != None)
     self.assertEqual(p.id, 0)
     self.assertEqual(p.name, "Asus2500")
     self.assertEqual(p.category, "Laptop")
Exemplo n.º 23
0
    def check_offsale_product(self, id, url):
        prd = Product.objects(key=id).first()
        if prd is None:
            print '\n\nbelleandclive {0}, {1}\n\n'.format(id, url)
            return

        cont = self.net.fetch_product_page(url)
        if cont == -302:
            return
        elif cont is None or isinstance(cont, int):
            cont = self.net.fetch_product_page(url)
            if cont is None or isinstance(cont, int):
                print '\n\nbelleandclive product[{0}] download error.\n\n'.format(url)
                return
        else:
            tree = lxml.html.fromstring(cont)
            time = tree.cssselect('#sub-header p.countdown')[0].get('data-countdown')[:-3]
            if time:
                products_end = datetime.utcfromtimestamp( float(time) )
            else:
                products_end = datetime.utcnow() + timedelta(days=3)
            if prd.products_end != products_end:
                prd.products_end = products_end
                prd.update_history.update({ 'products_end': datetime.utcnow() })
                prd.on_again = True
                prd.save()
                print '\n\nbelleandclive product[{0}] on sale again.'.format(url)
Exemplo n.º 24
0
    def save_b(self):
        ''' add operation '''
        # entete de la facture
        if not self.table_in.isvalid:
            return False
        date = str(self.date.text())
        datetime_ = date_to_datetime(date)
        store = self.liste_store[self.box_mag.currentIndex()]
        values_t = self.table_in.get_table_items()

        for ligne in values_t:
            qty, name = ligne
            product = Product.select().where(Product.name == name).get()

            rep = Reports(orders=None, type_=Reports.E, store=store,
                          date=datetime_, product=product,
                          qty_use=int(qty))
            try:
                rep.save()
            except:
                self.parent.Notify(
                    u"Ce mouvement n'a pas pu être enrgistré dans les raports", "error")
                return False

        self.parent.change_context(GReportViewWidget)
        self.parent.Notify(u"L'entrée des articles avec succès", "success")
Exemplo n.º 25
0
    def check_onsale_product(self, id, url):
        prd = Product.objects(key=id).first()
        if prd is None:
            print '\n\nshopbop {0}, {1}\n\n'.format(id, url)
            return

        ret = self.fetch_page(url)
        if isinstance(ret, int):
            print("\n\nshopbop download product page error: {0}".format(url))
            return

        tree = lxml.html.fromstring(ret)

        listprice = price = None
        for price_node in tree.cssselect('div#productPrices div.priceBlock'):
            if price_node.cssselect('span.salePrice'):
                price = price_node.cssselect('span.salePrice')[0].text_content().replace(',', '').replace('$', '').strip()
            elif price_node.cssselect('span.originalRetailPrice'):
                listprice = price_node.cssselect('span.originalRetailPrice')[0].text_content().replace(',', '').replace('$', '').strip()

        soldout = True if tree.cssselect('img#soldOutImage') else False

        if listprice and prd.listprice != listprice:
            prd.listprice = listprice
            prd.update_history.update({ 'listprice': datetime.utcnow() })
        if prd.price != price:
            prd.price = price
            prd.update_history.update({ 'price': datetime.utcnow() })
        if prd.soldout != soldout:
            prd.soldout = soldout
            prd.update_history.update({ 'soldout': datetime.utcnow() })
        prd.save()
Exemplo n.º 26
0
def add():
    """
    Endpoint add product.
    This is using docstrings for specifications.
    ---
    responses:
      200:
        code: 200,
        description: Add product in database
    """
    if request.method == 'POST':
        data = request.get_json()
        req_sku = data["sku"]
        req_name = data["name"]
        req_price = data["price"]
        req_brand = data["brand"]
        req_stock = data["stock"]
        new_product = Product(sku=req_sku, name=req_name, price=req_price, brand=req_brand, stock=req_stock )
        db.session.add(new_product)
        db.session.commit()
        response = {
            'status': 'ok',
            'code': 200,
            'description': 'add product is ok',
        }
        response.headers.add("Access-Control-Allow-Origin", "*")
        return jsonify( response )
Exemplo n.º 27
0
    def check_offsale_product(self, id, url):
        prd = Product.objects(key=id).first()
        if prd is None:
            print '\n\nmodnique {0}, {1}\n\n'.format(id, url)
            return

        ret = fetch_product(url)
        if ret[0] == -302:
            return
        elif isinstance(ret[0], int):
            print '\n\nmodnique download error: {0} , {1}\n\n'.format(ret[0], ret[1])
            return

        soldout = None
        tree = lxml.html.fromstring(ret[0])
        text = tree.cssselect('#soldout a span')[0].text_content().strip()
        if 'Add To Waitlist' in text:
            soldout = True
        elif 'sold out' in text:
            soldout = True
        elif 'size sold' in text:
            soldout = False
        if soldout is False:
            print '\n\nmodnique product[{0}] on sale again.'.format(url)
            # no specific time, so add 3 days, If it off sale, can be fond by offsale function
            products_end = datetime.utcnow() + timedelta(days=3)
            prd.products_end = products_end
            prd.update_history.update({ 'products_end': datetime.utcnow() })
            prd.on_again = True
            prd.save()
Exemplo n.º 28
0
def delete_products(request, id):
    try:
        product = ProductExists(id=id)
    except Exception as e:
        return jsoinify_error(e)
    product = Product.query().get(product.id).delete()
    return {"suucess": True, "result": "product deleted successfully"}
Exemplo n.º 29
0
    def test_process_item_existing_product(self):
        existing_product = Product(
            store=self.item["store"],
            sku=self.item["sku"],
            brand=self.item["brand"],
            name=self.item["name"],
            description=self.item["description"],
            package=self.item["package"],
            image_url=self.item["image_url"],
        )

        self.session.add(existing_product)
        self.session.commit()

        pipeline = StoragePipeline(db_engine=self.engine)
        pipeline.open_spider(self.spider)
        pipeline.process_item(self.item, self.spider)
        pipeline.close_spider(self.spider)

        product = (
            self.session.query(Product)
            .filter_by(store=self.item["store"], sku=self.item["sku"])
            .first()
        )
        self.assertEqual(product, existing_product)
        branch_product = (
            self.session.query(BranchProduct)
            .filter_by(product=product, branch=self.item["branch"])
            .first()
        )
        self.assertIsNotNone(branch_product)
Exemplo n.º 30
0
def get_products(request, id):
    try:
        product_id = ProductExists(id=id)
    except Exception as e:
        return jsoinify_error(e)
    product = Product.query().get(product_id.id)
    return {"suucess": True, "product": product.deep()}
Exemplo n.º 31
0
def compare(days_count : int):
    TODAY_PRICE = 0
    PAST_PRICE = 1
    days = [day.date for day in Price.select().distinct(Price.date)] # Get all days 
    
    if days_count >= len(days):
        print(f"Parser has only {len(days)} day(s) info")
        return
    elif days_count <= 0:
        print(f"Error with days_count <= 0")
        return
    else:
        for product in Product.select().execute():
            today_prices = Price.select().where((Price.date == date.today()) & (Price.product == product.id)).order_by(Price.shop).execute()
            past_prices = Price.select().where((Price.date == days[-days_count-1]) & (Price.product == product.id)).order_by(Price.shop).execute()
            
            print('-------')
            for prices in zip(today_prices, past_prices):
                print("Price for {:s} has {:s} by {:.2f} in shop '{:s}' for {:s} user".format(
                    prices[TODAY_PRICE].product.group, 
                    'increased' if prices[TODAY_PRICE].price > prices[PAST_PRICE].price 
                        else 'decreased' if prices[TODAY_PRICE].price < prices[PAST_PRICE].price else 'not changed', 
                    prices[TODAY_PRICE].price - prices[PAST_PRICE].price 
                        if prices[TODAY_PRICE].price >= prices[PAST_PRICE].price 
                        else prices[PAST_PRICE].price - prices[TODAY_PRICE].price, 
                    prices[TODAY_PRICE].shop,
                    'authorized' if prices[TODAY_PRICE].authorized
                    else 'not authorized'))
Exemplo n.º 32
0
def parse_price():
    request_green = requests.Session()
    request_evroopt = requests.Session()

    authorized_request_green = green_parser.authorize(requests.Session())
    authorized_request_evroopt = e_parser.authorize(requests.Session())

    if date.today() in [price.date for price in Price.select().execute()]:
        return
    else:
        products = Product.select().order_by(Product.id).execute()
        bar = Bar('Parse prices', max=len(products))
        
        for product in products:
            with conn.atomic() as trn:
                try:
                    main_parser(green_parser, request_green, product.id, product.link_g)
                    main_parser(green_parser, authorized_request_green, product.id, product.link_g)
                    main_parser(e_parser, request_evroopt, product.id, product.link_e)
                    main_parser(e_parser, authorized_request_evroopt, product.id, product.link_e)
                except AttributeError:
                    trn.rollback()
                finally:
                    bar.next()
        bar.finish()
Exemplo n.º 33
0
    def check_offsale_product(self, id, url):
        prd = Product.objects(key=id).first()
        if prd is None:
            print '\n\nnomorerack {0}, {1}\n\n'.format(id, url)
            return

        cont = self.fetch_product_offsale_page(url)
        if isinstance(cont, int):
            print '\nnomorerack off sale page[{0}] return: {1}\n'.format(url, cont)
            return
        tree = lxml.html.fromstring(cont)
        offsale = tree.cssselect('div#content div#front div#primary div#products_view div.right div.add_to_cart div#add_to_cart div.error_message')
        offsale = 'not available' in offsale[0].text_content() if offsale else False
        products_end = self.parse_time(tree, cont)
        if offsale is True and (not prd.products_end or prd.products_end > datetime.utcnow()):
            tt = products_end if products_end else datetime.utcnow()
            if tt.year !=  prd.products_end.year:
                return
            print 'nomorerack product[{0}] products_end error: [{1} vs {2}]'.format(url, prd.products_end, products_end)
            prd.products_end = datetime(tt.year, tt.month, tt.day, tt.hour, tt.minute)
            prd.update_history.update({ 'products_end': datetime.utcnow() })
            prd.on_again = True
            prd.save()
        elif products_end and prd.products_end != products_end:
            if products_end.year !=  prd.products_end.year:
                return
            print 'nomorerack product[{0}] products_end error: [{1} vs {2}]'.format(url, prd.products_end, products_end)
            prd.products_end = products_end
            prd.update_history.update({ 'products_end': datetime.utcnow() })
            prd.on_again = True
            prd.save()
Exemplo n.º 34
0
def create_test_prod():
    cat = Category(name='sale', friendly_name='sale')
    cat.save()
    product = Product(
        category=cat,
        sku='111111',
        name='test',
        description='Test Description',
        price='10.99',
        image='img.jpg',
    )

    # save product

    product.save()
    return (product, cat)
Exemplo n.º 35
0
    def check_offsale_product(self, id, url):
        prd = Product.objects(key=id).first()
        if prd is None:
            print '\n\ngilt {0}, {1}\n\n'.format(id, url)
            return

        ret = self.s.get(url, headers=self.headers)
        if ret.url == 'http://www.gilt.com/' or ret.content == '':
            prd.soldout = True
            prd.update_history.update({ 'soldout': datetime.utcnow() })
            prd.save()
            return
        tree = self.get_correct_tree(ret.content)

        soldout = True
        sizes = tree.cssselect('#sku-selection .sku-attribute .sku-attribute-values li')
        count = len(sizes)
        for size in sizes:
            if 'for_sale' in size.get('class'):
                soldout = False
        if soldout is False:
            print '\n\ngilt product[{0}] on sale again.'.format(url)
            if prd.soldout != soldout:
                prd.soldout = soldout
                prd.update_history.update({ 'soldout': datetime.utcnow() })
            prd.products_end = datetime.utcnow() + timedelta(days=3)
            prd.update_history.update({ 'products_end': datetime.utcnow() })
            prd.on_again = True
            prd.save()
Exemplo n.º 36
0
def add_product():
    """Adds a new product to the database."""
    new_products = request.get_json()
    for new_product in new_products:
        try:
            if set(new_product.keys()) != set(constants.MANDATORY_PRODUCT_FIELDS):
                raise errors.InvalidRequestParametersError
            brand_id = helpers.check_brand(new_product['brand_name'])
            category_id = helpers.check_category(new_product['category_name'])
            float(new_product['price'])
            float(new_product['discount'])
            int(new_product['discount'])
            int(new_product['price'])
        except ValueError:
            raise errors.InvalidRequestParametersError
        except errors.InvalidRequestParametersError:
            return format_response('Mandatory field is missing', 422)
        products = Product(
            product_name=new_product['product_name'],
            price=new_product['price'],
            discount=new_product['discount'],
            quantity=new_product['quantity'],
            created_at=datetime.datetime.now(),
            updated_at=datetime.datetime.now(),
            brand_id=brand_id,
            category_id=category_id
        )
        db.session.add(products)
    db.session.commit()
    return format_response("Product(s) Added", 200)
Exemplo n.º 37
0
    def check_onsale_product(self, id, url):
        prd = Product.objects(key=id).first()
        if prd is None:
            print '\n\nventepricee {0}, {1}\n\n'.format(id, url)
            return

        ret = self.net.fetch_page(url)
        if isinstance(ret, int):
            ret = self.net.fetch_page(url)
            if isinstance(ret, int):
                print '\n\nventeprivee product[{0}] download error.\n\n'.format(url)
                return
        js = ret.json
        brand = js['operationName']
        title = js['name']
        if prd.title.lower() != title.lower():
            print 'venteprivee product[{0}] title error: {1}, {2}'.format(prd.combine_url, prd.title, title)
        price = js['formattedPrice']
        if prd.price != price:
            print 'venteprivee product[{0}] price error: {1}, {2}'.format(prd.combine_url, prd.price, price)
        listprice = js['formattedMsrp']
        if prd.listprice != listprice:
            print 'venteprivee product[{0}] listprice error: {1}, {2}'.format(prd.combine_url, prd.listprice, listprice)
        soldout = js['isSoldOut']
        if prd.soldout != soldout:
            print 'venteprivee product[{0}] soldout error: {1}, {2}'.format(prd.combine_url, prd.soldout, soldout)
            prd.soldout = soldout
            prd.update_history.update({ 'soldout': datetime.utcnow() })
            prd.save()
Exemplo n.º 38
0
 def generate_products(self, categories):
     """
         This method creates a list of Product Objects for a specified list of categories, to be inserted in the
         database by the controller
             categories : list or str
             products : list
     """
     if type(categories) == str:
         categories = [categories]
     products = []
     for index, category in enumerate(categories, 1):
         category_id = self.get_category_id(category)
         for page in range(1, self.get_pages_count(category) + 1):
             for i in self.get_products(page, category):
                 if "nutrition-facts-completed" in i["states"] and "product-name-completed" in i["states"] and "brands-completed" in i["states"] and "nutriscore_score" in i and "id" in i and "stores" in i:
                     try:
                         i["brands"].index(",")
                         multiple_brands = True
                     except ValueError:
                         multiple_brands = False
                     products.append(
                         Product(
                             ref_id=i["id"],
                             name=i["product_name"].replace("\n", ""),
                             brand=i["brands"][:i["brands"].index(",")]
                             if multiple_brands else i["brands"],
                             nutriscore=i["nutriscore_score"],
                             category_id=category_id,
                             retailer=i["stores"],
                             url=i["url"]))
             if len(products) > index * 400:
                 break
     return products
Exemplo n.º 39
0
    def save_report(self):
        ''' add operation '''
        # entete de la facture
        self.table_out.changed_value()
        if not self.table_out.isvalid:
            return False
        date_out = str(self.date_out.text())
        datetime_ = date_to_datetime(date_out)
        self.current_store = self.liste_store[self.box_store.currentIndex()]

        values_t = self.table_out.get_table_items()

        for qty, name in values_t:
            rep = Reports(type_=Reports.S, store=self.current_store,
                          date=datetime_, product=Product.get(name=name),
                          qty_use=int(qty))
            try:
                rep.save()
            except:
                self.parent.Notify(
                    u"Ce mouvement n'a pas pu être enrgistré dans les raports", "error")
                return False

        self.parent.change_context(GReportViewWidget)
        self.parent.Notify(u"La sortie des articles avec succès", "success")
Exemplo n.º 40
0
def process_order_pizza():

    toppings = [val for key, val in request.form.items() if 'add_' in key]

    #quantity of pizza's being added
    quantity = int(request.form['pizza_quantity'])

    #calculate pizze price
    pizza_price = PizzaSizePrice.query.filter_by(
        size=request.form['pizza_size']).first().price

    #now add price of toppings (all toppings are 0.5c for now)
    toppings_price = 0.5 * len(toppings)

    total_price = (pizza_price + toppings_price) * quantity
    print(total_price)
    #create a new product and get the id
    new_product_id = Product.create_product(type='pizza',
                                            order_id=session['currOrder_id'],
                                            product_price=total_price,
                                            quantity=quantity)

    #create a new pizza and get the object back to add toppings
    new_pizza_obj = Pizza.create_pizza(request.form, new_product_id,
                                       pizza_price)

    for item in toppings:
        currTopping = Topping.query.filter_by(name=item).first()
        new_pizza_obj.toppings_on_this_pizza.append(currTopping)
        db.session.commit()

    return redirect(f"/checkout/{session['currOrder_id']}")
Exemplo n.º 41
0
 def test_0a_1_2_4_MyModel(self):
     #Trying to add the product with id, and seeing how the d will be neglected
     product = Product(name="Cheese",
                       price=50.4,
                       quantity=7.89,
                       id=10000000,
                       code=789456611)
     self.assertEqual(
         product.simple(), {
             "id": None,
             "name": "Cheese",
             "price": 50.4,
             "quantity": 7.89,
             "code": 789456611
         })
     print("Test 0a_1_2_4 : MyModel: success")
Exemplo n.º 42
0
def import_data():
    session = Session()
    client = OpenFoodFactsApi()
    categories = client.get_categories()

    for category in categories:
        category_name = Category(name=category)
        products = client.get_products(category)
        # insert data to Product, Store, Brand
        for product in products:
            p = session.query(Product).filter(
                Product.name == product.get("product_name")).first()
            print(p)
            if not product.get("product_name"):
                continue
            brand_insert = get_or_create_brand(session, product.get("brands"),
                                               product.get("label"))
            product_data = Product(name=product.get("product_name"),
                                   nutriscore=product.get("nutrition_grades"),
                                   nova=product.get("nova_groups_tags"),
                                   url=product.get("url"),
                                   barcode=product.get("code"),
                                   brand=brand_insert)

            for store_name in product.get("stores").split(","):
                store = Store(name=store_name)
                product_data.stores.append(store)
            product_data.categories.append(category_name)
        session.add(product_data)
    session.commit()
    session.close()
Exemplo n.º 43
0
    def test_0a_1_2_3_get_dict(self):
        product = Product(name="Cheese",
                          price=50.4,
                          quantity=7.89,
                          code=789456611)
        the_dict = {
            "Id": 41,
            "paSSword": "******",
            "username": "******",
            "bool1": True,
            "bool2": False,
            "nr": NotReceived(),
            "unsupported1": {},
            "unsupported2": product
        }
        validated = get_dict(the_dict, id=True, dangerous=True)
        self.assertEqual(
            validated, {
                "username": "******",
                "bool1": True,
                "bool2": False,
                "paSSword": "******",
                "Id": 41
            })

        validated = get_dict(the_dict)
        self.assertEqual(validated, {
            "username": "******",
            "bool1": True,
            "bool2": False
        })
        print("Test 0a_1_2_3 : get_dict: with dict")
Exemplo n.º 44
0
def seed_products():
   products = ["Sheets", "Detergent", "Paper towels", "Coke", "Fan", "Bag", "Bulbs", "Batteries", "Deodrant", "Pillow"]
   descriptions = ["Stay warm", "Top load detergent, very strong", "Soft and powerful", "Refreshing carbonated drink", "Get a fan this summer",
   "water-proof bag", "Lights up your world", "Long lasting batteries", "24 hour freshness", "Soft and comfortable for a good nights sleep"]
   for i in range(len(products)):
      db.session.add(Product(name=products[i], description=descriptions[i]))
   db.session.commit()
Exemplo n.º 45
0
    def test_0a_1_1_8_validate_key(self):
        product = Product(name="Cheese",
                          price=50.4,
                          quantity=7.89,
                          code=789456611)

        class tst(object):
            def __init__(self):
                self.Id = 41
                self.paSSword = "******"
                self.username = "******"
                self.bool1 = True
                self.bool2 = False
                self.nr = NotReceived()
                self.unsupported1 = {}
                self.unsupported2 = product

        validation_obj = tst()
        validated = []
        for key in [
                "Id", "paSSword", "username", "bool1", "bool2", "nr",
                "unsupported1", "unsupported2"
        ]:
            validated.append(
                validate_key(validation_obj, key, unsupported=False))
        self.assertEqual([False, False, True, True, True, False, False, False],
                         validated)
        print("Test 0a_1_1_8 : validate_key: with object")
Exemplo n.º 46
0
def shop():
    data = []
    if request.method == "POST":
        f = request.files['file']
        filename = upload_img(f)
        new_product = Product(request.form['name'], request.form['title'],
                              filename, request.form['price_eggs'],
                              request.form['price_coins'],
                              request.form['price_voices'],
                              request.form['price_old'], request.form['new'],
                              request.form['timer'])
        session.add(new_product)
        session.commit()
        return redirect('shop')
    else:
        for instance in session.query(Product):
            line = {
                'id': instance.id,
                'name': instance.name,
                'title': instance.title,
                'price': instance.price,
                'price_old': instance.price_old,
                'new': instance.is_new,
                'timer': instance.timer_end,
                'img': instance.img_addr,
                'is_del': instance.is_del
            }
            data.append(line)
        return render_template('shop.html', data=data)
Exemplo n.º 47
0
    def setUp(self):
        self.stuff = FoodStuff(name='some stuff 3')
        self.stuff.save()

        recipe = Recipe(name='some recipe 3')
        recipe.save()

        ingredient = RecipeIngredient(
            stuff  = self.stuff,
            recipe = recipe,
            count  = 1.5
        )
        ingredient.save()

        self.product = Product(
            name   = 'some product 3',
            recipe = recipe,
            markup = 1.5
        )
        self.product.save()

        provider = FoodProvider(name='some provider')
        provider.save()

        purchase = Purchase(
            provider   = provider,
            stuff      = self.stuff,
            cost       = 200,
            unit_count = 10,
            unit_size  = 1,
        )
        purchase.save()

        self.offer = SaleOffer(product=self.product)
        self.offer.save()
Exemplo n.º 48
0
 def get(self, subdomain=None):
     #args
     item = self.request.get('item','-')
     qty = int(self.request.get('qty',1))
     
     '''NAMESPACE CHANGE (memcache and datastore)'''
     namespace = namespace_manager.get_namespace()
     namespace_manager.set_namespace(subdomain)
     
     #15 mins session (900 secs), if a previous session does not exist it creates a new one
     self.session = self.session_store.get_session(name='mc_session',max_age=900,backend='memcache')
     try:
         cart = self.session['cart']
         logging.info('cart found in memcache :)')
     except:
         return self.response.write('Not cart in session or the session has expired')
         
     
     product = Product.get_by_key_name(item)
     
     if not product: return self.response.write('The product does not exist')
     elif product.unreserve(qty):
         '''It was not removed from stock'''
         cart.remove_item(CartItem(product),qty)
     else:
         self.response.write('Some products were not reserved. Probably the session expired')
         
         
     self.session['cart'] = cart
     self.session_store.save_sessions(self.response)
     '''NAMESPACE CHANGE'''
     namespace_manager.set_namespace(namespace)
     
     return self.response.write(str(cart))
Exemplo n.º 49
0
    def set_data_for(self, main_date):

        try:
            on, end = main_date.current.current
        except:
            on, end = main_date.current
        on = datetime(on.year, on.month, on.day, 0, 0, 0)
        end = datetime(end.year, end.month, end.day, 23, 59, 59)
        reports = []
        this_periode_rpt = Reports.select().where(Reports.date >= on,
                                                  Reports.date <= end)
        for store in Store.select().order_by(Store.name):
            if ([(i) for i in this_periode_rpt.where(Reports.store << [store, ])] == []):
                continue
            cpt = 0
            for prod in Product.select().order_by(Product.name):
                if ([(i) for i in this_periode_rpt.where(Reports.store == store,
                                                         Reports.product << [prod, ])] == []):
                    continue
                dict_store = {}
                repts = this_periode_rpt.where(
                    Reports.store == store, Reports.product == prod)
                dict_store["store"] = store.name if cpt < 1 else ""
                dict_store["product"] = prod.name
                dict_store["sum_qty_in"] = repts.select(
                    peewee.fn.SUM(Reports.qty_use)).where(Reports.type_ == Reports.E).scalar()
                dict_store["sum_qty_out"] = repts.select(
                    peewee.fn.SUM(Reports.qty_use)).where(Reports.type_ == Reports.S).scalar()
                cpt += 1
                reports.append(dict_store)

        self.data = [(rep.get('store'), rep.get('product'), rep.get('sum_qty_in'),
                      rep.get('sum_qty_out')) for rep in reports]
Exemplo n.º 50
0
def manageprodlist():
    if ((g.user.role != ROLE_WEBDEV) and (g.user.role != ROLE_ADMIN)):
        flash(
            'Only an Administrator or Users with Web Developer Roles can access this page'
        )
        return redirect(url_for('index'))

    form = prod_form()

    if form.validate_on_submit():
        prod = Product(name=str(form.product_name.data))
        check_prod = Product.query.filter_by(name=prod.name).first()
        if not check_prod:
            db.session.add(prod)
            db.session.commit()
            all_products = Product.query.all()
            flash('New Product Added')
        else:
            flash('Product with this name already exists')

        return redirect(url_for('manageprodlist'))

    all_products = Product.query.all()
    return render_template('prodlist.html',
                           title='Product List',
                           prods=all_products,
                           form=form)
Exemplo n.º 51
0
def createNewProduct():
    user = User.query.get(request.data['id'])
    if not user.is_admin:
        return jsonify({'message': 'only a admin can access this route'})
    data = request.json
    category = Category.query.filter_by(name=data['category_name']).first()
    if not category:
        return jsonify({'message': 'Please enter a valid category'})
    newProduct = Product(product_name=data['product_name'],
                         description=data['description'],
                         brand=data['brand'],
                         discount=data['discount'],
                         regular_price=data['regular_price'],
                         category_id=category.id,
                         image=data['image'])
    db.session.add(newProduct)
    db.session.commit()
    if (data['details']):
        print('gonna start entering the product details')
        for detail in data['details']:
            prod_details = ProductDetails(product_id=newProduct.id,
                                          size=detail['size'],
                                          quantity=detail['quantity'])
            db.session.add(prod_details)
            db.session.commit()
    return jsonify(product_schema.dump(newProduct))
Exemplo n.º 52
0
    def test_a_1_010_product_delete_relationships(self):
        #measuring lengths beofre actions
        #populate_tables()
        products_before = len(Product.query().all())
        categories_before = len(Category.query().all())
        pc_before = len(ProductCategory.query().all())

        # deleting the product
        prod_to_del = Product.query().get(1)

        prod_to_del.delete()
        self.assertEqual(len(Product.query().all()), products_before - 1)
        self.assertEqual(len(Category.query().all()), categories_before)
        self.assertEqual(len(ProductCategory.query().all()), pc_before - 5)

        print("Test a_1_10: product delete relationships")
Exemplo n.º 53
0
 def save(self):
     # print(self.data)
     # product_obj = self.data
     uid = uuid.uuid4(),
     name = self.name.data
     desc = self.desc.data
     content = self.content.data
     types = self.types.data
     price = self.price.data
     origin_price = self.origin_price.data
     # img = self.img.data
     img = '/xxx.jpg'
     img_list = self.img_list.data
     channel = self.channel.data
     buy_link = self.buy_link.data
     buy_qr_code = self.buy_qr_code.data
     status = self.status.data
     sku_count = self.sku_count.data
     remain_count = self.remain_count.data
     view_count = self.view_count.data
     score = self.score.data
     reorder = self.reorder.data
     is_valid = self.is_valid.data
     try:
         product_obj = Product(uid=uid, name=name, desc=desc, content=content, types=types, price=price,
                               origin_price=origin_price, img=img, img_list=img_list, channel=channel,
                               buy_link=buy_link, buy_qr_code=buy_qr_code, status=status, sku_count=sku_count,
                               remain_count=remain_count, view_count=view_count, score=score, reorder=reorder,
                               is_valid=is_valid)
         db.session.add(product_obj)
         db.session.commit()
         return product_obj
     except Exception as e:
         print(e)
     return None
Exemplo n.º 54
0
    def saveDatabase(self, item):
        try:
            product = Product(store="Richart's",
                              barcodes=item['barcodes'],
                              sku=str(item['sku']),
                              brand=item['brand'],
                              name=item['name'],
                              description=item['description'],
                              package=item['package'],
                              categories=item['categories'],
                              image_urls=item['image_urls'])

            branch = BranchProduct(
                branch=item['store'],
                product=product,
                stock=item['stock'],
                price=float(item['price']),
            )

            self.session.add(product)
            self.session.commit()
            return item

        except IntegrityError as e:
            self.session.rollback()
            return None
Exemplo n.º 55
0
    def set_data_for(self, prod_find):

        products = Product.select().order_by(Product.name.asc())
        if prod_find:
            products = products.where(Product.name.contains(prod_find))

        self.data = [("", prod.name, "") for prod in products]
Exemplo n.º 56
0
def up():
    for item in seed:
        product = Product(**item["init"])

        db.session.add(product)

    db.session.commit()
Exemplo n.º 57
0
def get_all_product():
    try:
        data = [[p.name, p.category.name, p.price] for p in Product.select()]

        return data
    except peewee.DoesNotExist:
        return None
Exemplo n.º 58
0
def fill_products(products_file):
    with open(products_file, mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        for row in csv_reader:
            p = Product(asin=row["Asin"], title=row["Title"])
            db.session.add(p)
        db.session.commit()
Exemplo n.º 59
0
    def new_product(product_dict):
        publishing_house = PublishingHouse.query.filter_by(name=product_dict['publishing_house_name']).first()
        if publishing_house is None:
            publishing_house = PublishingHouse(product_dict['publishing_house_name'])
            publishing_house.save_data()
            publishing_house_id = PublishingHouse.query.filter_by(name=product_dict['publishing_house_name']).first().id
        else:
            publishing_house_id = publishing_house.id

        product_type = Type.query.filter_by(product_type=product_dict['type']).first()
        if product_type is None:
            product_type = Type(product_dict['type'])
            product_type.save_data()
            product_type_id = Type.query.filter_by(product_type=product_dict['type']).first().id
        else:
            product_type_id = product_type.id

        product = Product(product_dict['title'],
                          product_dict['publishing_year'],
                          product_dict['quantity_in_stock'],
                          publishing_house_id,
                          product_type_id)
        if product_type.product_type == "книга":
            for author_name in product_dict['authors']:
                author = Author.query.filter_by(name=author_name).first()
                if author is None:
                    author = Author(author_name)
                    db.session.add(author)
                    db.session.commit()
                    product.authors.append(author)
                else:
                    product.authors.append(author)
        db.session.add(product)
        db.session.commit()
Exemplo n.º 60
0
def load_from_csv():
    engine = create_engine(Config().SQLALCHEMY_DATABASE_URI,
                           convert_unicode=True)
    db_session = scoped_session(sessionmaker(bind=engine))
    Base.query = db_session.query_property()
    with open('example.csv', newline='') as file:
        reader = csv.reader(file)
        for row in reader:
            r = [it.strip().lower() for it in row]
            levels = r[:-1]
            item = r[-1]
            prev_product_group = None
            if not Product.query.filter_by(title=item).first():
                for level in levels:
                    product_group = ProductGroup.query.filter_by(
                        title=level).first()
                    if not product_group:
                        product_group = ProductGroup(level)
                        if prev_product_group:
                            product_group.parent_id = prev_product_group.id
                        db_session.add(product_group)
                        db_session.commit()
                    prev_product_group = product_group
                new_product = Product(item, prev_product_group.id)
                db_session.add(new_product)
                db_session.commit()