Exemplo n.º 1
0
def checkout(request):
    context = {}
    print('url = ',request.build_absolute_uri)
    cart_obj, cart_created = Cart.objects.new_or_get(request)
    billing_address_id = request.session.get('billing_address_id', None)
    shipping_address_id = request.session.get('shipping_address_id', None)
    
    billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request)

    order_obj = None
    if cart_created or cart_obj.cart_items.count() == 0:
        return redirect('/')

    login_form = LoginForm()
    guest_form = GuestForm()

    if billing_profile : 
        if not shipping_address_id :
            return redirect('addresses:shipping_address')
        if not billing_address_id:
            return redirect('addresses:billing_address')
        context['shipping_address'] = Address.objects.get(id=shipping_address_id, billing_profile=billing_profile)
        context['billing_address'] = Address.objects.get(id=billing_address_id,  billing_profile=billing_profile)

    if request.method == "POST":
        if billing_profile is not None:
            print('billing exist')
            order_obj, new_obj = Order.objects.new_or_get(billing_profile, cart_obj)
        if shipping_address_id:
            print(shipping_address_id)
            order_obj.shipping_address = Address.objects.get(id=shipping_address_id)
        if billing_address_id:
            print(billing_address_id)
            order_obj.billing_address = Address.objects.get(id=billing_address_id)
        if billing_address_id or shipping_address_id:
            order_obj.save()

            order_item = OrderItem()
            for item in cart_obj.cart_items.all():
                order_item = OrderItem()
                order_item.order = order_obj
                order_item.item = item.item
                order_item.quantity = item.quantity
                order_item.total = item.total
                order_item.save()
                
            cart_obj.cart_items.all().delete()
            del request.session['item_count']
            return redirect("success")

    context['order'] = order_obj
    context['form'] = login_form
    context['guest_form'] = guest_form
    context['cart'] = cart_obj
    context['billing_profile'] = billing_profile

    return render(request, 'carts/checkout.html', context)
Exemplo n.º 2
0
def test_merge_same_products(
    buyer,
    traidoo_region,
    products,
    delivery_address,
    delivery_options,
    seller,
    logistics_user,
):
    order = Order(buyer=buyer, region=traidoo_region)
    order.save()
    order.recalculate_items_delivery_fee()

    order_items = [
        OrderItem(
            product=products[0],
            quantity=5,
            order=order,
            delivery_address=delivery_address,
            delivery_option=delivery_options[0],
            latest_delivery_date=(timezone.now().date() + datetime.timedelta(days=3)),
        ),
        OrderItem(
            product=products[0],
            quantity=5,
            order=order,
            delivery_address=delivery_address,
            delivery_option=delivery_options[0],
            latest_delivery_date=(timezone.now().date() + datetime.timedelta(days=2)),
        ),
        OrderItem(
            product=products[0],
            quantity=5,
            order=order,
            delivery_address=delivery_address,
            delivery_option=delivery_options[0],
            latest_delivery_date=(timezone.now().date() + datetime.timedelta(days=1)),
        ),
    ]

    [items.save() for items in order_items]
    order.recalculate_items_delivery_fee()

    factory = factories.ProducerInvoiceFactory(
        order=order, seller=seller, region=traidoo_region
    )

    assert len(factory._items) == 1
    assert factory._items[0].product == products[0]
    assert factory._items[0].quantity == 15
    assert factory._items[0].product_snapshot == order_items[0].product_snapshot
    assert factory._items[0].order == order
    assert factory._items[0].delivery_address == order_items[0].delivery_address
    assert factory._items[0].delivery_option == order_items[0].delivery_option
    assert factory._items[0].latest_delivery_date == order_items[0].latest_delivery_date
Exemplo n.º 3
0
def modal(request):
    t = loader.get_template("orders/modalmenu.html")
    if request.method == "POST":
        i = int(request.POST["itemid"])
        item = Menu.objects.get(id=i)
        cart = Cart.objects.get(user_id=request.user.id)
        r = {
            "item": item.item,
            "itemid": i,
            "category": item.category.item,
            "size": request.POST["size"],
            "price": float(request.POST["price"]),
            "quantity": int(request.POST["quantity"]),
            "cart": cart,
            "toppings": request.POST.getlist("toppings[]"),
        }
        form = CreateOrderItem(r, x=i)
        if form.is_valid():
            r.pop("itemid")
            toppingspop = r.pop("toppings")
            orditem = OrderItem(**r)
            orditem.save()
            if len(toppingspop) > 0:
                orditem.toppings.set(toppingspop)
                orditem.save()

            return HttpResponse("it was a success!", status=200)
        else:
            return HttpResponse(t.render({"form": form}, request), status=422)

    elif request.method == "GET":
        i = int(request.GET["item"])
        item = Menu.objects.get(id=i)
        form = CreateOrderItem(x=i, initial={"size": "Large"})
        return HttpResponse(t.render({"item": item, "form": form}, request))
Exemplo n.º 4
0
    def save(self, user, commit=True):
        from django.contrib.contenttypes.models import ContentType
        #
        booking = super(BookingForm, self).save(commit=False)

        booking.booked_by = user
        open_order_list = Order.objects.open_order(user=user)
        if open_order_list:
            order = open_order_list[0]

        if commit:
            booking.save()

            # Add to open order
            if not open_order_list:
                order = Order(ordered_by=user)

            order.save()

            order_item = OrderItem(
                order=order,
                description=booking.price.__unicode__(),
                value=(booking.price.value * booking.quantity),
                vat=booking.price.vat,
                content_type=ContentType.objects.get_for_model(booking),
                object_id=booking.id)

            order_item.save()

        return booking
Exemplo n.º 5
0
    def handle(self, *args, **options):

        reference = datetime(2018, 1, 1, 9, 0, 0, 0, datetime_tz.utc)
        new_order_number = Order.objects.order_by().aggregate(max_number=Coalesce(Max('number'), 0))['max_number'] + 1
        new_orders_amount = options['amount']

        orders_to_create = []
        for i in range(new_orders_amount):
            num = new_order_number + i
            orders_to_create.append(Order(
                number=num,
                created_date=reference + timedelta(hours=num - 1)
            ))
        orders = Order.objects.bulk_create(orders_to_create)

        # to get id (non-PostgreSQL db)
        orders = (Order.objects.filter(number__gte=new_order_number)
                  # .annotate(cnt_items=Count('items')).filter(cnt_items=0)
                  .order_by('id'))

        order_items_to_create = []
        for order_id, order_number in orders.values_list('id', 'number'):
            for i in range(randint(1, 5)):
                order_items_to_create.append(OrderItem(
                    order_id=order_id,
                    product_name='Товар{}-{}'.format(order_number, i + 1),
                    product_price=uniform(100, 9999),
                    amount=randint(1, 10)
                ))
        items = OrderItem.objects.bulk_create(order_items_to_create)

        print('Created {} orders and {} order items'.format(len(orders_to_create), len(order_items_to_create)))
Exemplo n.º 6
0
def order_custom(request):
    config = OrderConfig.objects.get(id=1)
    options = CustomCakeOrderConfigOption.objects.filter(
        available=True).order_by('sort')
    if request.method == 'POST':
        custom_cake_order_form = CustomCakeOrderForm(data=request.POST,
                                                     options=options)
        order_form = OrderForm(request.POST)
        if custom_cake_order_form.is_valid() and order_form.is_valid():
            product = Product.objects.get(slug='custom-cake')
            new_order = order_form.save()
            OrderItem(price=product.price,
                      quantity=1,
                      product=product,
                      order_id=new_order.id).save()
            new_order.send_admin_custom_cake_confirm_emails(
                custom_cake_order_form.cleaned_data)
            new_order.send_client_custom_cake_confirm_emails(
                custom_cake_order_form.cleaned_data)
            return render(request,
                          template_name='orders/order/custom-done.html',
                          context={'config': config})
    else:
        custom_cake_order_form = CustomCakeOrderForm(options)
        # cake_form = CustomCakeForm()
        order_form = OrderForm()
    return render(
        request,
        'orders/order/custom.html',
        {
            'config': config,
            # 'cake_form': cake_form,
            'order_form': order_form,
            'ok': custom_cake_order_form
        })
Exemplo n.º 7
0
def create_order(request):
    cart = request.data.get("cart")
    orderData =  request.data.get("order")
    orderData['user'] = request.user
    serializers = OrderSerializer(orderData)
    print(orderData)
   
    order = Order.objects.create(
        firstname = orderData['firstname'],
        lastname = orderData['lastname'],
        email = orderData['email'],
        address = orderData['address'],
        city = orderData['city'],
        postal_code = orderData['postal_code'],
        user = request.user
    )
    if cart:
        for item in cart:
            product = get_object_or_404(Product, id=item['id']) 
            order_item = OrderItem(
                order=order,
                product = product,
                price = item['price'],
                quantity = item['quantity']
                
            )
            order_item.save()
    else:
        order.delete()
        return Response(status=HTTP_400_BAD_REQUEST,data='Cart is Empty')
    return Response({'order_no': order.id},
                    status=HTTP_201_CREATED)
Exemplo n.º 8
0
    def update(self, instance, validated_data):
        if validated_data.get('status') is not None:
            if self.context['request'].user.is_superuser:
                instance.status = validated_data.get('status', instance.status)
                instance.save()
                return instance
            else:
                raise serializers.ValidationError(
                    'Only the admin can change status')

        item_data = validated_data.pop('item')
        raw_item = []

        for item_data in item_data:
            items = OrderItem(
                order=instance,
                product=item_data['product'],
                quantity=item_data['quantity'],
            )

            raw_item.append(items)
        OrderItem.objects.filter(order=instance).delete()
        OrderItem.objects.bulk_create(raw_item)
        instance.sum_order = instance.total_price
        instance.save()
        return instance
Exemplo n.º 9
0
 def test_get_total_cost(self):
     for item in range(10):
         order_item = OrderItem(order=self.order,
                                product=self.product,
                                price=1,
                                count=1)
         order_item.save()
     self.assertEqual(self.order.get_total_cost(), 10)
Exemplo n.º 10
0
def create_order():
    user = current_user
    # You can not check is user is not None because user is LocalProxy even when no authenticated
    # to check if the user is authenticated we may do hasattr
    user_id = user.id if hasattr(user, 'id') else None

    address_id = request.json.get('address_id', None)

    if address_id is not None:
        # reusing address, the user has to be authenticated and owning that address
        address = Address.query.filter_by(id=address_id, user_id=user_id).first()
        if address is None:
            return get_error_response('Permission Denied, you can not use this address', 401)
    else:
        first_name = request.json.get('first_name', None)
        last_name = request.json.get('last_name', None)
        zip_code = request.json.get('zip_code', None)
        street_address = request.json.get('address', None)
        country = request.json.get('address', None)
        city = request.json.get('address', None)

        if user_id is not None:
            if first_name is None:
                first_name = user.first_name

            if last_name is None:
                last_name = user.last_name

        address = Address(first_name=first_name, last_name=last_name, city=city, country=country,
                          street_address=street_address, zip_code=zip_code, )
        if hasattr(user, 'id'):
            address.user_id = user.id

        db.session.add(address)
        db.session.flush()  # we would need the address.id so let's save the address to the db to have the id

    import faker
    fake = faker.Faker()
    order = Order(order_status=0, tracking_number=fake.uuid4(), address_id=address.id)

    cart_items = request.json.get('cart_items')
    product_ids = [ci['id'] for ci in cart_items]
    products = db.session.query(Product).filter(Product.id.in_(product_ids)).all()
    if len(products) != len(cart_items):
        return get_error_response('Error, make sure all products you want to order are still available')

    for index, product in enumerate(products):
        order.order_items.append(OrderItem(price=product.price,
                                           quantity=cart_items[index]['quantity'], product=product,
                                           name=product.name,
                                           slug=product.slug,
                                           user_id=user_id))

    db.session.add(order)
    db.session.commit()
    return get_success_response('Order created successfully', data=order.get_summary(include_order_items=True),
                                status_code=200)
Exemplo n.º 11
0
    def change_cart_item(cls, cart_obj, product_item, is_added_to_cart):
        """
        Change the cart item

        - Add more existed product to cart.
        - Add new product to cart.
        - Update product item quantity in cart.

        @param is_added_to_cart: A flag to determine add to cart or not
        @param cart_obj: Shopping cart object
        @param product_item: Product item data
        @return: Return `True` if the process completed successfully.
        """
        try:
            cart_item_objs = OrderItem.objects.non_archived_only() \
                .filter(order=cart_obj, product=product_item['product'])
        except EmptyCartException as e:
            raise e

        is_duplicated_item = len(cart_item_objs) > 1
        is_one_item = len(cart_item_objs) == 1

        # Do not allow duplicate cart item.
        if is_duplicated_item:
            raise DuplicateCartItemException(
                'There are duplicate product item '
                'in the cart')

        if is_added_to_cart:
            if is_one_item:
                cart_item_objs.update(quantity=F('quantity') + 1)
            else:
                # There is no item in the cart. Create a new one.
                new_item_values = {
                    'order': cart_obj,
                    'product': Product.objects.get(pk=product_item['product']),
                    'quantity': 1
                }

                cart_item_obj = OrderItem(**new_item_values)
                cart_item_obj.save()

            return True
        else:
            # Update cart item quantity
            if is_one_item:
                updated_data = {'quantity': product_item.get('quantity', None)}

                UpdatingCartItemSerializer(data=updated_data).is_valid(
                    raise_exception=True)

                cart_item_objs.update(**updated_data)
                return True
            else:
                raise CartItemDoesNotExistException('Cart item not found')
Exemplo n.º 12
0
def order_add_var_item(request, pk, var_pk, restaurant_pk, menu_pk, **kwargs):
    product = Product.objects.get(pk=pk)
    variation = ProductVariation.objects.get(pk=var_pk)
    menu = Menu.objects.get(pk=menu_pk)
    restaurant = Restaurant.objects.get(pk=restaurant_pk)
    if request.user.is_authenticated:
        pass
        # TODO: Lógica para usuários autenticados

    try:
        order_slug = request.session["order_slug"]
    except KeyError:
        order = Order(restaurant=restaurant)

        order.save()
        request.session["order_slug"] = order_slug = order.slug

    order = Order.objects.get(slug=order_slug)
    if order.orderitem_set.all().filter(item=product,
                                        variation=variation).exists():

        item = OrderItem.objects.get(order=order,
                                     item=product,
                                     variation=variation)
        item.quantity = item.quantity + 1
        item.save()
        messages.info(
            request, f'{product.name} Já está no pedido. '
            f'<a href="/orders/cart/{order_slug}/" '
            f'class="alert-link">Ver pedido</a>.')

        return redirect(
            reverse('restaurant_menu',
                    kwargs={
                        'restaurant_slug': restaurant.slug,
                        'menu_slug': menu.slug
                    }))

    else:
        item = OrderItem(order=order,
                         item=product,
                         unity_price=variation.price,
                         variation=variation)
        item.save()

    messages.success(
        request, f'{item.item.name} adicionado ao pedido. '
        f'<a href="/orders/cart/{order_slug}/" '
        f'class="alert-link">Ver pedido</a>.')
    return redirect(
        reverse('restaurant_menu',
                kwargs={
                    'restaurant_slug': restaurant.slug,
                    'menu_slug': menu.slug
                }))
Exemplo n.º 13
0
    def create(self, validated_data):
        print('>>>', validated_data)
        chef = validated_data.get('chef')
        consumer = validated_data.get('consumer')
        meal = validated_data.get('meal')
        quantity = validated_data.get('quantity')

        item = OrderItem(consumer=consumer,
                         chef=chef,
                         meal=meal,
                         quantity=quantity)
        item.save()
        return item
Exemplo n.º 14
0
 def setUp(self):
     self.product = Product(product_name="Arduino",
                            product_image="",
                            product_prices=750,
                            product_overview="aeqweq")
     self.order = Order(first_name='N',
                        last_name='Zh',
                        email='*****@*****.**',
                        address='S',
                        city='Bishkek')
     self.order_item = OrderItem(order=self.order,
                                 product=self.product,
                                 price=100,
                                 count=10)
Exemplo n.º 15
0
 def test_get_total_cost_product_different_count(self):
     for item in range(10):
         product = Product(product_name=str(item),
                           product_image="",
                           product_prices=5 * item,
                           product_overview=str(item))
         product.save()
         order_item = OrderItem(order=self.order,
                                product=product,
                                price=product.product_prices,
                                count=item)
         order_item.save()
         #
     self.assertEqual(self.order.get_total_cost(), 1425)
Exemplo n.º 16
0
    def save(self, event, price, user, commit=True):
        from django.contrib.contenttypes.models import ContentType
        #
        booking = super(BookingForm, self).save(commit=False)

        booking.booked_by = user
        booking.event = event
        booking.price = price
        total_booked = 0
        open_order_list = Order.objects.open_order(user=user)
        if open_order_list:
            order = open_order_list[0]

            for item in order.orderitem_set.all():
                total_booked += item.content_object.quantity

        if not (event.pricing_set.all().filter(online_book=True)
                and not event.fully_booked):
            raise ValidationError(_('This event is fully booked'),
                                  code='Fully Booked')
            commit = False
        elif event.num_spaces < (booking.quantity + total_booked):
            places = booking.quantity + total_booked
            raise ValidationError(
                _('Not enough spaces for %(places)s people.'),
                code='No Space',
                params={'places': places},
            )
            commit = False

        if commit:
            booking.save()

            # Add to open order
            if not open_order_list:
                order = Order(ordered_by=user)

            order.save()

            order_item = OrderItem(
                order=order,
                description=event.__unicode__(),
                value=(price.value * booking.quantity),
                vat=price.vat,
                content_type=ContentType.objects.get_for_model(booking),
                object_id=booking.id)

            order_item.save()

        return booking
 def handle(self, *args, **kwargs):
     file_name = kwargs['file_name']
     with open(f'{file_name}.csv') as csv_file:
         reader = csv.DictReader(csv_file)
         for row in reader:
             try:
                 order_item = OrderItem(order_id=row['order_id'],
                                        product_name=row['product_name'],
                                        qty=row['qty'])
                 order_item.save()
             except Exception as e:
                 raise CommandError('OrderItem save fail')
     self.stdout.write(
         self.style.SUCCESS('%s.csv Data Feed Success!' % file_name))
Exemplo n.º 18
0
def save_order(stripe_response):

    # print("Fulfilling order")
    transaction_id = stripe_response.id
    user_id = stripe_response.metadata.user_id
    cart_id = stripe_response.metadata.cart_id

    # Fetch all record of cart
    try:
        cart_data = Cart.objects.get(id=cart_id)
    except Cart.DoesNotExist:
        cart_data = None

    if cart_data is not None:

        # Insert into orders table
        order = Order(user_id=user_id,
                      total=cart_data.total,
                      transaction_id=transaction_id)
        order.save()
        latest_order_id = Order.objects.latest('id')
        # Fetch all record of cart items
        try:
            cart_items = CartItem.objects.filter(cart_id=cart_data.id)
        except CartItem.DoesNotExist:
            cart_items = None

        if cart_items is not None:
            # Insert into order detail table
            for data in cart_items:
                product_info = Product.objects.get(id=data.product_id)
                order_item = OrderItem(order_id=latest_order_id.pk,
                                       product_id=data.product_id,
                                       quantity=data.quantity,
                                       product_price=product_info.price,
                                       product_total=data.product_total)
                order_item.save()

        # Removing the current cart and its item data
        cart_data.delete()
        cart_items.delete()

    return True
Exemplo n.º 19
0
 def post(self,request,pk=None,format=None):
     # print('Request data is ' + str(request.data))
     # o_parameters = {"table_no":request.data['tableno']}
     # r = requests.post('http://127.0.0.1:8000/orders/o/',data=o_parameters)
     print('aa')
     check_ob = Order.objects.filter(table_no=request.data['tableno']).count()
     if(check_ob <=0 ):
         new_order = Order(table_no=request.data['tableno'])
         new_order.save()
     order = Order.objects.get(table_no=request.data['tableno'])
     print('bb')
     print(order)
     check_oi = OrderItem.objects.filter(order=order).count()
     orderi = OrderItem(order=order,quantity=request.data['quantity'])
     orderi.save()
     food = FoodItem.objects.get(name=request.data['name'])
     print(orderi.fooditem)
     orderi.fooditem.add(food) 
     return Response('Success')
Exemplo n.º 20
0
def create_order_from_cart(**kwargs):
    logger.debug("creating order from Cart")
    user = kwargs['user']
    ship_mode = kwargs['ship_mode']
    cart = get_user_cart(user)
    total = 0
    if cart.coupon:
        total = cart.solded_price
    else:
        total = cart.amount
    total += ship_mode.price
    logger.info(f"create_order_from_cart : Total : {total}")
    #order = Order.objects.create(user=user, address=address, coupon=cart.coupon, amount=cart.amount, solded_price=cart.solded_price, quantity=cart.quantity, shipping_price=SHIPPING_PRICE, total=total)
    order_kwargs = {'coupon' : cart.coupon, 'amount' : cart.amount, 'solded_price' : cart.solded_price, 'quantity' : cart.quantity, 'shipping_price' : ship_mode.price, 'total' : total}
    order_kwargs.update(kwargs)
    order = Order.objects.create(**order_kwargs)
    OrderStatusHistory.objects.create(order=order, order_status=order.status, order_ref_id=order.id, changed_by=user)
    logger.debug("order instance created")
    items_queryset = get_user_cartitems(user)
    logger.debug("got cartitems queryset")
    batch_size = 10
    logger.debug("preparing orderitems from CartItems")
    orderitems = None
    product_update_list = items_queryset.values_list('product', 'product__quantity', 'quantity')
    try:
        orderitems = (OrderItem(order=order, product=item.product, quantity=item.quantity,promotion_price=item.promotion_price, unit_price=item.original_price,total_price=item.item_total_price) for item in items_queryset)
    except Exception as e:
        logger.error("error on preparing orderitems from CartItems")
        logger.exception(e)
    logger.debug("orderitems prepared from CartItems")

    if orderitems:
        while True:
            batch = list(islice(orderitems, batch_size))
            if not batch:
                break
            OrderItem.objects.bulk_create(batch, batch_size)
    for pk, available_quantity, quantity in product_update_list:
        ProductVariant.objects.filter(pk=pk).update(quantity=F('quantity') - quantity, is_active=(available_quantity > quantity))
        Product.objects.filter(variants__in=[pk]).update(quantity=F('quantity') - quantity)
    logger.debug("Order created from Cart")
    return order
Exemplo n.º 21
0
    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        item_data = validated_data.pop('item')
        order = super().create(validated_data)

        raw_item = []

        for item_data in item_data:
            items = OrderItem(
                order=order,
                product=item_data['product'],
                quantity=item_data['quantity'],
            )

            raw_item.append(items)

        OrderItem.objects.bulk_create(raw_item)
        order.sum_order = order.total_price
        order.save()
        return order
Exemplo n.º 22
0
def get_order_items(cartProducts):
    orderItems = []
    if cartProducts:
        for productID, quantity in cartProducts.items():

            product = Product.objects.filter(id=productID).first()

            if product:
                if product.discount_price != product.price:
                    discountedPrice = product.discount_price
                else:
                    discountedPrice = None

                orderItem = OrderItem(product=product,
                                      quantity=quantity,
                                      price=product.price,
                                      discountedPrice=discountedPrice)
                orderItems.append(orderItem)

    return orderItems
Exemplo n.º 23
0
 def post(self,request,pk=None,format=None):
     table_qs = Table.objects.filter(table_no = request.data['tableno'])
     table = list(table_qs)[0]
     # print(table)
     check_ob = Order.objects.filter(table_no=table).count()
     if(check_ob <=0 ):
         
         new_order = Order(table_no=table)
         new_order.save()
     
     order_qs = Order.objects.filter(table_no = table)
     order = list(order_qs)[0]
     print(order)
     food = FoodItem.objects.get(name=request.data['name'])
     print(food)
     orderi = OrderItem(order=order,fooditem=food,quantity=request.data['quantity'])
     
     orderi.save()
     
     return Response('Success')
Exemplo n.º 24
0
def seed_orders():
    orders_count = db.session.query(func.count(Order.id)).scalar()
    orders_to_seed = 31
    addresses = db.session.query(Address).options(load_only('id',
                                                            'user_id')).all()
    products = db.session.query(Product).options(
        load_only('id', 'name', 'slug', 'price')).all()

    for i in range(orders_count, orders_to_seed):
        address = random.choice(addresses)
        tracking_number = fake.uuid4()
        order_status = fake.random_int(min=0, max=2)
        user_id = address.user_id
        order = Order(tracking_number=tracking_number,
                      order_status=order_status,
                      address_id=address.id,
                      user_id=user_id)

        db.session.add(order)
        '''
        this is to save the order now, so I can have the id to be used in order items
        or the other way is to comment flush(), order_id=order.id, and session.add(oi).
        Instead use order.order_items.append(oi); See below. Both ways lead to the same result
        '''

        db.session.flush()

        for i in range(fake.random_int(min=1, max=6)):
            product = random.choice(products)
            oi = OrderItem(name=product.name,
                           slug=product.slug,
                           price=product.price,
                           order_id=order.id,
                           product_id=product.id,
                           user_id=user_id,
                           quantity=fake.random_int(min=1, max=5))
            db.session.add(oi)

            # order.order_items.append(oi)

        db.session.commit()
Exemplo n.º 25
0
 def form_valid(self, form):
     cart = Cart(self.request)
     if len(cart) == 0:
         return redirect('cart:cart_details')
     order = form.save(commit=False)
     order.user = self.request.user
     order.total_price = cart.get_total_price()
     order.save()
     products = Product.objects.filter(id__in=cart.cart.keys())
     orderitems = []
     for i in products:
         q = cart.cart[str(i.id)]['quantity']
         orderitems.append(
             OrderItem(order=order,
                       product=i,
                       quantity=q,
                       total=q * i.price))
     OrderItem.objects.bulk_create(orderitems)
     cart.clear()
     messages.success(self.request, 'Your order is successfully placed.')
     return redirect('store:product_list')
Exemplo n.º 26
0
def save_cart_as_order(cart):
    address = None
    if cart.get('details').get('delivery_address'):
        address = Address(
        street_one = cart.get('details').get('delivery_address').get('street_one'),
        street_two = cart.get('details').get('delivery_address').get('street_two'),
        city = cart.get('details').get('delivery_address').get('city'),
        state = cart.get('details').get('delivery_address').get('state'),
        zipcode = cart.get('details').get('delivery_address').get('zipcode'),
        )
        address.save()
    customer = Customer(
    first_name = cart.get('details').get('contact_info').get('first_name'),
    last_name = cart.get('details').get('contact_info').get('last_name'),
    email = cart.get('details').get('contact_info').get('email'),
    phone_number = cart.get('details').get('contact_info').get('phone'),
    address = address,
    )
    customer.save()
    order = Order(
    ref_code = create_ref_code(),
    customer = customer,
    ordered_date = timezone.now(),
    pickup = cart.get('details').get('pickup'),
    note = cart.get('details').get('note'),
    )
    order.save()
    id_list = cart.get('details').get('item_id_list')
    for id in id_list:
        item = Item.objects.get(id=id)
        order_item = OrderItem(
        item = item,
        quantity = cart.get(str(id)).get('quantity'),
        note = cart.get(str(id)).get('note'),
        order = order,
        )
        order_item.save()
    return order
Exemplo n.º 27
0
    def save(self, user, value, commit=True):
        from django.contrib.contenttypes.models import ContentType

        pricing = Pricing()

        pricing.value = value

        pricing.save()

        donation = super(PaymentForm, self).save(commit=False)

        donation.price = pricing

        donation.booked_by = user
        open_order_list = Order.objects.open_order(user=user)
        if open_order_list:
            order = open_order_list[0]

        if commit:
            donation.save()

            # Add to open order
            if not open_order_list:
                order = Order(ordered_by=user)

            order.save()

            order_item = OrderItem(
                order=order,
                description=donation.__unicode__(),
                value=(pricing.value * donation.quantity),
                vat=donation.price.vat,
                content_type=ContentType.objects.get_for_model(donation),
                object_id=donation.id)

            order_item.save()

        return pricing
Exemplo n.º 28
0
 def post(self, request, *args, **kwargs):
     cart = Cart(request.session)
     serializer = OrderSerializer(data=request.data)
     if serializer.is_valid():
         order = serializer.save()
         for item in cart.items:
             instance = OrderItem(
                 order=order,
                 product=item.product,
                 price=item.price,
                 quantity=item.quantity
             )
             instance.save()
         cart.clear()
         UserOrderNotification.apply_async((order.pk,), countdown=10)
         AdminOrderNotification.apply_async((order.pk,), countdown=10)
         return Response(
             status=status.HTTP_201_CREATED
         )
     else:
         return Response(
             status=status.HTTP_422_UNPROCESSABLE_ENTITY
         )
def checkout(request):

    #assume credit card not recorded for customer until proven otherwise
    cc_reg = "btn btn-sm btn-success disabled"
    #get user object
    user = get_object_or_404(User, username=request.user)

    #set cost and amount variables
    global total_cost
    total_cost = 0
    total_amount = 0
    delivery_cost = 0

    #if basket present
    if 'cart' in request.session:

        #Select all records from Cart_Item for current id
        items_in_cart = CartItem.objects.filter(
            cart_id=request.session['cart'])

        #for each cart item, use the stored product_id to retrive product details from product table
        products = Product.objects.filter(
            id__in=[item.product_id for item in items_in_cart])

        #getting amount ordered of each product so can auto-fill checkout list
        for item in products:
            cartItem_amount = get_object_or_404(
                CartItem, product_id=item.id, cart_id=request.session['cart'])
            item.amount = cartItem_amount.amount
            item.cost = item.amount * item.price
            total_cost = total_cost + item.cost
            total_amount = total_amount + item.amount

        #add £2 deliver charge per item
        delivery_cost = total_amount * 2
        total_cost = total_cost + delivery_cost
        pence_cost = int(total_cost * 100)

        if items_in_cart.exists():

            #Check that credit card and address have been logged before allowing checkout (and enabling purchase button)
            if user.stripe_custID == "None":
                messages.error(
                    request,
                    "Please register a valid credit card in your profile")

            elif user.address_line1 == "None" or user.address_line2 == "None" or user.county == "None" or user.postcode == "None":
                messages.error(
                    request,
                    "Please register a delivery address in your profile")

            else:
                #enable purchase button
                cc_reg = "btn btn-sm btn-success"

                #if request method is POST some is trying to buy product
                if 'purchase' in request.POST:
                    #set cost and amount variables to check if checkout amounts needs to be refreshed at checkout.
                    #
                    #On a multi-user system for a company with relatively small stock levels, between the customer
                    #putting item(s) in cart and getting to checkout, their is the real risk that another customer purchase
                    #could pull stock levels down to a level where the current customers order can't be met with existing
                    #stock. This would then require extra time to restock, so the company would prefer the customer call them
                    #so they can speak through the options.
                    total_cost_refresh = 0
                    total_amount_refresh = 0
                    delivery_cost_refresh = 0

                    #Go through and check stock levels are still OK pre purchase
                    #i.e has another customer made a purchase and reduced available stock levels below what can be fulfilled?
                    refresh_checkout = False

                    #This is a
                    cart_items_to_refresh = []

                    for item in products:
                        #Need to get current stock level
                        current_product = get_object_or_404(Product,
                                                            id=item.id)
                        if item.amount > current_product.stock_level:
                            refresh_checkout = True
                            #Get the object that hold this amount value
                            cartItem = get_object_or_404(
                                CartItem,
                                product_id=item.id,
                                cart_id=request.session['cart'])

                            #set it to the stock leve value (so that 'refresh_checkout' won't be true 2nd time around)
                            cartItem.amount = current_product.stock_level
                            #save it to database
                            cartItem.save()
                            #Also change value of item being iterated over
                            item.amount = current_product.stock_level

                            #tracking the items in order that need to be refreshed
                            cart_items_to_refresh.append(current_product)

                        item.cost = item.amount * item.price
                        total_cost_refresh = total_cost_refresh + (
                            item.amount * item.price)
                        total_amount_refresh = total_amount_refresh + item.amount

                    #£2 deliver charge per item
                    delivery_cost_refresh = total_amount_refresh * 2
                    total_cost_refresh = total_cost_refresh + delivery_cost_refresh

                    if refresh_checkout == True:
                        messages.error(
                            request,
                            "Other recent customer purchases mean we can no longer currently meet you order with our existing stock, your order has been updated to reflect current stock levels. Please contact us to discuss acquiring the additional items."
                        )

                        #Need to amend cartItem to store new amount value, so that if purchase not made
                        #but cart stored, the item is not deleted (on signing back in) unless
                        #stock levels has actually gone below the amended amount
                        for item in cart_items_to_refresh:
                            current_product = get_object_or_404(Product,
                                                                id=item.id)
                            cart_item = get_object_or_404(
                                CartItem,
                                product_id=item.id,
                                cart_id=request.session['cart'])
                            #if the stock level is 0, remove from cart, no point in having it (would only confuse customer)
                            if current_product.stock_level == 0:
                                cart_item.delete()
                            else:
                                cart_item.amount = current_product.stock_level
                                cart_item.save()

                        #disable the purchase button if refrsh has meant the order is now for nothing (to prevent processing errors)
                        if total_amount_refresh == 0:
                            cc_reg = "btn btn-sm btn-success disabled"

                        return render(
                            request, "checkout/checkout.html", {
                                "user": user,
                                "products": products,
                                "cc_reg": cc_reg,
                                "total_cost": total_cost_refresh,
                                "total_amount": total_amount_refresh,
                                "delivery_cost": delivery_cost_refresh
                            })

                    try:
                        #Try to make payment!
                        charge = stripe.Charge.create(
                            amount=pence_cost,
                            currency="gbp",
                            customer=user.stripe_custID,
                        )
                        messages.success(request, "Payment Successful")

                        #Create order entries in database
                        customer = get_object_or_404(User,
                                                     username=request.user)
                        new_order = Order(address_line1=user.address_line1,
                                          address_line2=user.address_line2,
                                          county=user.county,
                                          postcode=user.postcode,
                                          total=(pence_cost / 100),
                                          customer_id=customer.id)
                        new_order.save()

                        for item in products:
                            new_orderItem = OrderItem(order_id=new_order.id,
                                                      product=item,
                                                      quantity=item.amount,
                                                      price=item.price)
                            new_orderItem.save()

                            #Reduce the stock level
                            #The amount won't be bigger than current stock levels due to pre-purchase stock
                            #level checks (so no need to check here)
                            current_product = get_object_or_404(Product,
                                                                id=item.id)
                            current_product.stock_level = current_product.stock_level - item.amount
                            current_product.save()

                        #"When Django deletes an object, by default it emulates the behavior of the SQL constraint ON DELETE
                        #CASCADE – in other words, any objects which had foreign keys pointing at the object to be deleted
                        #will be deleted along with it". So this command should remove the cart and associated cart items
                        #from the database.
                        Cart.objects.filter(
                            id=request.session['cart']).delete()
                        del request.session['cart']

                        #If the cart was from a stored version, remove it
                        if user.saved_cart_id != 0:
                            user.saved_cart_id = 0
                            user.save()

                        #Send user to orders page after successful purchase
                        return redirect("orders")

                    #Gracefully catch error, inform customer of issue
                    except stripe.error.CardError as e:
                        body = e.json_body
                        err = body.get('error', {})
                        messages.error(request, err.get('message'))
                else:
                    #this is enabling purchase button on initial page load (rather than when purchase has been pressed)
                    #when credit card and address have been stored in database.
                    cc_reg = "btn btn-sm btn-success"

            return render(
                request, "checkout/checkout.html", {
                    "user": user,
                    "products": products,
                    "cc_reg": cc_reg,
                    "total_cost": total_cost,
                    "total_amount": total_amount,
                    "delivery_cost": delivery_cost
                })

        #empty cart, let use rknow
        else:
            messages.error(
                request,
                "Nothing in your cart, please add an item before attempting purchase"
            )
            return render(
                request, "checkout/checkout.html", {
                    "cc_reg": cc_reg,
                    "total_cost": total_cost,
                    "total_amount": total_amount,
                    "delivery_cost": delivery_cost
                })

    else:
        messages.error(
            request,
            "You don't have a cart yet, please create one by adding an item before attempting purchase"
        )
        return render(
            request, "checkout/checkout.html", {
                "cc_reg": cc_reg,
                "total_cost": total_cost,
                "total_amount": total_amount,
                "delivery_cost": delivery_cost
            })
Exemplo n.º 30
0
def populate():
    """Populate the database with activity simulating last 365 days."""
    # Start by dropping all the previous data
    main_tables = (Expense, Customer, Order, Item, StatusShift, Timetable,
                   User)
    for table in main_tables:
        table.objects.all().delete()

    # Create a default user name
    user = User.objects.create_user(username='******', password='******')

    # random numbers upper bound
    u = len(WORDS) - 1

    # Create some customers
    for name in NAMES:
        Customer.objects.create(
            name=name,
            address=multiword(),
            city=multiword(),
            phone=randint(20000, 2000000),
            email='{}@{}.com'.format(multiword(1), multiword(1)),
            cp=randint(1000, 99000),
            CIF=str(randint(10000, 99000)),
            notes=multiword(5),
            provider=randint(0, 1),
        )

    # Create some items
    for _ in range(10):
        Item.objects.create(
            name=WORDS[randint(0, u)],
            item_type=randint(0, 18),
            foreing=randint(0, 1),
            price=randint(10, 150),
            fabrics=randint(1, 3),
            stocked=300,
        )

    # Create daily activity for the last n days
    days = (date.today() - date(date.today().year, 1, 1)).days
    for n in range(days):
        print('.', end='')
        curr_datetime = timezone.now() - timedelta(days=days - n)
        order = Order.objects.create(
            inbox_date=curr_datetime,
            user=user,
            customer=choice(Customer.objects.filter(provider=False)),
            ref_name=multiword(),
            delivery=curr_datetime + timedelta(days=randint(7, 30)),
            status=randint(1, 6),
            waist=randint(60, 70),
            chest=randint(90, 120),
            hip=randint(90, 120),
            others=multiword(5),
        )

        for i in range(randint(2, 4)):
            item = OrderItem(
                element=choice(Item.objects.all()),
                reference=order,
                qty=randint(1, 3),
                price=randint(10, 100),
                stock=randint(0, 1),
            )
            item.clean()
            if randint(1, 15) > 1:
                item.crop = timedelta(seconds=1000 * randint(1, 3))
                item.sewing = timedelta(seconds=1000 * randint(1, 3))
                item.iron = timedelta(seconds=1000 * randint(1, 3))
            item.save()

        # Add a comment
        if randint(1, 15) > 1:
            Comment.objects.create(creation=curr_datetime,
                                   user=user,
                                   reference=order,
                                   comment=multiword(10))

        # Sell something
        active_orders = Order.live.all()
        sell_it = randint(1, 20) > 1  # p = 19/20
        if sell_it and active_orders.exists():
            order = active_orders.first()
            pay_method = choice(['C', 'T', 'V'])
            CashFlowIO.objects.create(
                creation=curr_datetime,
                order=order,
                amount=order.pending,
                pay_method=pay_method,
            )
            if order.status != '7':
                order.deliver()  # Creates status shift

            # Set status to 9 (invoiced)
            order.status = '9'
            order.save()
            i = Invoice(reference=order,
                        issued_on=curr_datetime,
                        amount=order.total,
                        pay_method=pay_method)
            i.save(kill=True)

        # Update Item health
        [i.save() for i in Item.objects.all()]

        # Expend some money somewhere
        providers = Customer.objects.filter(provider=True)
        expense = Expense.objects.create(
            creation=curr_datetime,
            issuer=choice(providers),
            invoice_no=choice(WORDS),
            issued_on=curr_datetime,
            concept=multiword(2),
            amount=randint(180, 250),
            pay_method=choice(['C', 'T', 'V']),
            notes=multiword(5),
        )
        if randint(1, 15) > 1:
            expense.kill()

    # Deliver a couple of orders without selling
    [order.deliver() for order in Order.live.all()[:3]]