Beispiel #1
0
 def post(self):
   """HTML POST handler.
   
   Check the query parameters for the name of the product, then make it."""
   
   template_values = self.build_template_values()
   
   if not template_values[handlers.base.PROFILE_KEY]:
     return self.forbidden()
   elif not template_values[handlers.base.PROFILE_KEY].is_publisher:
     return self.forbidden()
   
   name = self.request.get('name')
   description = self.request.get('description')
   link = self.request.get('link')
   if (not name) or (not link) or (not description):
     return self.forbidden()
   
   product = Product()
   product.creator = template_values[handlers.base.PROFILE_KEY]
   product.name = name
   product.link = link
   product.description = description
   product.generate_access_code()
   product.put()
   
   template_values[handlers.base.PROFILE_KEY].products.append(product.key().id())
   template_values[handlers.base.PROFILE_KEY].put()
   
   return self.redirect(self.uri_for('profile.edit'))
Beispiel #2
0
    def create_stock(self, product_id: int, location: str,
                     qty: int) -> StockItemDalModel:
        """
        Creates stock but first checks for existing items to avoid duplicates

        :param product_id: The id of the product to use
        :param location: The location within the warehouse
        :param qty: The number of product at the location
        :return: The stock DAL model
        """

        product = Product.get_by_id(product_id)
        if product is None:
            raise Exception("Product cannot be None when creating stock")

        try:
            stock_item = StockItem.select().where(
                StockItem.product_id == product_id,
                StockItem.location == location).get()

            stock_item.quantity = qty
            stock_item.save()
        except DoesNotExist:
            stock_item = StockItem.create(location=location,
                                          quantity=qty,
                                          product=product)

        return StockItemDalModel.create_from_model(stock_item)
Beispiel #3
0
def update_oss_table():
    # Fetch all distinct vendor, product tuples from the main table.
    unique_products = db.session.query(Cpe.vendor, Cpe.product)
    unique_products = unique_products.select_from(
        join(Nvd, Cpe).outerjoin(Vulnerability,
                                 Vulnerability.cve_id == Nvd.cve_id))
    unique_products = unique_products.filter(Vulnerability.cve_id.isnot(None))
    unique_products = unique_products.distinct(Cpe.vendor, Cpe.product)
    # Fetch only entries which are not already contained in OpenSourceProducts.
    unique_products = unique_products.outerjoin(
        Product,
        and_(Cpe.vendor == Product.vendor, Cpe.product == Product.product))
    unique_products = unique_products.filter(Product.vendor.is_(None))
    dump_query(unique_products)

    # We don't do any updates for now.
    created = 0
    for entry in unique_products:
        new_entry = Product(vendor=entry.vendor,
                            product=entry.product,
                            is_open_source=True)
        db.session.add(new_entry)
        sys.stdout.write(".")
        sys.stdout.flush()
        created += 1
    db.session.commit()
    print("")
    sys.stdout.write("created(")
    write_highlighted(created, Fore.GREEN, False)
    sys.stdout.write(")")
    def delete_product(self, id: int):
        """
        Deletes the specified product from the database

        :param id: The id of the product to delete
        """
        model = Product.get(Product.id == id)
        model.delete_instance()
Beispiel #5
0
    def get_total_product_stock(self, product_id: int) -> int:
        """
        Gets a count of all stock stored for a product

        :param product_id: The id of the product
        :return: The total stock stored
        """
        return Product.get_by_id(product_id).stock.count
Beispiel #6
0
    def test_get_stock_item_returns_stock_item(self):
        repo = StockRepository(DatabaseManager())

        db_product = Product(name="iPhone X", description="Apple iPhone\nwith FaceID", target_stock=3)
        db_product.save()

        db_stock = StockItem(location="A3", quantity=4, product=db_product)
        db_stock.save()

        expected = StockItemDalModel(db_stock.id, db_stock.location, db_stock.quantity, db_product.id)
        expected.product = ProductDalModel(db_product.id, db_product.name,
                                           db_product.description, db_product.target_stock)

        # Act
        stock_item: StockItemDalModel = repo.get_stock_item(db_stock.id)

        # Assert
        self.assertEqual(stock_item, expected)
    def get_all_products(self) -> [ProductDalModel]:
        """
        Retrieves all products from the database and converts to DAL model

        :return: A list of all products
        """
        products = Product.select()
        dal_models = [ProductDalModel.create_from_model(p) for p in products]
        return dal_models
Beispiel #8
0
    def get_stock_for_product(self, product_id: int) -> [StockItemDalModel]:
        """
        Gets all of the stock items for the specified product

        :param product_id: The id of the product
        :return: List of products stock
        """
        p = Product.get_by_id(product_id)
        dal_models = [StockItemDalModel.create_from_model(m) for m in p.stock]
        return dal_models
    def get_product(self, id: int) -> ProductDalModel:
        """
        Retrieves a product from the database with the specified id

        :param id: The id of the product to retrieve
        :return: The product
        """
        product_model = Product.get(Product.id == id)
        product = ProductDalModel.create_from_model(product_model)
        return product
    def get_all_orders(self) -> List[OrderDalModel]:
        """
        Get all orders in the database

        :return: A list of all orders in the database
        """
        orders = Order.select()
        product_orders = (ProductOrder.select())
        order_models = orders.prefetch(product_orders, (Product.select()))
        dal_models = [OrderDalModel.create_from_model(m) for m in order_models]

        return dal_models
Beispiel #11
0
def displayfunc(request):
    pro1 = Product(
        title="Float Recliner",
        price_reg="Rs 750/month",
        description=
        "Rent our Float, a neutral fabric recliner, which merges seamlessly with any decor in your home.",
        qauntity=8,
        image="ridada",
        weight=40,
        depth=90,
        width=80,
        height=110,
        price_sale="Rs 550/month",
        bestseller="yes",
        status="available",
        productlink="/sofa/bcde/",
        category="sofa")

    pro = User(name="Rishab",
               email="*****@*****.**",
               password="******",
               number=9971775086,
               pincode=110032,
               city="Delhi",
               address="1/757 West rohtash nagar shahdara",
               state="Delhi")

    # Product.objects.all().delete()
    # for xyz in range(1,20):
    #    Product.objects.filter(id=xyz).delete()
    design = ""

    # design ='Printing all Dreamreal entries in the DB : <br>'
    # a = Product.objects.get(title="Dhyanachand Bed (Brown)")
    # design +=a.price_sale + "<br>"
    # list1=["1000","899","899","800","750","750",]
    # i=0
    b = User.objects.get(email="*****@*****.**")
    c = b.id

    objects = UserPurchase.objects.filter(email=c)
    for a in objects:
        # xyz.price_reg=list1[i]
        design += a.productid + "<br>"

    # objects = TestModels.objects.all()
    # for xyz in objects:
    #     p=xyz.price
    #     p= str(p)
    #     p = p + "<br>"
    #     design += p
    return HttpResponse(design)
Beispiel #12
0
    def post(self):
        if not self._check_params():
            raise AppException(ret_msg='missing some parameters')

        if self.request_body['type'] == 'product' and self.request_body[
                'action'] == 'add':
            try:
                for items in self.request_body['data']:
                    products = Product(**items)
                    self.sessions.add(products)
                    self.sessions.commit()
            except Exception as e:
                raise AppException(ret_msg='failed, exception: %s' %
                                   e.__str__())
            self.jsonify(ret_msg=u"success")

        if self.request_body['type'] == 'product' and self.request_body[
                'action'] == 'query':
            result = []
            if isinstance(self.request_body['data'], unicode):
                for items in self.sessions.query(Product).all():
                    result.append({
                        'f_id': items.f_id,
                        'f_name': items.f_name,
                        'f_description': items.f_description
                    })

            if isinstance(self.request_body['data'], list):
                for items in self.request_body['data']:
                    tmp = None
                    if items.has_key('f_id'):
                        tmp = self.sessions.query(Product).filter(
                            Product.f_id == int(items['f_id'])).one_or_none()

                    if items.has_key('f_name'):
                        tmp = self.sessions.query(Product).filter(
                            Product.f_name == items['f_name']).one_or_none()
                    if tmp:
                        result.append({
                            'f_id': tmp.f_id,
                            'f_name': tmp.f_name,
                            'f_description': tmp.f_description
                        })

            self.jsonify(ret_msg=u"success", data=result)

        if self.request_body['type'] == 'product':
            raise AppException(ret_msg=u'unsupported action')

        raise AppException(ret_msg=u'type error')
    def edit_product(self, product: ProductDalModel) -> ProductDalModel:
        """
        Updates the product in the database

        :param product: The product to update with the new values set
        :return: The new product
        """

        model = Product.get(Product.id == product.id)
        model.name = product.name
        model.description = product.description
        model.target_stock = product.target_stock
        model.save()

        return ProductDalModel.create_from_model(model)
def product_view(request):
    if request.method == 'POST':
        form = NewProductForm(request.POST)
        print("errors in create/views.py")
        print(form.errors)
        print(form.non_field_errors)
        if form.is_valid():
            cform = form.cleaned_data
            print(cform)
            new_product = Product(product_name=cform['product_name'],
                                  product_description=cform['product_desc'],
                                  price=cform['price'],
                                  genre=cform['genre'],
                                  release_date=cform['release_date'],
                                  stock=cform['stock'],
                                  merchant_id=cform['merchant_id'],
                                  developer_id=cform['developer_id'])
            new_product.save()

            return redirect('/search/product/' + str(new_product.id))
    else:
        form = NewProductForm()
    context = {'form': form, 'is_logged_in': True}
    return render(request, 'create/newProduct.html', context)
    def create_product(self, name: str, description: str,
                       target_stock: int) -> ProductDalModel:
        """
        Creates a product in the database and assigns an id

        :param name: The name of the product
        :param description: An explanation of the product
        :param target_stock: The ideal stock level
        :return: The new product
        """
        model = Product.create(name=name,
                               description=description,
                               target_stock=target_stock)
        product = ProductDalModel.create_from_model(model)

        return product
def __process_request(user):
    parser = FormParser()
    parser.discover_values()
    code = parser.get_value("code", "")
    descr = parser.get_value("descr", "")
    price = parser.get_value("price", "")
    if __validate_properties(code, descr, price):
        return False
    else:
        product = Product(0, user.user_id, code, current_date(), \
        descr, float(price) if is_float(price) else 0)

        conn = Connection()
        if not conn.create_product(product):
            __ERRORS[constants.VALIDATION_ERROR] = conn.errors()
            return False
    return True
Beispiel #17
0
 def fetch_products_by_user_id(self, user_id):
     """Fetch all products from a specic user"""
     self.__open_connection()
     cursor = self.__db.cursor()
     result = []
     try:
         sql_query = """select code,descr,price,entry_date,image_path from product where user_id = %s"""
         cursor.execute(sql_query, (user_id, ))
         query = cursor.fetchall()
         for code, descr, price, entry_date, image_path in query:
             result.append(
                 Product(0, 0, code, entry_date, descr, float(price),
                         image_path))
     except mariadb.Error as error:
         self.__log(self.__default_sql_error, error)
     finally:
         self.__close_connection(cursor)
     return result
Beispiel #18
0
def update_products(
    vuln: "data.models.Vulnerability", products: List[Dict[str, str]] = None
) -> Optional[List["data.models.Product"]]:
    # avoid circular imports
    # pylint: disable=import-outside-toplevel
    from data.database import db
    from data.models import Product, Cpe

    # pylint: enable=import-outside-toplevel

    if products is None:
        products = request.form.get("products")

    if isinstance(products, str):
        try:
            products = json.loads(products)
        except (TypeError, json.JSONDecodeError) as ex:
            raise InvalidProducts("Invalid products") from ex

    if products is not None:
        if not isinstance(products, list) or any(
            (not isinstance(p, dict) or "product" not in p or "vendor" not in p)
            for p in products
        ):
            raise InvalidProducts("Invalid products")

        vuln.products = []  # type: ignore
        for product in products:
            if not db.session.query(
                Cpe.query.filter_by(
                    vendor=product["vendor"], product=product["product"]
                ).exists()
            ).scalar():
                raise InvalidProducts(
                    "Invalid product {vendor}/{product}".format(**product)
                )
            prod_obj = Product.query.filter_by(
                vendor=product["vendor"], product=product["product"]
            ).one_or_none()
            if not prod_obj:
                prod_obj = Product(vendor=product["vendor"], product=product["product"])
            vuln.products.append(prod_obj)
        return vuln.products
    return None
    def get_or_create_by_name(self,
                              name: str,
                              description: str = "from api",
                              target_stock: int = 1) -> ProductDalModel:
        """
        Ensures that there is a product with the specified name, if one cannot be found it is created

        :param name: The name to find
        :param description: The description of the product if created
        :param target_stock: The target stock level if created
        :return: The product with the name specified
        """
        product_model: Product
        try:
            product_model = Product.get(Product.name == name)
        except peewee.DoesNotExist:
            return self.create_product(name, description, target_stock)

        return ProductDalModel.create_from_model(product_model)
Beispiel #20
0
 def get(self):
   """HTML GET handler.
   
   Renders a form for inputing the information used to create a monster under
   a specific set of rules. The rules are specified by the MonsterBuilder 
   being used."""
   
   template_values = self.build_template_values()
   template_values['questions']= CoreMonsterBuilder.questions()
   
   product = self.request.get('product')
   if product:
     product = Product.get_by_id(int(product))
     if product.creator.account != template_values[handlers.base.USER_KEY]:
       return self.forbidden()
     template_values['product'] = product
   
   template = configuration.site.jinja_environment.get_template('monster/create.html')
   self.response.write(template.render(template_values))
Beispiel #21
0
 def get(self, access_code=None):
   """HTML GET handler.
   
   Check the query parameters for the access code and grant access to that
   product."""
   
   user = users.get_current_user()
   profile = Profile.for_user(user)
   if not profile:
     return self.forbidden()
   if not access_code:
     return self.forbidden()
     
   product = Product.get_by_access_code(access_code)
   if not product:
     return self.not_found()
     
   profile.products.append(product.key().id())
   profile.put()
   
   return self.redirect(self.uri_for('profile.edit'))
Beispiel #22
0
 def get(self, entity_id=None):
   """HTML GET handler.
   
   Update the product with the specified ID"""
   
   template_values = self.build_template_values()
   
   if entity_id:
     try:
       product = Product.get_by_id(int(entity_id))
     except ValueError:
       return self.not_found()
     if not product:
       self.not_found()
       return
     product.generate_access_code()
     product.put()
   else:
     self.redirect(self.uri_for('product.home'))
     return
   
   return self.redirect(self.uri_for('profile.edit'))
Beispiel #23
0
 def get(self, entity_id=None):
   """HTML GET handler.
   
   Display the product with the specified ID"""
   
   template_values = self.build_template_values()
   
   if entity_id:
     try:
       product = Product.get_by_id(int(entity_id))
     except ValueError:
       return self.not_found()
     if not product:
       self.not_found()
       return
     template_values['product'] = product
   else:
     self.redirect(self.uri_for('product.home'))
     return
   
   template = configuration.site.jinja_environment.get_template('product/view.html')
   self.response.write(template.render(template_values))
Beispiel #24
0
    def post(self):
        if self.request_body['type'] == 'history' and self.request_body[
            'action'] == 'add':
            try:
                for items in self.request_body['data']:
                    products = Product(**items)
                    self.sessions.add(products)
                    self.sessions.commit()
            except Exception as e:
                raise AppException(
                    ret_msg='failed, exception: %s' % e.__str__())
            self.jsonify(ret_msg=u"success")

        if self.request_body['type'] == 'history' and self.request_body[
            'action'] == 'query':
            result = []
            if self.request_body.has_key('sort'):
                sort = self.request_body['sort']
                if sort == 'f_id':
                    sorts = ConfigHistory.f_id
                elif sort == 'f_create_time':
                    sorts = ConfigHistory.f_create_time
                elif sort == 'f_name':
                    sorts = Product.f_name
                else:
                    sorts = ConfigHistory.f_id

                if self.request_body.has_key('order'):
                    order = self.request_body['order']
                    if order == 'desc':
                        sorts = desc(sorts)
                    else:
                        sorts = asc(sorts)

            if self.request_body.has_key('search'):
                search = self.request_body['search']


                total_record = self.sessions.query(ConfigHistory,
                                                   Product.f_name).join(
                    Product).filter(Product.f_name.like('%'+'%s' %(search) +'%')).order_by(sorts)
            else:
                total_record = self.sessions.query(ConfigHistory,
                                                   Product.f_name).join(
                    Product).order_by(sorts)

            total = total_record.count()
            for items in total_record.limit(
                    self.request_body['limit']).offset(
                self.request_body['offset']):
                result.append({'f_id': items[0].f_id,
                               'f_create_time': items[
                                   0].f_create_time.__str__(),
                               'f_name': items[1],
                               'f_config': items[0].f_config,
                               'f_description': items[0].f_description})
            self.jsonify(ret_msg=u"success", total=total, data=result)
        else:
            raise AppException(ret_msg=u'args error')

        if self.request_body['type'] == 'product':
            raise AppException(ret_msg=u'unsupported action')

        raise AppException(ret_msg=u'type error')