def setUpClass(self):
        """
        Method to setup global values needed for all tests

        """
        self.guitar = Product('Electric Guitar', 3.50,
                              'Fun way to make music.')
        self.shampoo = Product("Coconut Oil Shampoo", 7.99,
                               "silky smoothe hair treatment shampoo")
Beispiel #2
0
def add_product_1_0():
    if not request.json or 'barcode' not in request.json\
       or 'units' not in request.json or 'price' not in request.json\
       or 'name' not in request.json:
        abort(400)
    if not request.json['barcode'] or not request.json['name']\
       or not request.json['units'] or not request.json['price']:
        abort(400)
    if (logger.log_op(request.json)):
        m = MasterList.query.filter_by(barcode=request.json['barcode']).first()
        if m is not None:
            abort(409, {"message": "Producto existente"})
        m = ProductsMasterlist(request.json['barcode'], request.json['name'],
                               request.json['price'])
        db_session.add(m)
        db_session.commit()
        p = Product(request.json['barcode'], request.json['units'], 1)
        db_session.add(p)
        db_session.commit()
        prod = ProductStore.query.filter_by(
            barcode=request.json['barcode']).filter_by(storeid=1).first()
        return make_response(jsonify({"mobilerp": prod.serialize}), 200)
    else:
        return make_response(
            jsonify({'mobilerp': 'Operacion duplicada, saltando'}), 428)
def edit(id):
    title = 'Editar Produto'
    product = Product()
    ret = product.get(id)
    if not product.id:
        flash(ret, 'info')
        return redirect(url_for('product.index'))
    
    image = b64encode(product.imagem).decode("utf-8")
    if request.form:
        form = ProductForm()
        product.descricao = form.descricao.data
        product.valor = form.valor.data
        if form.imagem_edicao.data.filename != '':
            image_edit = request.files.get('imagem_edicao')
            product.imagem = image_edit.read()
        else:
            image_edit = product.imagem
    else:
        form = ProductForm()
        form.descricao.data = product.descricao
        form.valor.data = product.valor

    form.imagem.validators = []
    if form.validate_on_submit():
        ret = product.update()
        flash(ret, 'info')
        return redirect(url_for('product.edit', id=product.id))
    return render_template('product_form.html', form=form, title=title, mode='edit', image=image, productId=product.id), 200
    def applyDiscountOnProduct(self, productBody):

        foundProduct = self.productDiscountRepository.checkIfProductIsInDatabase(productBody['Id'])
        if foundProduct:
            return self.productDiscountRepository.updateProductDiscount(productBody['Id'], productBody)

        type = productBody['Type']

        ValidFrom = datetime.now()
        ValidTo = datetime.now()

        # Generating the percentage based on the how much was the product sold
        if type == 'mostBought':
            discountPercentage = 10
            ValidTo = ValidFrom + timedelta(days=30)
        elif type == 'leastBought':
            discountPercentage = 20
            ValidTo = ValidFrom + timedelta(days=30)
        else:
            return {'error': 'Type of product discount can only be mostBought or leastBought. {} is illegal type.'.format(type)}, 400

        timesBought = 0
        newProduct = Product(Id=productBody['Id'],
                                TimesBought=timesBought,
                                ValidFrom=ValidFrom,
                                ValidTo=ValidTo,
                                Type=type,
                                DiscountPercentage=discountPercentage)

        return self.productDiscountRepository.applyDiscountOnProduct(newProduct=newProduct)
Beispiel #5
0
def get_products(db, paras):
    listObj = {
        "items": [],
        "total": 0,
    }
    type = paras["type"]

    cond = "WHERE 1=1 "
    if type:
        cond += "AND P_Type='%s' " % type

    state = paras["state"]
    if state:
        cond += "AND P_State='%s' " % state

    cond += "ORDER BY P_CreateTime "

    ret = db.select(TB_PRODUCT, cond=cond)
    if ret == -1:
        ERROR("get user list error")
        return (DB_ERR, None)

    for dur in db.cur:
        obj = dbmysql.row_to_dict(TB_PRODUCT, dur)
        product = Product(db, dbObj=obj)
        product.loadFromObj()

        listObj["items"].append(product.toObj())

    listObj["items"].sort(key=lambda x: x["infoObj"]["id"])

    listObj["total"] = len(listObj["items"])

    return (OCT_SUCCESS, listObj)
Beispiel #6
0
def add_product(db, paras):
    product = Product(db, name=paras["name"])
    product.type = paras["type"]
    product.desc = paras["desc"]

    infoObj = {
        "id": paras["code"],
        "type": paras["type"],
        "name": paras["name"],
        "provider": paras["provider"],
        "price": paras["price"],
        "costPrice": paras["costPrice"],
        "desc": paras["desc"],
        "model": paras["model"],
        "code": paras["code"]
    }

    if paras["frequency"]:
        infoObj["frequency"] = paras["frequency"]

    if paras["cores"]:
        infoObj["cores"] = paras["cores"]

    if paras["threads"]:
        infoObj["threads"] = paras["threads"]

    if paras["capacity"]:
        infoObj["capacity"] = paras["capacity"]

    product.infoObj = infoObj

    ret = product.add()

    return ret, None
Beispiel #7
0
 def process(self, request, session):
     _id = request.values.get('id')
     productObj = Product()
     prodDetail = productObj.find({'_id': ObjectId(_id)})
     if (prodDetail.count() != 1):
         return abort(404)
     log, u = checkLogin(session)
     return render_template('product.html', m=prodDetail[0], log=log, u=u)
Beispiel #8
0
def updateHelper(barcode, units, storeid):
    p = Product.query.filter_by(storeid=storeid, barcode=barcode).first()
    if p is None:
        p = Product(barcode, 0, storeid)
    u = p.units + units
    db_session.add(p)
    db_session.commit()
    return "UPDATE product set units={0} where barcode='{1}' and storeid={2}"\
        .format(u, barcode, storeid)
def search_prod(prod):
    product = Product()
    products = product.filterByName(prod)
    ret_prods = []
    if products:
        for p in products:
            img = str(b64encode(p[3]).decode("utf-8"))
            ret_prods.append({"id": p[0], "descricao": p[1], "valor": str(p[2]), "imagem": img})
    return jsonify(ret_prods)
Beispiel #10
0
 def post(self):
     self.name = request.json['name']
     self.description = request.json['description']
     self.price = request.json['price']
     self.qty = request.json['qty']
     self.new_product = Product(self.name, self.description, self.price,
                                self.qty)
     db.session.add(self.new_product)
     db.session.commit()
     return product_schema.jsonify(self.new_product)
Beispiel #11
0
 def post(self):
     args = parser.parse_args()
     product = Product(name=args['name'],
                       description=args['description'],
                       preco=args['preco'],
                       store_id=args['store_id'],
                       label=args['label'])
     db.add(product)
     db.commit()
     return product.serialize(), 201
Beispiel #12
0
 def process(self, request, session):
     query = request.values.get('query')
     productObj = Product()
     prodList = productObj.findAll(query)
     log, u = checkLogin(session)
     return render_template('search.html',
                            query=query,
                            m=prodList,
                            log=log,
                            u=u)
Beispiel #13
0
 def products(self, submit):
     product = Product()
     products = product.get_all_products(with_quantity=True)
     res = ''
     for elem in products:
         # res = res.join(f"<li>{i}</li>" for i in elem)+"<br>"
         res = res + "<li> ID: " + str(elem[0]) + "</li>"
         res = res + "<li> Product name: " + str(elem[1]) + "</li>"
         res = res + "<li> Price: " + str(elem[2]) + "</li>"
         res = res + "<li> Article: " + str(elem[3]) + "</li>"
         res = res + "<li> Quantity: " + str(elem[4]) + "</li> <br>"
     return f"""
Beispiel #14
0
def newProduct():
    if not request.json or 'barcode' not in request.json\
       or 'units' not in request.json or 'price' not in request.json\
       or 'name' not in request.json:
        abort(400)
    if request.json['barcode'] is '' or request.json['name'] is ''\
       or request.json['units'] is '' or request.json['price'] is '':
        abort(401)
    p = Product(request.json['barcode'], request.json['name'],
                request.json['units'], request.json['price'])
    db_session.add(p)
    db_session.commit()
    return make_response(jsonify({'mobilerp': [p.serialize]}), 200)
Beispiel #15
0
def index():
    product = Product()
    desc = request.args.get('descricao', '')

    if desc:
        products = product.getByDesc(desc)
    else:
        products = product.getAll()

    images = []
    for product in products:
        images.append(b64encode(product[3]).decode("utf-8"))
    return render_template('product.html', products=products, images=images, desc=desc), 200
Beispiel #16
0
async def createProduct(request):
    try:
        body = await request.json()
    except Exception as e:
        raise ClientException('Invalid body')

    # every field may be null
    productToCreate = Product(name=body.get("name", None),
                              description=body.get("description", None),
                              properties=body.get("properties", None))

    await productToCreate.commit()
    return web.json_response({'id': str(productToCreate.id)})
Beispiel #17
0
def create():

    schema = ProductSchema()

    try:
        data = schema.load(request.get_json())
        product = Product(**data)
        db.commit()
    except ValidationError as err:
        #if the Validation fails, send back 422 response
        return jsonify({
            'message': 'Validation failed',
            'errors': err.messages
        }), 422
    return schema.dumps(product), 201
Beispiel #18
0
def add():
    form = ProductForm()
    title = 'Cadastrar Produto'
    if form.validate_on_submit():
        image = request.files.get('imagem')
        if image:
            product = Product(
                form.descricao.data,
                form.valor.data,
                image.read()
            )
            ret = product.insert()
            flash(ret, 'info')
            return redirect(url_for('product.index'))
    return render_template('product_form.html', form=form, title=title, mode='add'), 200
Beispiel #19
0
def buy_fund():
    jongmok = input('종목명?')
    yongdo = input('용도?')

    while True:
        price = input('가격?')
        if price.isdigit():
            break

    while True:
        yang = input('개수는?')
        if yang.isdigit():
            break
    dec = input('기타 추가 설명을 입력해주세요.')
    obj = Product(jongmok, yongdo, yang, dec, price)
    obj.print_obj()
    bot.send_msg(obj.make_str())
Beispiel #20
0
def delete(id):
    product = Product()
    ret = product.get(id)
    if not product.id:
        flash(ret, 'info')
        return redirect(url_for('product.index'))

    order = OrderProduct()
    has = order.hasByProduct(id)
    if has:
        flash('O produto não pode ser deletado pois ele já está relacionado à algum pedido.', 'info')
        return redirect(url_for('product.index'))

    if request.method == 'POST':
        ret = product.delete()
        flash(ret, 'info')
        return redirect(url_for('product.index'))
    title = 'Deseja realmente deletar o produto ' + str(product.id) + '?'
    return render_template('product_delete.html', productId=id, title=title), 200
    def test_can_get_all_saved_product(self):
        """
        Method to test if all saved product can be retrieved with the attibutes of id, price, name

        """
        prodData = ProductData()
        prodData.save_product(self.guitar)
        data = prodData.get_all_products()

        data_index_1 = len(data)
        self.Electric = Product('Electric Guitar', 5.50,
                                'Fun way to make music.')
        prodData.save_product(self.Electric)
        data = prodData.get_all_products()

        data_index_2 = len(data)

        self.assertEqual(data_index_2, data_index_1 + 1)
        self.assertIn((data_index_2, 5.50, 'Electric Guitar'), data)
def product_create(user, storeId):
    product_fields = product_schema.load(request.json)
    product = Product.query.filter_by(title=product_fields["title"]).first()
    if product:
        return abort(400, description="Title already in use")

    new_product = Product()
    new_product.title = product_fields["title"]
    new_product.price = product_fields["price"]
    new_product.store_id = storeId

    store = Store.query.filter_by(id=storeId, user_id=user.id).first()
    if not store:
        return abort(400, description="Incorrect storeID in URL")

    store.product.append(new_product)
    db.session.commit()

    return jsonify(product_schema.dump(new_product))
Beispiel #23
0
def getCategorySpecificRecords(node, name, recordCount):
    numCalls = int(math.ceil(float(recordCount)/pageSize))
    products = []

    #iterate through all pages and append the product data for specific category
    for currentPage in range(1,numCalls+1):
        curr_url ='https://www.sephora.com/api/catalog/search?country_switch=ca&type=keyword&q=sale&icid2=meganav_sale_top_nav_link%3fpageSize=-1&currentPage=' + str(currentPage) + '&content=true&includeRegionsMap=true&page=60&currentPage=' + str(currentPage)
        s_url = curr_url + "&node=" + str(node)
        req = Request(url=s_url, headers=headers) 
        res = urlopen(req).read().decode()
        productData = json.loads(res)

        for x in productData["products"]:
            salePriceExists = x["currentSku"]
            if "salePrice" in salePriceExists:
                p = Product(x["brandName"],x["productName"], x["heroImage"], x["productId"], x["rating"], 
                x["currentSku"]["listPrice"], x["currentSku"]["salePrice"], x["currentSku"]["isLimitedEdition"], x["currentSku"]["isLimitedTimeOffer"])
                products.append(p)
    return products
    async def getProducts(
        self, productFilter: 'ProductRepository.Filter', currency: str = 'USD' # yes, it is just hardcoded
    ) -> List[Product]:
        multiplier = await self.getCurrencyMultiplier(currency)
        if multiplier is None: raise Exception(f'No multiplier for currecncy {currency}')
        productFilter.applyMultiplier(multiplier)

        sql = Query.from_(products) \
            .select(
                products.id, products.name, products.picture,
                (products.price_dollar * multiplier).as_('price')
            ).where(productFilter.getCriterion()) \
                .limit(productFilter.limit).offset(productFilter.offset)

        result = await databaseClient.query(sql.get_sql())
        return [
            Product(
                id = row[0], name = row[1], picture = row[2],
                price = row[3].normalize()
            ) for row in result
        ]
Beispiel #25
0
 def post(self):
     # 新增商品
     try:
         # 获取前端传来的参数
         data = json.loads(self.get_argument('data'))
         if data['IsHot'] == '1':
             data['IsHot'] = True
         else:
             data['IsHot'] = False
         if data['IsNew'] == '1':
             data['IsNew'] = True
         else:
             data['IsNew'] = False
         pro = Product(**data)
         session.add(pro)
         session.commit()
         self.write_json(pro.ProductID, code=1)
     except Exception, e:
         # 事务
         print e
         session.rollback()
         self.write_json("failed", code=0)
 def postInformationFor5MostBoughtProducts(self, productIds):
     for pId in productIds:
         foundProduct = self.checkIfProductIsInDatabase(pId)
         if foundProduct:
             foundProduct.Type = "mostBought"
             foundProduct.ValidFrom = datetime.now()
             foundProduct.ValidTo = datetime.now() + timedelta(days=30)
             foundProduct.TimesBought = 0
             foundProduct.DiscountPercentage = 10
             db.session.commit()
         else:
             newProduct = Product()
             newProduct.Id = pId
             newProduct.TimesBought = 0
             newProduct.ValidFrom = datetime.now()
             newProduct.ValidTo = datetime.now() + timedelta(days=30)
             newProduct.Type = "mostBought"
             newProduct.DiscountPercentage = 10
             db.session.add(newProduct)
             db.session.commit()
     return {
         'success':
         'The products with the given ids were successfully added to the database'
     }, 200
Beispiel #27
0
from models.User import User
from models.Request import Request
from models.Product import Product


class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2', )


users = [
    User(0, 'Rafael Cruz', 'rafael', '123', 100.00),
    User(1, 'Bruno', 'bruno', '456', 50.00),
    User(2, 'Atendente 01', 'atendente', '111', 0)
]

menu = [Product(0, 'Pão', 10), Product(1, 'Vinho', 20)]

requests = []

# Create server
with SimpleXMLRPCServer(('localhost', 8000),
                        requestHandler=RequestHandler) as server:
    server.register_introspection_functions()

    def login(username, password):
        for user in users:
            if username == user.username and password == user.password:
                if str(username) == str('atendente'):
                    return {'requests': requests, 'user': user}
                else:
                    return {'menu': menu, 'user': user}
Beispiel #28
0
from pony.orm import db_session
from app import db
from models.Farm import Farm, Comment
from models.Product import Product
from models.User import User, UserSchema

db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():
    schema = UserSchema()
    dragan = User(username='******',
                  email='*****@*****.**',
                  password_hash=schema.generate_hash('pass'))
    fruit = Product(name='Fruit')
    vine = Product(name='Vine')
    honey = Product(name='Honey')
    meat = Product(name='Meat')
    fish = Product(name='Fish')
    dairy = Product(name='Dairy')
    vegetables = Product(name='Vegetables')
    eggs = Product(name='Eggs')
    destilery = Product(name='Destilery')
    brewery = Product(name='Brewery')

    my_farm = Farm(
        name='Happy Farm',
        country='UK',
        region='Kent',
        address='Maidstone Rd, Paddock Wood, Tonbridge TN12 6PY',
        products=[brewery, fish],
Beispiel #29
0
#! python3
"""
    Main file to run package code. Import all the table models you desire to use in this file.
    ex: from models.Product import Product
        product = Product()
"""

from models.Brand import Brand
from models.Product import Product

products = Product()

print(products.all())
Beispiel #30
0
def seed_db():
    from models.User import User
    from models.Store import Store
    from models.Product import Product
    from models.Customer import Customer
    from models.Order import Order
    from main import bcrypt
    from faker import Faker

    faker = Faker()
    users = []
    stores = []
    products = []
    customers = []

    for i in range(5):
        user = User()
        user.email = f"test{i+1}@test.com"
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        user.isAdmin = False
        db.session.add(user)
        users.append(user)

        db.session.commit()

        store = Store()
        store.storename = faker.bs()
        store.firstname = faker.first_name()
        store.lastname = faker.last_name()
        store.user_id = users[i].id
        db.session.add(store)
        stores.append(store)

        db.session.commit()

        for j in range(5):
            product = Product()
            product.title = faker.numerify(text="Duck ###")
            product.price = faker.random_int(min=5, max=200, step=5)
            product.store_id = stores[i].id
            db.session.add(product)
            products.append(product)

        db.session.commit()

        for j in range(5):
            customer = Customer()
            customer.firstname = faker.first_name()
            customer.lastname = faker.last_name()
            customer.email = faker.ascii_email()
            customer.phone = faker.phone_number()
            customer.store_id = stores[i].id
            db.session.add(customer)
            customers.append(customer)

            db.session.commit()

            for k in range(5):
                order = Order()
                order.order_placed = choice([True, False])
                order.customer_id = choice(customers).id
                db.session.add(order)

                db.session.commit()

                for m in range(3):
                    order.orders_products.append(choice(products))

                    db.session.commit()

        customers = []

    db.session.commit()

    print("Tables seeded")