예제 #1
0
def order(product_id, id):
    id_user = current_user.id
    item = Items.query.get(id)
    product = Product.query.get(product_id)
    product.first_free()
    item = Items.query.get(product.free_items[item.size])

    item_pack = ItemPack.query.get(item.id_itemPack)
    item.id_user = id_user
    item_pack.change_status()

    if product.add_rows():
        item_pack2 = ItemPack()
        item_pack2.goal = item_pack.goal
        item_pack2.id_product = product_id
        item_pack2.sizes = item_pack.sizes
        item_pack2.status = 4
        db.session.add(item_pack2)
        db.session.commit()
        for size in item_pack.sizes:
            items = Items()
            items.id_itemPack = item_pack2.id
            items.size = size
            db.session.add(items)
    # сделать бронирование первого свободного размера

    db.session.commit()
    return redirect(url_for("product", id=product_id))
예제 #2
0
def change_product(id):
    product = Product.query.get(id)
    categories = Category.query.all()
    types = Type.query.all()
    sites = Site.query.all()
    sizes = ""
    arr_sizes = []
    main_item_pack = product.item_packs.filter(ItemPack.status > 2).order_by(
        ItemPack.status).first()
    if product.type_id == 1:
        for size in main_item_pack.sizes:
            sizes += size + "; "
            arr_sizes.append(size)

    if (not current_user.is_admin) and (current_user.id !=
                                        product.site.manager_id):
        return redirect(url_for("product", id=id))
    cp_form = ChangeProductForm()
    if request.method == "POST":

        if request.form['name'] != product.name and request.form['name'] != "":
            product.name = request.form['name']
        if request.form['price'] != product.price and request.form[
                'price'] != "":
            product.price = request.form['price']
        if request.form['description'] != product.description and request.form[
                'description'] != "":
            product.description = request.form['description']

        if request.form['url'] != product.url and request.form['url'] != "":
            product.url = request.form['url']
        if request.form['article'] != product.article and request.form[
                'article'] != "":
            product.article = request.form['article']
        if request.form['category'] != product.category_id:
            product.category_id = request.form['category']
        if request.form['site'] != product.site_id:
            product.site_id = request.form['site']
        if product.type_id == 1:
            if request.form['goal'] != main_item_pack.goal and request.form[
                    'goal'] != "":                main_item_pack.goal = \
request.form['goal']
            if request.form['sizes'] != sizes:
                string_sizes = re.findall(r'\b[-\w]+', request.form['sizes'])
                if len(string_sizes) == int(request.form['goal']):
                    for item_pack in product.item_packs.filter(
                            ItemPack.status > 2).order_by(
                                ItemPack.status).all():
                        item_pack.sizes = string_sizes
                        item_pack.items.delete()
                        for i in string_sizes:
                            items = Items()
                            items.id_itemPack = item_pack.id
                            items.size = i
                            db.session.add(items)
                        item_pack.change_status()
                    product.delete_excess()
        elif request.form['goal'] != main_item_pack.goal and request.form[
                'goal'] != "":
            main_item_pack.goal = request.form['goal']
            for item_pack in product.item_packs.filter(
                    ItemPack.status > 2).order_by(ItemPack.status).all():
                item_pack.items.delete()
                for i in main_item_pack.goal:
                    items = Items()
                    items.id_itemPack = item_pack.id
                    db.session.add(items)
                item_pack.change_status()
        db.session.commit()
        product.delete_excess()
        # работа с картинками

        # file = request.files['main_img']
        # now = str(int(time.time()))
        # if file and allowed_file(file.filename): #add main image
        #     file.filename = translit(product_name, reversed=True)+ '_'+now
        #     main_img = app.config['UPLOAD_FOLDER'] + secure_filename(file.filename)
        #     file.save('app' + main_img)
        # inputs = ['second_image_1','second_image_2','second_image_3','second_image_4']
        # secondary_img = []
        # for inp in inputs: #add secondary_images
        #     s_file = request.files.get(inp, None)
        #     if s_file != None:
        #         img = request.files[inp]
        #         if img and allowed_file(img.filename):
        #             img.filename = file.filename + '_'+str(inputs.index(inp))
        #             s_path = app.config['UPLOAD_FOLDER'] + secure_filename(img.filename)
        #             s_file.save('app' + s_path)
        #             secondary_img.append(s_path)

        # db.session.add(product)
        # db.session.commit()
        # item_pack.id_product = product.id
        # db.session.add(item_pack)
        # db.session.commit()
        # if product.type_id == 2:
        #     for i in range(item_pack.goal):
        #         items = Items()
        #         items.id_itemPack = item_pack.id
        #         db.session.add(items)
        # db.session.commit()
        return redirect(url_for("product", id=product.id))
    return render_template("change_product.html",
                           title="Изменить товар",
                           cp_form=cp_form,
                           categories=categories,
                           types=types,
                           sites=sites,
                           product=product,
                           sizes=sizes)
예제 #3
0
def add_product():
    if not current_user.is_manage or not current_user.is_admin:
        return redirect(url_for('index'))
    add_form = AddProductForm()
    categories = Category.query.all()
    if current_user.is_admin:
        sites = Site.query.all()
    else:
        sites = Site.query.filter_by(manager_id=current_user.id)
    types = Type.query.all()

    if request.method == "POST":
        product_name = request.form['name']
        price = request.form['price']
        description = request.form['description']
        goal = request.form['goal']
        url = request.form['url']
        type = request.form['type']
        category = request.form['category']
        article = request.form['article']
        site = request.form['site']
        file = request.files['main_img']
        now = str(int(time.time()))
        if file and allowed_file(file.filename):  #add main image
            file.filename = translit(product_name, reversed=True) + '_' + now
            main_img = app.config['UPLOAD_FOLDER'] + secure_filename(
                file.filename)
            file.save('app' + main_img)
        inputs = [
            'second_image_1', 'second_image_2', 'second_image_3',
            'second_image_4'
        ]
        secondary_img = []
        for inp in inputs:  #add secondary_images
            s_file = request.files.get(inp, None)
            if s_file != None:
                img = request.files[inp]
                if img and allowed_file(img.filename):
                    img.filename = file.filename + '_' + str(inputs.index(inp))
                    s_path = app.config['UPLOAD_FOLDER'] + secure_filename(
                        img.filename)
                    s_file.save('app' + s_path)
                    secondary_img.append(s_path)

        product = Product()
        item_pack = ItemPack()
        product.name = product_name
        product.url = url
        item_pack.goal = goal
        product.description = description
        product.price = price
        product.date_add = now
        product.category_id = category
        product.type_id = type
        product.site_id = site
        product.main_image = main_img
        product.article = article
        product.second_image = secondary_img
        db.session.add(product)
        db.session.commit()
        item_pack.id_product = product.id
        item_pack.status = 4
        db.session.add(item_pack)
        db.session.commit()
        if product.type_id == 1:
            sizes = re.findall(r'\b[-\w]+', request.form['sizes'])
            item_pack.sizes = sizes
            for i in sizes:
                items = Items()
                items.id_itemPack = item_pack.id
                items.size = i
                db.session.add(items)
        else:
            for i in range(item_pack.goal):
                items = Items()
                items.id_itemPack = item_pack.id
                db.session.add(items)
        db.session.commit()
        return redirect(url_for("product", id=product.id))

        # if type == 1:
        #     pass
        # elif type == 2:
        #     for i in goal:
        #         item = Items()
        #         item.id_product = product.id
        #         db.session.add(item)
        #     db.session.commit()
        # return render_template("post.html",title = product.name, product_items=product.items, product=product, login_form=True,categories=categories)
    return render_template("add_product.html",
                           title="Добавить товар",
                           categories=categories,
                           types=types,
                           sites=sites,
                           add_form=add_form)
예제 #4
0
def order_min(product_id):
    id_user = current_user.id
    order_form = OrderForm()
    item_pack = ItemPack.query.filter(ItemPack.id_product == product_id,
                                      ItemPack.status > 2).order_by(
                                          ItemPack.status,
                                          ItemPack.id).first_or_404()

    item_pack.get_busy_items()
    count = int(request.form['count_order'])

    if count >= item_pack.goal - item_pack.count_busy:  #если заказанное количество больше либо равно чем количество свободных итемов
        add_itempacks = (
            count - (item_pack.goal - item_pack.count_busy)
        ) // item_pack.goal + 1  # вычисляем сколько итемпаков должно быть добавлено
    else:
        add_itempacks = 0  #иначе - переменная равна нулю

    if request.method == 'POST':
        if add_itempacks != 0:  #если необходимо добавить итемпаки
            #
            while add_itempacks > 0 or count > 0:  # цикл идет пока надо добавить итемпаки или поставить юзера
                item_pack_j = ItemPack.query.filter(
                    ItemPack.id_product == product_id
                    and ItemPack.status > 2).order_by(
                        ItemPack.status).first_or_404(
                        )  #выборка итемпака доступного для изменения
                if item_pack_j.get_free_items() and count > 0:
                    #если в итепаке есть свободные итемы и все еще необходимо поставить итемы
                    for item in item_pack_j.items.filter_by(
                            id_user=None).order_by(
                                Items.id):  # в цикле ставим юзера на итем
                        if count > 0:
                            item.id_user = current_user.id
                            count -= 1  #минусуем количество которое надо поставить
                        else:
                            break
                #
                else:  #если в итемпаке нет свободных итемов
                    item_pack_j.status = 2  # меняем статус предыдущего итемпака
                    item_pack2 = ItemPack()  #создаем новый итемпак
                    item_pack2.goal = item_pack_j.goal  #даем ему параметры предыдущего итемпака
                    item_pack2.id_product = product_id
                    item_pack2.sizes = item_pack_j.sizes
                    item_pack2.status = 4
                    db.session.add(
                        item_pack2)  # добавляем в сессию информацию о итемпаке
                    db.session.commit()
                    for item in range(item_pack2.goal
                                      ):  #через цикл добавляем новые итемы
                        items = Items()  #создаем новый итемпак
                        items.id_itemPack = item_pack2.id  #даем параметры
                        if count > 0:  #если еще надо поставить юзера на размер
                            items.id_user = current_user.id  #ставим
                            count -= 1  #минусуем параметp

                        db.session.add(items)  #добавляем в сессию изменения

                    add_itempacks -= 1  #минусуем количество добавления итемпаков
                db.session.commit()  #коммитим изменения

        else:  #если не надо добавлять итемпаки
            while count:  #пока надо поставить на размер
                item = item_pack.items.filter_by(id_user=None).order_by(
                    Items.id).first()  #запрос на итемы
                item.id_user = id_user  #ставим юзера
                count -= 1  #минусуем параметр
            item_pack.change_status()  #меняем статус итемпака если надо
        db.session.commit()  #
    return redirect(url_for("product", id=product_id))