Пример #1
0
def basket_add():
    entry = Basket()
    entry.member = session['uid']
    entry.goods = request.form.get('goods_id')
    entry.goods_cnt = request.form.get('quantity')
    
    db_session.add(entry)
    db_session.commit()

    return redirect("/basket")
Пример #2
0
 def add_item(self,request):
     u = self.current_user(request)
     prodid = int(request.REQUEST['id'])
     if 'value' in request.REQUEST:
         value = request.REQUEST['value']
         token = request.REQUEST['token']
         visual = request.REQUEST['visual']
         s = Sellable(user=u,name=token,value=value,sellid=prodid,visual=visual); s.save()
         if 'qty' in request.REQUEST:
             for i in range(int(request.REQUEST['qty'])-1):
                 s = Sellable(user=u,name=token,value=value,sellid=prodid,visual=visual); s.save()
     exists = Basket.objects.all().filter(user=u,product=prodid)
     if not len(exists): 
         basket = Basket(user=u,product=prodid)
         basket.save()
     return self.view_items(request)
Пример #3
0
def list(event, context):
    customer_id = event['pathParameters']['id']

    basket = Basket.query(customer_id)

    return {
        'statusCode': 200,
        'body': json.dumps({'items': [dict(result) for result in basket]})
    }
Пример #4
0
    async def get_user_basket_items(u_id, loop):
        con, cur = await create_con(loop)
        await cur.execute('select * from basket where u_id = %s', u_id)
        items = await cur.fetchall()

        result = []
        for item in items:
            result.append(
                Basket(item[0], item[1], item[2], item[3], item[4], item[5]))
        return result
Пример #5
0
def get(event, context):
    customer_id = event['pathParameters']['id']
    item_id = event['pathParameters']['product_id']

    try:
        basket = Basket.get(customer_id, item_id)

        return {'statusCode': 200, 'body': basket.body()}
    except:
        raise Exception("Invalid request")
Пример #6
0
def create(event, context):
    data = json.loads(event['body'])

    customer_id = data['customer_id']
    product_id = data['product_id']
    basket = None

    # check if the item is in the basket already, if so we're gonna just add to it
    try:
        basket = Basket.get(customer_id, product_id)

        if basket is not None:
            basket.quantity = basket.quantity + data['quantity']
    except:
        pass

    if basket is None:
        basket = Basket(customer_id=customer_id,
                        product_id=product_id,
                        quantity=data['quantity'],
                        price=data['price'])

    basket.save()

    return {"statusCode": 200, "body": basket.body()}
Пример #7
0
def generate_basket(session: Session, count: int, users: list) -> list:
    result = []
    for i in range(count):

        user = users[random.randint(0, len(users) - 1)]

        basket = Basket(users=user)
        session.add(basket)

        result.append(basket)
    session.commit()
    for i in result:
        session.refresh(i)
        log.debug(f"Generate basket: {i}")
    return result
Пример #8
0
    async def put(request: Request) -> Response:
        try:
            login = await authorized_userid(request)
            if not login:
                return respond_with_json({"error": "Unauthorized"}, status=401)
            else:
                conn = request.app['db_pool']
                Session = sessionmaker(bind=conn)
                session = Session()
                user = Users.get_user_by_login_sync(session, login=login)
            if not user:
                return respond_with_json(
                    {"error": F"No user with login {login}"}, status=404)

            data = await request.json()
            if data:
                basket = session.query(Basket).filter_by(users=user).filter_by(
                    order=None).first()
                if not basket:
                    basket = Basket(users=user)

                try:
                    for product in data["products"]:
                        product_shop = session.query(ProductShop).filter_by(
                            id=product['id']).first()
                        product_in_basket = ProductInBasket(
                            basket=basket,
                            product_shop=product_shop,
                            quantity=product['quantity'])
                        session.add(product_in_basket)
                    session.commit()
                except Exception as ex:
                    session.rollback()
                    log.warning(
                        f"Endpoint: basket, Method: put. Msg:{str(ex)}")
                    return respond_with_json(
                        {"error": "Internal Server Error"}, status=500)

                return respond_with_json({"msg": "Products add successfully"})
            else:
                return respond_with_json({"error": "No parameters"},
                                         status=400)
        except Exception as ex:
            log.warning(f"Endpoint: basket, Method: put. Msg:{str(ex)}")
            return respond_with_json({"error": "Internal Server Error"},
                                     status=500)
Пример #9
0
def update(event, context):
    #    if 'requestContext' in event:
    #        if 'identity' in event['requestContext']:
    #            if 'cognitoIdentityId' in event['requestContext']['identity']:
    #                id = event['requestContext']['identity']['cognitoIdentityId']
    #    else:
    id = event['pathParameters']['id']

    data = json.loads(event['body'])

    product_id = data['product_id']

    try:
        basket = Basket.get(id, product_id)

        basket.quantity = data['quantity']

        basket.save()

        return {'statusCode': 200, 'body': {basket.body()}}
    except Exception as ex:
        logger.error(ex)
        raise Exception("Invalid request")
Пример #10
0
    from basket.list import list

if 'ENV' in os.environ:
    from get import get
else:
    from basket.get import get

logger = logging.getLogger()

if __name__ == "__main__":
    from uuid import uuid4
    import random
    # Tests the model against a local DynamoDB
    # docker run --rm -p 8000:8000 amazon/dynamodb-local:latest

    if not Basket.exists():
        Basket.create_table(read_capacity_units=100,
                            write_capacity_units=100,
                            wait=True)

    customer_id = str(uuid4())

    print('###Test creating basket')
    for x in range(1, 6):
        item = {
            "customer_id": customer_id,
            "product_id": str(x),
            "price": random.uniform(0.99, 10.99),
            "quantity": random.randint(1, 10)
        }
        event = {'body': json.dumps(item)}
Пример #11
0
def add_basket(request):
    #Basket view( can change and delete items in basket)
    if request.method == 'POST':
        if 'del' in request.POST:
            basket_del = Basket.objects.get(pk=int(request.POST['b_pk']))
            basket_del.delete()
        elif 'save' in request.POST:
            basket_plus = Basket.objects.get(pk=int(request.POST['b_pk']))
            basket_plus.quantity = int(request.POST['quant'])
            basket_plus.sum_total = basket_plus.quantity * basket_plus.price
            basket_plus.save()
        else:
            good = Goods.objects.get(pk=int(request.POST['pk']))
            basket = Basket()
            if request.user.is_authenticated():
                basket.user = request.user
            if not request.session.exists(request.session.session_key):
                request.session.create()
            basket.basket_id = request.session.session_key
            basket.item = good.title
            basket.partnumber = good.partnumber
            basket.price = good.good_price
            basket.quantity = int(request.POST['quantity'])
            basket.order_number = random.randint(1, 1000000000)
            basket.sum_total = basket.quantity * basket.price
            basket.save()
        baskets = Basket.objects.filter(basket_id=request.session.session_key)
        summ = 0
        for bas in baskets:
            summ += bas.sum_total
        templ = loader.get_template("add_basket.html")
        context = RequestContext(request, {'baskets': baskets, 'summ': summ})
        return HttpResponse(templ.render(context))
    else:
        templ = loader.get_template("errors.html")
        error = "Get request! o.O"
        context = RequestContext(request, {'error': error})
        return HttpResponse(templ.render(context))
Пример #12
0
def add_basket(request):
    #Basket view( can change and delete items in basket)
    if request.method == 'POST':
        if 'del' in request.POST:
            basket_del = Basket.objects.get(pk=int(request.POST['b_pk']))
            basket_del.delete()
        elif 'save' in request.POST:
            basket_plus = Basket.objects.get(pk=int(request.POST['b_pk']))
            basket_plus.quantity = int(request.POST['quant'])
            basket_plus.sum_total = basket_plus.quantity * basket_plus.price
            basket_plus.save()
        else:
            good = Goods.objects.get(pk=int(request.POST['pk']))
            basket = Basket()
            if request.user.is_authenticated():
                basket.user = request.user
            if not request.session.exists(request.session.session_key):
                request.session.create()
            basket.basket_id = request.session.session_key
            basket.item = good.title
            basket.partnumber = good.partnumber
            basket.price = good.good_price
            basket.quantity = int(request.POST['quantity'])
            basket.order_number = random.randint(1, 1000000000)
            basket.sum_total = basket.quantity * basket.price
            basket.save()
        baskets = Basket.objects.filter(basket_id = request.session.session_key)
        summ = 0
        for bas in baskets:
            summ += bas.sum_total
        templ = loader.get_template("add_basket.html")
        context = RequestContext(request, {'baskets':baskets, 'summ':summ})
        return HttpResponse(templ.render(context))
    else:
        templ = loader.get_template("errors.html")
        error = "Get request! o.O"
        context = RequestContext(request, {'error':error})
        return HttpResponse(templ.render(context))
Пример #13
0
def products_select(id):
    products = Products.query.all()
    selected_customer = Customers.query.get_or_404(id)
    if request.method == 'POST':

        # Choose product form:
        if request.form.get('product_id') or request.form.get(
                'product_name') or request.form.get('product_id_list'):
            if request.form.get('product_id'):
                product_id = int(request.form.get('product_id'))
                selected_product = Products.query.get_or_404(product_id)
                existing = Basket.query.filter_by(
                    product_id=selected_product.products_id).first()
                if existing:
                    basket = Basket.query.all()
                else:
                    to_basket = Basket(
                        product_id=selected_product.products_id,
                        product_name=selected_product.name,
                        product_price=selected_product.price,
                        product_group=selected_product.group,
                        stock_quantity=selected_product.stock_quantity)
                    db.session.add(to_basket)
                    db.session.commit()
                    basket = Basket.query.all()
                return render_template('invoicing.html',
                                       products=products,
                                       selected_customer=selected_customer,
                                       basket=basket)

            elif request.form.get('product_id_list'):
                product_id = int(request.form.get('product_id_list'))
                selected_product = Products.query.get_or_404(product_id)
                existing = Basket.query.filter_by(
                    product_id=selected_product.products_id).first()
                if existing:
                    basket = Basket.query.all()
                else:
                    to_basket = Basket(
                        product_id=selected_product.products_id,
                        product_name=selected_product.name,
                        product_price=selected_product.price,
                        product_group=selected_product.group,
                        stock_quantity=selected_product.stock_quantity)
                    db.session.add(to_basket)
                    db.session.commit()
                    basket = Basket.query.all()
                return render_template('invoicing.html',
                                       products=products,
                                       selected_customer=selected_customer,
                                       basket=basket)

            basket = Basket.query.all()
            return render_template('invoicing.html',
                                   products=products,
                                   selected_customer=selected_customer,
                                   basket=basket)

        #Choosing product quantity
        elif request.form.get('product_qty'):
            selected_qty = request.form.get('product_qty').split(' ')
            product_id = int(selected_qty[0])
            product_qty = int(selected_qty[1])
            current_product = Basket.query.filter_by(
                product_id=product_id).first()
            current_product.product_quantity = product_qty
            current_product.product_amount = current_product.product_price * current_product.product_quantity
            db.session.commit()
            basket = Basket.query.all()
            return render_template('invoicing.html',
                                   products=products,
                                   selected_customer=selected_customer,
                                   basket=basket)
            #return render_template('test.html', selected_qty=selected_qty, product_id=product_id, product_qty=product_qty, current_product=current_product)

        #Clean basket
        elif request.form.get('clean'):
            basket = Basket.query.all()
            for product in basket:
                db.session.delete(product)
            db.session.commit()
            return render_template('invoicing.html',
                                   products=products,
                                   selected_customer=selected_customer)

        #Make invoice
        elif request.form.get('make_invoice'):
            basket = Basket.query.all()
            new_invoice = Invoices(customer=selected_customer)
            net_sum = 0
            for item in basket:
                product_qty = item.product_quantity
                total_price = item.product_amount
                new_product = Products.query.get_or_404(item.product_id)
                new_invoice.invoicing.append(new_product)
                net_sum += round(float(total_price), 2)
                new_quantity = Quantities(invoice=new_invoice,
                                          product=new_product,
                                          order_quantity=product_qty,
                                          total_price=total_price)
                db.session.add(new_quantity)
                db.session.delete(item)
            new_invoice.net = net_sum
            new_invoice.tax = round(float(new_invoice.net * 0.23), 2)
            new_invoice.sum = round(float(new_invoice.net + new_invoice.tax),
                                    2)
            db.session.add(new_invoice)
            db.session.commit()
            new_invoice = Invoices.query.order_by("-invoices_id").first()
            payment_day = new_invoice.date + datetime.timedelta(
                days=selected_customer.payment)
            new_invoice.payment_date = payment_day
            db.session.commit()
            new_invoice = Invoices.query.order_by("-invoices_id").first()
            return render_template('invoicing.html',
                                   products=products,
                                   selected_customer=selected_customer,
                                   new_invoice=new_invoice,
                                   payment_day=payment_day)

    return render_template('invoicing.html',
                           products=products,
                           selected_customer=selected_customer)