Esempio n. 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))
Esempio n. 2
0
def items(request):
    if request.method == "POST":
        form = Profileform(request.POST, request.FILES)
        if form.is_valid():
            item = Items(
                author=request.POST['author'],
                profile_pic=request.FILES['profile_pic'],
                item_name=request.POST['item_name'],
                servings=request.POST['servings'],
                preparation_time=request.POST['preparation_time'],
                cooking_time=request.POST['cooking_time'],
                food_image=request.FILES['food_image'],
                ingredients=request.POST['ingredients'],
                direction=request.POST['direction'],
                item_type=request.POST['item_type'],
            )
            current_user = request.user.id
            item.save()
            name = item.id
            add_author(request, current_user, name)
        else:
            pass
        return redirect('/items/')
    else:
        form = Profileform()
        current_user = request.user.id
        items = Items_List.objects.all().select_related('item_list').filter(
            user_name_id=current_user).order_by('item_list__item_name')
        lists = Items_List.objects.select_related('item_list')
        return render(request, 'author_items.html', {
            'items': items,
            'form': form
        })
Esempio n. 3
0
def add_item_to_shopping_list(id):
    # get the access token from header
    access_token = request.headers.get('Authorization')
    if access_token:
        # attempt to decode the token and get the User ID
        user_id = Users.decode_token(access_token)
        if not isinstance(user_id, str):
            # check if shopping list exists in the database
            shopping_list = ShoppingLists.query.filter_by(user_id=user_id,
                                                          id=id).first()
            if not shopping_list:
                return make_response(
                    jsonify({
                        "message":
                        "Shopping list can not be found to add items"
                    })), 404
            data = request.get_json()
            item = Items(name=data['name'],
                         quantity=data['quantity'],
                         shopping_list_id=id,
                         bought_from=data['bought_from'],
                         status=data['status'])
            item.save()
            return make_response(
                jsonify({"message": "Item added to shopping list"})), 201
        else:
            # user is not legit, so the payload is an error message
            message = user_id
            response = {'message': message}
            return make_response(jsonify(response)), 401
    return make_response(jsonify({'message':
                                  'Please register or login.'})), 401
Esempio n. 4
0
def processAdd(request):
    if request.method == 'POST':
        if request.user.is_authenticated and request.user.is_superuser:
            adder = Items(titulo=request.POST['titulo'],
                          short=request.POST['short'],
                          descricao=request.POST['descricao'],
                          preco=request.POST['preco'],
                          picture=request.FILES['picture'],
                          quantidade=request.POST['quantidade'])
            adder.save()
            return redirect('adminpanel')
        else:
            return redirect('home')
    else:
        return redirect('home')
 def post(self):
     item = request.get_json()["item"]
     price = request.get_json()["price"]
     exist = Items.query.filter_by(item=item).one_or_none()
     if exist:
         return {"message": "Item already exists"}, 403
     try:
         new_item = Items(item=item, price=price)
         new_item.insert()
     except:
         db.session.rollback()
         return {"message": "An error occured"}, 404
     finally:
         db.session.close()
     return {"message": "Item created"}, 201
Esempio n. 6
0
def itemUpdate(id):
    data = request.get_json()
    print(data)
    for key, value in data.items():
        field = remove_tags(value)

    # Update to items inventory Database
    item = db.session.query(Items).get(id)
    if item is not None:
        item.name = data['name']
        item.description = data['description']
        item.duration = data['duration']
        item.inventory = data['inventory']
        item.price = data['price']
        item.imgUrl = data['imgUrl']
        db.session.commit()
        return 'id #' + str(id) + ' has been updated'
    else:
        new_entry = Items(name=data['name'],
                          description=data['description'],
                          inventory=data['inventory'],
                          duration=data['duration'],
                          price=data['price'],
                          imgUrl=data['imgUrl'])

        db.session.add(new_entry)
        db.session.commit()
        return 'Added ' + str(data['name']) + ' to items list'

    return "id not found"
def additemNext():
    if not session.get('rmail'):
        return redirect(request.url_root)
    if request.method == "GET":
        # iid = request.args.get("iid")
        iname = request.args.get("iname")
        iprice = request.args.get("iprice")
        # rid = request.args.get("rid")

    elif request.method == "POST":
        # iid = request.form['iid']
        iname = request.form['iname']
        iprice = request.form['iprice']
        # rid = request.form['rid']

    rmail = session['rmail']
    restad = Restadmin.query.filter(Restadmin.rmail == rmail).first()
    restid = restad.rid

    items = Items(iname=request.form["iname"],
                  iprice=request.form["iprice"],
                  rid=restid)
    db.session.add(items)
    db.session.commit()

    return redirect(url_for('showmyrestmenu'))
Esempio n. 8
0
def fillDB():
    db.create_all()
    # create admin user
    admin = User(firstname='admin',
                 lastname='',
                 studentid='123456',
                 email='admin')
    admin.set_password('1234')
    try:
        db.session.add(admin)
        db.session.commit()
    except Exception as e:
        return "FAILED entry: " + str(e)
    #create items
    objects = [{
        'name': 'iPad',
        'description': 'iPad Pro 1000',
        'inventory': 10,
        'duration': 4,
        'price': 19.99,
        'imgUrl': 'ipad.png'
    }, {
        'name': 'Laptop',
        'description': 'Top of the line mac book air',
        'inventory': 10,
        'duration': 4,
        'price': 29.99,
        'imgUrl': 'laptop.png'
    }, {
        'name': 'Calculator',
        'description': 'Ti 84-Plus',
        'inventory': 10,
        'duration': 2,
        'price': 9.99,
        'imgUrl': 'calculator.png'
    }, {
        'name': 'Surface Pro 6',
        'description': 'Newest modest of 2018',
        'inventory': 10,
        'duration': 4,
        'price': 29.99,
        'imgUrl': 'sp6.png'
    }]
    try:
        items_entries = []
        for item in objects:
            new_entry = Items(name=item['name'],
                              description=item['description'],
                              inventory=item['inventory'],
                              duration=item['duration'],
                              price=item['price'],
                              imgUrl=item['imgUrl'])
            items_entries.append(new_entry)

        db.session.add_all(items_entries)
        db.session.commit()
    except Exception as e:
        return "FAILED entry: " + str(e)
Esempio n. 9
0
def createsome():

    #user1 = User(username='******')
    #db.session.add(user1)
    #db.session.commit()

    #FOOD = ['Canned Vegtables', 'Canned Meat', 'Fresh Vegtables', 'Fresh Meat', 'Dried Beans']

    i1 = Items(Needed_item='Canned Vegtables', country='Canada')
    i2 = Items(Needed_item='Canned Vegtables', country='Canada')
    i3 = Items(Needed_item='Fresh Vegtables', country='Canada')
    i4 = Items(Needed_item='Bread', country='Canada')
    i5 = Items(Needed_item='Eggs', country='Canada')
    i6 = Items(Needed_item='Milk', country='Canada')
    i7 = Items(Needed_item='Butter', country='Canada')

    db.session.add(i1)
    db.session.add(i2)
    db.session.add(i3)
    db.session.add(i4)
    db.session.add(i5)
    db.session.add(i6)
    db.session.add(i7)
    db.session.commit()

    return 'created :'
Esempio n. 10
0
def addprofile(request):
    if request.method == 'POST':
        item = Items(
            author=request.POST['author'],
            profile_pic=request.FILES['profile_pic'],
            item_name=request.POST['item_name'],
            servings=request.POST['servings'],
            preparation_time=request.POST['preparation_time'],
            cooking_time=request.POST['cooking_time'],
            food_image=request.FILES['food_image'],
            ingredients=request.POST['ingredients'],
            direction=request.POST['direction'],
            item_type=request.POST['item_type'],
        )
        current_user = request.user.id
        item.save()
        return redirect('/items/')
    else:
        return redirect('/items/')
Esempio n. 11
0
def items_add():
  
    form = AddItemsForm()
    if request.method == 'POST':
        newitem = Items(request.form['Category'], request.form['Vendor'], request.form['Model'], request.form['Price'])
        db.session.add(newitem)
        db.session.commit()
        return render_template('items_add.html', form=form, user_message="Add")
    else:
        return render_template('items_add.html', form=form, user_message="")
Esempio n. 12
0
def search():
    form = SearchForm()
    items = [Items()]
    items[0].name = 'search'
    if form.validate_on_submit():
        print(form.search.data)
        items = Items.query.filter((form.search.data == Items.name) | (form.search.data == Items.description)).all()
        if not items:
            items = None
    return render_template('search.html', form=form, items=items)
Esempio n. 13
0
def items_restored():
    # Establish the root path on the operating system
    basedir = os.path.abspath(os.path.dirname(__file__))
    # Change the working directory to the backup directory
    os.chdir(basedir + "/app/admin/Items_Backup")
    source_file = 'items_database_categories.py'
    categories_list = []
    # Open the original file default is read only
    with open(source_file) as f:
        # iterate over the lines of the original file
        for line in f:
            split_line = line.split(']')
            split2_line = split_line[0].split('[')
            categories_ids = split2_line[1].split(',')
            categories_list = categories_list + categories_ids
    f.close()
    for category in categories_list:
        # Get the category that the items are being recovered.
        category_obj = app.database.session.query(Categories).filter_by(
            id=category).first()
        # Establish the root path on the operating system
        basedir = os.path.abspath(os.path.dirname(__file__))
        # Change the working directory to the backup directory
        os.chdir(basedir + "/app/admin/Items_Backup")
        # Open the file that is being used in the recovery
        with open('items_database_export_%s.py' % category_obj.name) as f:
            # iterate ove the lines of the file
            for lines in f:
                if lines.startswith('{'):
                    # ast evaluates the string as an object.
                    item = ast.literal_eval(lines)
                    # create an Items object with the details from the line.
                    new_item = Items(asin=item['asin'],
                                     name=item['name'],
                                     category_id=item['category_id'],
                                     description=item['description'],
                                     created_by='Category')
                    # add the new item
                    app.database.session.add(new_item)
                    app.database.session.commit()
                    # add on the other elements of the item that is not passed in the initiation of the object
                    new_item.small_image = item['small_image']
                    new_item.medium_image = item['medium_image']
                    new_item.large_image = item['large_image']
                    new_item.brand = item['brand']
                    new_item.list_price = item['list_price']
                    new_item.offers = item['offers']
                    app.database.session.add(new_item)
                    app.database.session.commit()

    print 'Items have be recovered'
    return
Esempio n. 14
0
def addNewBucketlist(name, user_id, items=[]):
    day = time.time()
    date_created = str(
        datetime.datetime.fromtimestamp(day).strftime("%y-%m-%d"))
    date_modified = date_created
    bucketlist = Bucketlists(name=name)
    bucketlist.name = name
    bucketlist.date_modified = date_modified
    bucketlist.date_created = date_created
    bucketlist.created_by = user_id
    db.session.add(bucketlist)
    db.session.commit()
    if items is None:
        items = []
    if len(items) > 0:
        for each in items:
            item = Items(name=name, bucketlist=bucketlist)
            item.name = each['name']
            item.date_created = date_created
            item.date_modified = date_modified
            item.done = each['done']
            db.session.add(item)
            db.session.commit()
    return jsonify({
        'bucketlist name': bucketlist.name,
        'items': items,
        'date created': bucketlist.date_created,
        'created by': bucketlist.created_by
    }), 201
Esempio n. 15
0
def edit_tags(id):
    if current_user.is_anony():
        return render_template('403.html')
    ques = Items.query.get(id)
    pt = PostTag.query.filter(PostTag.postid == id).all()
    ptnum = PostTag.query.filter(PostTag.postid == id).count()
    taglist = []
    for p in pt:
        taglist.append(p.items_.title_or_ans)
    while (len(taglist) < 3):
        taglist.append('')
    tagval1 = taglist[0]
    tagval2 = taglist[1]
    tagval3 = taglist[2]
    if request.method == 'POST':
        thesetags = []
        tagval1 = request.form.get('tag1', '???')
        tagval2 = request.form.get('tag2', '???')
        tagval3 = request.form.get('tag3', '???')
        thesetags.append(tagval1)
        thesetags.append(tagval2)
        thesetags.append(tagval3)
        PostTag.query.filter(PostTag.postid == id).delete()
        db.session.commit()
        for t in thesetags:
            if t != '???' and t.strip() != '':
                existing_tag = Items.query.filter(Items.types == 3).filter(
                    Items.title_or_ans == t).first()
                if existing_tag is None:
                    p = Items(title_or_ans=t, types=3)
                    db.session.add(p)
                    db.session.add(p)
                    new_tag = Items.query.filter(Items.types == 3).filter(
                        Items.title_or_ans == t).first()
                    pt = PostTag(postid=id, tagid=new_tag.id)
                    db.session.add(pt)
                    db.session.commit()
                else:
                    old_tag = Items.query.filter(Items.types == 3).filter(
                        Items.title_or_ans == t).first()
                    pt = PostTag(postid=id, tagid=old_tag.id)
                    db.session.add(pt)
                    db.session.commit()
        return redirect(url_for('question', id=ques.id))
    return render_template('edit_tags.html', tagval1 = tagval1, tagval2 = tagval2, tagval3 = tagval3, ques = ques,\
      Permission = Permission)
Esempio n. 16
0
def add_item():
    form = addProductForm(request.form, csrf_enabled=True)
    item_id = 1
    if request.method == 'POST':

        item = Items(name=form.name.data,
                     photo=form.photo.data,
                     price=form.price.data,
                     item_description=form.item_description.data)
        if (item and form.name.data and form.photo.data and form.price.data
                and form.item_description.data):
            db.session.add(item)
            db.session.commit()
            item_id = item.id
            return redirect('view_item/' + str(item_id))
    print("add item:")
    return render_template('additem.html', form=form)
Esempio n. 17
0
def items_restored():
    # Establish the root path on the operating system
    basedir = os.path.abspath(os.path.dirname(__file__))
    # Change the working directory to the backup directory
    os.chdir(basedir + "/app/admin/Items_Backup")
    source_file = 'items_database_categories.py'
    categories_list = []
    # Open the original file default is read only
    with open(source_file) as f:
        # iterate over the lines of the original file
        for line in f:
            split_line = line.split(']')
            split2_line = split_line[0].split('[')
            categories_ids = split2_line[1].split(',')
            categories_list = categories_list + categories_ids
    f.close()
    for category in categories_list:
        # Get the category that the items are being recovered.
        category_obj = app.database.session.query(Categories).filter_by(id=category).first()
        # Establish the root path on the operating system
        basedir = os.path.abspath(os.path.dirname(__file__))
        # Change the working directory to the backup directory
        os.chdir(basedir + "/app/admin/Items_Backup")
        # Open the file that is being used in the recovery
        with open('items_database_export_%s.py' % category_obj.name) as f:
            # iterate ove the lines of the file
            for lines in f:
                if lines.startswith('{'):
                    # ast evaluates the string as an object.
                    item = ast.literal_eval(lines)
                    # create an Items object with the details from the line.
                    new_item = Items(asin=item['asin'], name=item['name'], category_id=item['category_id'],
                                     description=item['description'], created_by='Category')
                    # add the new item
                    app.database.session.add(new_item)
                    app.database.session.commit()
                    # add on the other elements of the item that is not passed in the initiation of the object
                    new_item.small_image = item['small_image']
                    new_item.medium_image = item['medium_image']
                    new_item.large_image = item['large_image']
                    new_item.brand = item['brand']
                    new_item.list_price = item['list_price']
                    new_item.offers = item['offers']
                    app.database.session.add(new_item)
                    app.database.session.commit()

    print 'Items have be recovered'
    return
Esempio n. 18
0
def write_articles():
    if current_user.is_anony():
        return render_template('403.html')
    form = PostForm()
    if request.method == 'POST':
        title = request.form.get('title')
        body = request.form.get('body')
        ar = Article(content=body)
        db.session.add(ar)
        db.session.commit()
        ar = Article.query.filter_by(content=body).first()
        it = Items(title_or_ans=title,
                   author_id=current_user.id,
                   types=1,
                   art_id=ar.id)
        db.session.add(it)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('write_articles.html', form=form)
Esempio n. 19
0
def raise_question():
    if current_user.is_anony():
        return render_template('403.html')
    form = QuestionForm()
    if request.method == 'POST':
        title = request.form.get('title')
        body = request.form.get('body')
        ques = Question(description=body)
        db.session.add(ques)
        db.session.commit()
        q = Question.query.filter_by(description=body).first()
        it = Items(title_or_ans=title,
                   author_id=current_user.id,
                   types=0,
                   ques_id=q.id)
        db.session.add(it)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('raise_question.html', form=form)
Esempio n. 20
0
def addBucketlistItem(id, name, done, user_id):
    try:
        bucketlist = db.session.query(Bucketlists).filter_by(
            created_by=user_id, id=id).one()
        day = time.time()
        date_created = str(
            datetime.datetime.fromtimestamp(day).strftime("%y-%m-%d"))
        item = Items(name=name)
        item.name = name
        item.bucketlist_id = id
        item.done = done
        item.date_created = date_created
        item.date_modified = date_created
        db.session.add(item)
        db.session.commit()
        return jsonify({
            'item name': item.name,
            'date created': item.date_created,
            'date modified': item.date_modified,
            'done': item.done
        }), 201
    except:
        return jsonify({"message": "Sorry bucketlist does not exist"}), 404
Esempio n. 21
0
def seed_items():
    for num in range(16):
        item = Items(
            itemName="GIRL DRESS",
            colors="pink",
            material="Cotton",
            detail="Textured gauze ruffle maci dress with necklace. Imported.",
            photoId=num + 1,
            categoryId=1)
        # item.sizes.push(1)
        db.session.add(item)
    db.session.commit()

    for num in range(8):
        item = Items(
            itemName="GIRL PANT",
            colors="black",
            material="Cotton",
            detail=
            "A colorful floral print creates the fun, fresh look of these comfortable leggings from Ideology.",
            photoId=num + 17,
            categoryId=2)
        # item.sizes.push(1)
        db.session.add(item)
    db.session.commit()

    for num in range(10):
        item = Items(
            itemName="GIRL TOP",
            colors="pink",
            material="Cotton",
            detail=
            "Look lovely in this heart print and bow detail tank by Epic Threads. Bow back detail.",
            photoId=num + 25,
            categoryId=3)
        # item.sizes.push(1)
        db.session.add(item)
    db.session.commit()

    for num in range(16):
        item = Items(
            itemName="TODDLER GIRL DRESS",
            colors="pink",
            material="Polyester",
            detail="Textured gauze ruffle maci dress with necklace. Imported.",
            photoId=num + 1,
            categoryId=4)
        # item.sizes.push(1)
        db.session.add(item)
    db.session.commit()

    for num in range(8):
        item = Items(
            itemName="TODDLER GIRL PANT",
            colors="navy",
            material="Cotton",
            detail=
            "A colorful floral print creates the fun, fresh look of these comfortable leggings from Ideology.",
            photoId=num + 17,
            categoryId=5)
        # item.sizes.push(1)
        db.session.add(item)
    db.session.commit()

    for num in range(10):
        item = Items(
            itemName="TODDLER GIRL TOP",
            colors="pink",
            material="Polyester",
            detail=
            "Look lovely in this heart print and bow detail tank by Epic Threads. Bow back detail.",
            photoId=num + 25,
            categoryId=6)
        # item.sizes.push(1)
        db.session.add(item)
    db.session.commit()

    for num in range(8):
        item = Items(
            itemName="BOY SHIRT",
            colors="gray",
            material="Cotton",
            detail=
            "He will have a fresh update to casual style in this t-shirt, fashioned in soft fabric for comfortable wear.",
            photoId=num + 35,
            categoryId=7)
        # item.sizes.push(1)
        db.session.add(item)
    db.session.commit()

    for num in range(9):
        item = Items(
            itemName="BOY JACKET",
            colors="black",
            material="Polyester",
            detail=
            "No need to mess with an icon. Gear up your star player in this boys jacket and head out the door. The signature sheen of tricot and 3-Stripes give your MVP a winning adidas style. Wash and wear. Repeat.",
            photoId=num + 43,
            categoryId=8)
        # item.sizes.push(1)
        db.session.add(item)
    db.session.commit()

    for num in range(8):
        item = Items(
            itemName="BOY PANT",
            colors="beige",
            material="Cotton",
            detail=
            "Jordan alpha dry pant is great for actives this season. Constructed with dry-fit fabrication to keep you dry in every day activities.",
            photoId=num + 52,
            categoryId=9)
        # item.sizes.push(1)
        db.session.add(item)
    db.session.commit()

    for num in range(8):
        item = Items(
            itemName="TODDLER BOY SHIRT",
            colors="gray",
            material="Cotton",
            detail=
            "He will have a fresh update to casual style in this t-shirt, fashioned in soft fabric for comfortable wear.",
            photoId=num + 35,
            categoryId=10)
        # item.sizes.push(1)
        db.session.add(item)
    db.session.commit()

    for num in range(9):
        item = Items(
            itemName="TODDLER BOY JACKET",
            colors="black",
            material="Polyester",
            detail=
            "No need to mess with an icon. Gear up your star player in this boys jacket and head out the door. The signature sheen of tricot and 3-Stripes give your MVP a winning adidas style. Wash and wear. Repeat.",
            photoId=num + 43,
            categoryId=11)
        # item.sizes.push(1)
        db.session.add(item)
    db.session.commit()

    for num in range(8):
        item = Items(
            itemName="TODDLER BOY PANT",
            colors="beige",
            material="Polyester",
            detail=
            "Jordan alpha dry pant is great for actives this season. Constructed with dry-fit fabrication to keep you dry in every day activities.",
            photoId=num + 52,
            categoryId=12)
        # item.sizes.push(1)
        db.session.add(item)
    db.session.commit()

    item = Items(
        itemName="GRIL DRESS",
        colors="blue",
        material="Cotton",
        detail="Textured gauze ruffle maci dress with necklace. Imported.",
        photoId=15,
        categoryId=1)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="GIRL PANT",
        colors="navy",
        material="Cotton",
        detail=
        "A colorful floral print creates the fun, fresh look of these comfortable leggings from Ideology.",
        photoId=17,
        categoryId=2)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="Girl Top Heart Print",
        colors="pink",
        material="Cotton",
        detail=
        "Look lovely in this heart print and bow detail tank by Epic Threads. Bow back detail.",
        photoId=31,
        categoryId=3)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="TODDLER GRIL DRESS",
        colors="pink",
        material="Polyester",
        detail="Textured gauze ruffle maci dress with necklace. Imported.",
        photoId=7,
        categoryId=4)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="TODDLER GIRL PANTS",
        colors="pink",
        material="Cotton",
        detail=
        "A colorful floral print creates the fun, fresh look of these comfortable leggings from Ideology.",
        photoId=20,
        categoryId=5)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="TODDLER GIRL TOP",
        colors="green",
        material="Polyester",
        detail=
        "Look lovely in this heart print and bow detail tank by Epic Threads. Bow back detail.",
        photoId=29,
        categoryId=6)
    db.session.add(item)

    item = Items(
        itemName="BOY SHIRT",
        colors="white",
        material="Cotton",
        detail=
        "He will have a fresh update to casual style in this t-shirt, fashioned in soft fabric for comfortable wear.",
        photoId=39,
        categoryId=7)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="BOY JACKET",
        colors="navy",
        material="Polyester",
        detail=
        "No need to mess with an icon. Gear up your star player in this boys jacket and head out the door. The signature sheen of tricot and 3-Stripes give your MVP a winning adidas style. Wash and wear. Repeat.",
        photoId=48,
        categoryId=8)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="BOY PANT",
        colors="olive",
        material="Cotton",
        detail=
        "Jordan alpha dry pant is great for actives this season. Constructed with dry-fit fabrication to keep you dry in every day activities.",
        photoId=56,
        categoryId=9)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="TODDLER BOY SHIRT",
        colors="yellow",
        material="Cotton",
        detail=
        "He will have a fresh update to casual style in this t-shirt, fashioned in soft fabric for comfortable wear.",
        photoId=35,
        categoryId=10)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="TODDLER BOY JACKET",
        colors="red",
        material="Polyester",
        detail=
        "No need to mess with an icon. Gear up your star player in this boys jacket and head out the door. The signature sheen of tricot and 3-Stripes give your MVP a winning adidas style. Wash and wear. Repeat.",
        photoId=51,
        categoryId=11)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="TODDLER BOY PANT",
        colors="beige",
        material="Polyester",
        detail=
        "Jordan alpha dry pant is great for actives this season. Constructed with dry-fit fabrication to keep you dry in every day activities.",
        photoId=58,
        categoryId=12)
    # item.sizes.push(1)
    db.session.add(item)

    db.session.commit()
Esempio n. 22
0
    def test_setUp(self):
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(
            basedir, 'test.db')
        self.app = app.test_client()
        db.create_all()

        #SET UP FOR REVIEWS TESTING
        self.content = 'Food was very spicy! Check with the waitress how spicy your dish is beforehand!'
        self.content2 = 'Great cheesy fries'
        self.restaurant = "mexican diner"
        self.restaurant2 = 'Five Guys in Leeds'
        self.length_checks = 'LengthCheckForAllDifferentFieldsInItemsTable'
        self.int_checks = 33
        self.both_cords = '-1.346'
        self.userID = 1
        self.basic_post = Items(restaurant=self.restaurant,
                                content=self.content,
                                location_lat=self.both_cords,
                                location_long=self.both_cords,
                                user_id=self.userID)
        self.post_no_rest = Items(restaurant=None,
                                  content=self.content,
                                  location_lat=self.both_cords,
                                  location_long=self.both_cords,
                                  user_id=self.userID)
        self.post_no_content = Items(restaurant=self.restaurant,
                                     content=None,
                                     location_lat=self.both_cords,
                                     location_long=self.both_cords,
                                     user_id=self.userID)
        self.post_no_cords = Items(restaurant=self.restaurant,
                                   content=self.content,
                                   location_lat=None,
                                   location_long=None,
                                   user_id=self.userID)
        self.post_no_userid = Items(restaurant=self.restaurant,
                                    content=self.content,
                                    location_lat=self.both_cords,
                                    location_long=self.both_cords,
                                    user_id=None)
        self.post_content = Items(restaurant=self.restaurant,
                                  content=self.content2,
                                  location_lat=self.both_cords,
                                  location_long=self.both_cords,
                                  user_id=self.userID)
        self.post_length_rest = Items(restaurant=self.length_checks,
                                      content=self.content,
                                      location_lat=self.both_cords,
                                      location_long=self.both_cords,
                                      user_id=self.userID)
        self.post_length_location = Items(restaurant=self.restaurant,
                                          content=self.content,
                                          location_lat=self.length_checks,
                                          location_long=self.length_checks,
                                          user_id=self.userID)
        self.post_length_content = Items(restaurant=self.restaurant,
                                         content=self.length_checks,
                                         location_lat=self.both_cords,
                                         location_long=self.both_cords,
                                         user_id=self.userID)
        self.post_int_rest = Items(restaurant=self.length_checks,
                                   content=self.content,
                                   location_lat=self.both_cords,
                                   location_long=self.both_cords,
                                   user_id=self.userID)
        self.post_int_location = Items(restaurant=self.restaurant,
                                       content=self.content,
                                       location_lat=self.int_checks,
                                       location_long=self.int_checks,
                                       user_id=self.userID)
        self.post_int_content = Items(restaurant=self.restaurant,
                                      content=self.int_checks,
                                      location_lat=self.both_cords,
                                      location_long=self.both_cords,
                                      user_id=self.userID)
Esempio n. 23
0
def seed_sizes():
    items = []
    size1 = Sizes(size="small", count=4)
    size2 = Sizes(size="medium", count=4)
    size3 = Sizes(size="large", count=4)
    size4 = Sizes(size="2T", count=4)
    size5 = Sizes(size="3T", count=4)
    size6 = Sizes(size="5T", count=4)
    db.session.add(size1)
    db.session.add(size2)
    db.session.add(size3)
    db.session.add(size4)
    db.session.add(size5)
    db.session.add(size6)
    db.session.commit()

    # for num in range(16):
    #     item = Items(itemName="dress", colors="black", material="cotton",
    #                  detail=fake.text(), photoId=num+1, categoryId=1)
    #     print("------------", item.sizes)
    #     print("+++++++++++", item)
    #     db.session.add(item)
    # item = Items(itemName="GRIL DRESS", colors="pink", material="Cotton",
    #              detail="Textured gauze ruffle maci dress with necklace. Imported.",
    #              photoId=5, categoryId=1)
    # # item.sizes.push(1)
    # db.session.add(item)

    # item = Items(itemName="GIRL PANT", colors="orange", material="Cotton",
    #              detail="A colorful floral print creates the fun, fresh look of these comfortable leggings from Ideology.",
    #              photoId=15, categoryId=2)
    # # item.sizes.push(1)
    # db.session.add(item)

    # item = Items(itemName="GIRL TOP", colors="pink", material="Cotton",
    #              detail="Look lovely in this heart print and bow detail tank by Epic Threads. Bow back detail.",
    #              photoId=31, categoryId=3)
    #     # item.sizes.push(1)
    # db.session.add(item)

    # item = Items(itemName="TODDLER GRIL DRESS", colors="yellow", material="Polyester",
    #              detail="Textured gauze ruffle maci dress with necklace. Imported.",
    #              photoId=9, categoryId=4)
    # # item.sizes.push(1)
    # db.session.add(item)

    # item = Items(itemName="TODDLER GIRL PANTS", colors="blue", material="Cotton",
    #              detail="A colorful floral print creates the fun, fresh look of these comfortable leggings from Ideology.",
    #              photoId=20, categoryId=5)
    #     # item.sizes.push(1)
    # db.session.add(item)

    # item = Items(itemName="TODDLER GIRL TOPS", colors="pink", material="Polyester",
    #              detail="Look lovely in this heart print and bow detail tank by Epic Threads. Bow back detail.",
    #              photoId=35, categoryId=6)
    # db.session.add(item)

    # item = Items(itemName="BOY SHIRTS", colors="blue", material="Cotton",
    #              detail="He will have a fresh update to casual style in this t-shirt, fashioned in soft fabric for comfortable wear.",
    #              photoId=40, categoryId=7)
    # # item.sizes.push(1)
    # db.session.add(item)

    # item = Items(itemName="BOY JACKETS", colors="navy", material="Polyester",
    #              detail="No need to mess with an icon. Gear up your star player in this boys jacket and head out the door. The signature sheen of tricot and 3-Stripes give your MVP a winning adidas style. Wash and wear. Repeat.",
    #              photoId=55, categoryId=8)
    # # item.sizes.push(1)
    # db.session.add(item)

    # item = Items(itemName="BOY PANTS", colors="black", material="Cotton",
    #              detail="Jordan alpha dry pant is great for actives this season. Constructed with dry-fit fabrication to keep you dry in every day activities.",
    #              photoId=59, categoryId=9)
    # # item.sizes.push(1)
    # db.session.add(item)

    # item = Items(itemName="TODDLER BOY SHIRTS", colors="blue", material="Cotton",
    #              detail="He will have a fresh update to casual style in this t-shirt, fashioned in soft fabric for comfortable wear.",
    #              photoId=35, categoryId=10)
    # # item.sizes.push(1)
    # db.session.add(item)

    # item = Items(itemName="TODDLER BOY JACKETS", colors="navy", material="Polyester",
    #              detail="No need to mess with an icon. Gear up your star player in this boys jacket and head out the door. The signature sheen of tricot and 3-Stripes give your MVP a winning adidas style. Wash and wear. Repeat.",
    #              photoId=51, categoryId=11)
    # # item.sizes.push(1)
    # db.session.add(item)

    # item = Items(itemName="TODDLER BOY PANTS", colors="black", material="Polyester",
    #              detail="Jordan alpha dry pant is great for actives this season. Constructed with dry-fit fabrication to keep you dry in every day activities.",
    #              photoId=59, categoryId=12)
    # # item.sizes.push(1)
    # db.session.add(item)

    item = Items(
        itemName="GRIL DRESS",
        colors="blue",
        material="Cotton",
        detail="Textured gauze ruffle maci dress with necklace. Imported.",
        photoId=15,
        categoryId=1)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="GIRL PANT",
        colors="navy",
        material="Cotton",
        detail=
        "A colorful floral print creates the fun, fresh look of these comfortable leggings from Ideology.",
        photoId=17,
        categoryId=2)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="Girl Top Heart Print",
        colors="pink",
        material="Cotton",
        detail=
        "Look lovely in this heart print and bow detail tank by Epic Threads. Bow back detail.",
        photoId=31,
        categoryId=3)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="TODDLER GRIL DRESS",
        colors="pink",
        material="Polyester",
        detail="Textured gauze ruffle maci dress with necklace. Imported.",
        photoId=7,
        categoryId=4)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="TODDLER GIRL PANTS",
        colors="pink",
        material="Cotton",
        detail=
        "A colorful floral print creates the fun, fresh look of these comfortable leggings from Ideology.",
        photoId=20,
        categoryId=5)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="TODDLER GIRL TOP",
        colors="green",
        material="Polyester",
        detail=
        "Look lovely in this heart print and bow detail tank by Epic Threads. Bow back detail.",
        photoId=29,
        categoryId=6)
    db.session.add(item)

    item = Items(
        itemName="BOY SHIRT",
        colors="white",
        material="Cotton",
        detail=
        "He will have a fresh update to casual style in this t-shirt, fashioned in soft fabric for comfortable wear.",
        photoId=39,
        categoryId=7)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="BOY JACKET",
        colors="navy",
        material="Polyester",
        detail=
        "No need to mess with an icon. Gear up your star player in this boys jacket and head out the door. The signature sheen of tricot and 3-Stripes give your MVP a winning adidas style. Wash and wear. Repeat.",
        photoId=48,
        categoryId=8)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="BOY PANT",
        colors="olive",
        material="Cotton",
        detail=
        "Jordan alpha dry pant is great for actives this season. Constructed with dry-fit fabrication to keep you dry in every day activities.",
        photoId=56,
        categoryId=9)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="TODDLER BOY SHIRT",
        colors="yellow",
        material="Cotton",
        detail=
        "He will have a fresh update to casual style in this t-shirt, fashioned in soft fabric for comfortable wear.",
        photoId=35,
        categoryId=10)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="TODDLER BOY JACKET",
        colors="red",
        material="Polyester",
        detail=
        "No need to mess with an icon. Gear up your star player in this boys jacket and head out the door. The signature sheen of tricot and 3-Stripes give your MVP a winning adidas style. Wash and wear. Repeat.",
        photoId=51,
        categoryId=11)
    # item.sizes.push(1)
    db.session.add(item)

    item = Items(
        itemName="TODDLER BOY PANT",
        colors="beige",
        material="Polyester",
        detail=
        "Jordan alpha dry pant is great for actives this season. Constructed with dry-fit fabrication to keep you dry in every day activities.",
        photoId=58,
        categoryId=12)
    # item.sizes.push(1)
    db.session.add(item)

    db.session.commit()
    for i in range(4):
        for size in [size1, size2, size3, size4]:
            item.sizes.append(size)
        db.session.commit()
        # size1.items.append(item)
    db.session.commit()
Esempio n. 24
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)
Esempio n. 25
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)
Esempio n. 26
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))
Esempio n. 27
0
def question(id):
    if current_user.is_anony():
        return redirect(url_for('question_for_anonymous', id=id))
    ques = Items.query.filter(Items.id == id, Items.deleted == 0).first()
    ansform = AnswerForm()
    if ansform.validate_on_submit():
        allans = Answer.query.filter_by(belongtoques=id).all()
        for a in allans:
            p = Items.query.filter_by(ans_id=a.id).first()
            if p.author_id == current_user.id:
                return render_template('not.html', text=u'您不能回答同一个问题两次')
        ans = Answer(belongtoques=id)
        db.session.add(ans)
        db.session.commit()
        a = Answer.query.order_by(
            Answer.id.desc()).filter_by(belongtoques=id).first()
        e = Items(title_or_ans=ansform.answer.data,
                  author_id=current_user.id,
                  types=2,
                  ans_id=a.id)
        db.session.add(e)
        db.session.add(a)
        db.session.commit()
    ansnum = Answer.query.filter(Answer.belongtoques == id).count()
    allans = Answer.query.filter(Answer.belongtoques == id).all()
    for a in allans:
        if Items.query.filter_by(ans_id=a.id).first().deleted == 1:
            ansnum = ansnum - 1
    ans_ = Answer.query.filter(Answer.belongtoques == id).all()
    ans_id_ = []
    ansdo = []
    for a in ans_:
        ans_id_.append(a.id)
    ans = Items.query.filter(Items.types == 2, Items.deleted == 0).filter(
        Items.ans_id.in_(ans_id_)).all()
    ans_id = []
    for a in ans:
        ans_id.append(a.id)
    i_do_to_the_ans = Upvote.query.filter(
        Upvote.upvoter == current_user.id).filter(
            Upvote.answerid.in_(ans_id)).all()
    for i in i_do_to_the_ans:
        if Items.query.get(i.answerid).deleted == 0:
            ansdo.append((i.answerid, i.descr))
    pt = PostTag.query.filter_by(postid=id).all()
    the_ques_tags_id = []
    related = []
    for p in pt:
        the_ques_tags_id.append(p.tagid)
    the_ques_tags = Items.query.filter(Items.id.in_(the_ques_tags_id)).all()
    rposts_rcds = PostTag.query.filter(
        PostTag.tagid.in_(the_ques_tags_id)).all()
    for r in rposts_rcds:
        related.append(r.postid)
    related = list(set(related))
    if len(related) != 0:
        related.remove(id)
        rposts = Items.query.filter(Items.id.in_(related),
                                    Items.deleted == 0).all()
    else:
        rposts = []
    thank = []
    thank_ = Thank.query.filter(Thank.personid == current_user.id).filter(
        Thank.postid.in_(ans_id)).all()
    for t in thank_:
        thank.append(t.postid)
    return render_template('question.html', ques = ques, form = ansform, Permission = Permission, \
     ans = ans, ansdo = ansdo, tags= the_ques_tags, ansnum = ansnum, rposts = rposts, thank = thank)
Esempio n. 28
0
def boardinfo(address):
    if request.method == "GET":
        board = Boards.query.filter_by(board_address=address).first()
        board_expenses = Expenses.query.filter_by(
            board_id=board.board_id).all()
        expenses = set
        for ticket in board_expenses:
            # 1 ticket/expense
            payers = set()
            for pay in eval(ticket.payers):
                payers.add({'name': pay[0], 'amount': pay[1]})
            ticket_items = []
            for item in Items.query.filter_by(
                    expense_id=ticket.expense_id).all():
                # 1 item of 1 ticket
                concerned = set()
                for name, quantity, amount in eval(item.concerned_users):
                    concerned.add({
                        'name': name,
                        'quantity': quantity,
                        'sum': amount
                    })
                item += [{
                    "name": item.item_name,
                    "price": item.item_price,
                    "concerned": concerned
                }]
            expenses.add({
                'payers': payers,
                'items': ticket_items,
                'total': ticket.amount,
                'date': ticket.date
            })

        return json.dumps({
            'address': address,
            'participants': board.users_list,
            'expenses': expenses
        })
    elif request.method == "PUT":
        board_name = request.args.get('name')
        users = eval(request.args.get('users'))
        print(users)
        address = str(uuid.uuid4())
        newboard = Boards(board_address=address,
                          name=board_name,
                          users_list=repr(users))
        db.session.add(newboard)
        db.session.commit()
        print("Created board:", newboard)
        return json.dumps({'address': address})

    elif request.method == "POST":
        try:
            exp_id = int(request.args.get('expense_id'))
            amount = float(request.args.get('total'))
            date = request.args.get('date')
            payers = eval(request.args.get('payers'))
            ticket_items = eval(request.args.get("items"))
        except ValueError as e:
            return json.dumps({"code": 400, "error": e})
        expense = Expenses.query.get(exp_id)
        expense.amount = amount
        expense.payers = payers
        expense.date = date
        for item_name, item_price, concerned_list in ticket_items:
            new_item = Items(expense_id=exp_id,
                             item_name=item[0],
                             concerned_users=repr(concerned_list))
            db.session.add(new_item)
        db.session.commit()
        return json.dumps({'code': 200})
Esempio n. 29
0
def addItem():

    form = ItemForm()

    if form.validate_on_submit():

        # Check if adding this item would bring total items being tracked to greater than 30
        if len(current_user.items.all()) > 30:
            flash("Error: cannot track more than 30 items.", "error")
            return redirect(url_for("items.items"))

        # The user has altered the item name.
        if form.hidden.data and not form.hidden.data == form.itemName.data:

            # Use the unmodified item name to query the database
            itemName = form.hidden.data

            # Go through all the sales for the item and update the foreign key due to name change.
            updateForeignKey = True

        else:
            itemName = form.itemName.data
            updateForeignKey = False

        item = Items.query.filter_by(user=current_user).filter_by(
            itemName=itemName).first()

        edit = True

        # User has entered an item name that is in database, but did not arrive through the editing route.
        if item and not form.hidden.data:
            flash(
                f"Item '{itemName}' is already in database.  Use editing option to adjust it.", "error")
            return redirect(url_for("items.items"))

        # Create a new Items object if the user is entering a new item
        if item is None:
            item = Items()
            edit = False

        # Capture sales for current item in case of an item name change in the next function
        if edit:
            sales = item.sales.all()

        # Update item object with new data from form.
        populateItemsObject(item, form, edit=edit)

        # The profit for each sale will be updated given the new item information from user
        if edit:
            for sale in sales:
                if updateForeignKey:
                    # Update each sale's itemName to the new itemName from form
                    sale.itemName = item.itemName
                calculateProfit(sale)

            flash(f"Item {item.itemName} updated.", "success")
        else:
            flash(f"{item.itemName} added.", "success")

        db.session.add(item)
        db.session.commit()

        return redirect(url_for("items.items"))

    return render_template("items/addItem.html", form=form, action="Edit" if form.data['hidden'] else "Add New", itemsRemaining=db.session.query(func.count(Items.itemName)).filter_by(
        username=current_user.username).scalar())
def main(result):
    from app.models import Items, Retailer
    retailer_details = Retailer.get_retailer_ids()
    from app import db
    search_string = result.search_string
    category_name = result.category
    all_eventuals = []
    try:
        all_eventuals.append(
            scrape_amazon_with_crochet(retailer_id=retailer_details['amazon'],
                                       search_string=search_string,
                                       category_name=category_name))
        all_eventuals.append(
            scrape_flipkart_with_crochet(
                retailer_id=retailer_details['flipkart'],
                search_string=search_string,
                category_name=category_name))
        all_eventuals.append(
            scrape_paytm_with_crochet(retailer_id=retailer_details['paytm'],
                                      search_string=search_string,
                                      category_name=category_name))
        if category_name == 'laptops' or category_name == 'mobiles':
            all_eventuals.append(
                scrape_croma_with_crochet(
                    retailer_id=retailer_details['croma'],
                    search_string=search_string,
                    category_name=category_name))
            # Query all the categories here. Get the key for each shop in the spider calling functions
            # Scrape Croma
            if 'asus' in search_string.lower():
                # Scrape asus online store
                pass
            elif 'hp' in search_string.lower():
                # Scrape hp online store
                pass
        elif category_name == 'mensfashion':
            pass
        elif category_name == "womensfashion":
            pass
            # scrape myntra, jabong, shein
        for eventual in all_eventuals:
            eventual.wait(timeout=15)
        num = 0
        for index, i in enumerate(output_data):
            item_name = i['item_name']
            retailer_id = i['retailer_id']
            item = Items.query.filter_by(item_name=item_name,
                                         retailer_id=retailer_id).first()
            if item:
                print("Item exists. Appending the result")
                item.results.append(result)
            else:
                num += 1
                item = Items(category=category_name, **i)
                db.session.add(item)
                db.session.commit()
                print("Item created. Adding to result")
                item.results.append(result)
    except crochet.TimeoutError:
        pass
    else:
        print(f"Web scraping output count - {index + 1 }")
        print(f"{num} New distinct items added to DB..")
        db.session.commit()
    finally:
        # Clear the output data list, to avoid mix ins with other results.
        output_data.clear()
        num = 0