コード例 #1
0
ファイル: api.py プロジェクト: degacth/natshop
    def post(self, request):
        data = request.data
        customer = request.customer
        if not customer: return self._order_error("Отсутствуют данные пользователя")

        cart = self._get_cart()
        if not len(cart): return self._order_error("Отсутствуют данные выбранных товаров")

        order = Order(comment=data['comment'], customer=customer)
        order.save()

        map(lambda item: OrderItem.objects.create(**{
            'title': item['title'],
            'comment': item.get('comment', ""),
            'count': item['count'],
            'price': item['price'],
            'product_url': item['url'],
            'order': order,
        }), cart)

        self._clear_cart()

        return Response({
            '_success': "Заказ сделан успешно"
        }, status=status.HTTP_201_CREATED)
コード例 #2
0
ファイル: checkout.py プロジェクト: mwd1234/intex2_fomo
def process_request(request, cart: cmod.Order = None):
    if request.user.is_authenticated:
        pass
    else:
        return HttpResponseRedirect('/account/login/')

    # Grab the cart
    cart = cmod.Order.objects.get(user=request.user, status='cart')
    cart.recalculate()

    cartTotal = cart.total_price
    cartTotal = round(cartTotal, 2)
    form = checkoutForm(request, cart=cart)
    form.submit_text = None

    cartTotal = '{:,.2f}'.format(cartTotal)

    myCatalogList = cmod.Category.objects.all()

    if form.is_valid():
        form.commit()
        return HttpResponseRedirect('/catalog/thanks')

    # render the format
    context = {
        'form': form,
        'categories': myCatalogList,
        'totalPrice': cartTotal,
        'cart': cart,
    }
    return request.dmp.render('checkout.html', context)
コード例 #3
0
ファイル: views.py プロジェクト: guiqi134/take-out-website
def get_cart(request):
    message = ''

    if request.POST:
        # 下单食物数量减少,创建order,购物车清空
        cart_id = request.session.get('CART-ID')

        # 下单的食物count数量减少
        items = models.Item.objects.filter(cart_id=cart_id).values(
            'quantity', 'unit_price', 'object_id')
        total_price = 0
        food_list = []
        rest_set = set()  # check if there more than one restaurant
        for item in items:
            food_id = item['object_id']
            total_price += item['quantity'] * item['unit_price']
            food = Food.objects.get(food_id=food_id)
            rest_set.add(food.RName)

        if len(rest_set) != 1:
            message = '商家必须相同'
        else:
            for item in items:
                food_id = item['object_id']
                food = Food.objects.get(food_id=food_id)
                food.count -= 1
                food_list.append(food)
                food.save()

            # 成功下单的cart
            cart = models.Cart.objects.get(id=cart_id)
            cart.checked_out = True
            cart.save()

            # 创建order
            new_order = Order()
            customer_id = Customer.objects.get(
                AName=request.session['user_name'])
            new_order.total_price = total_price
            new_order.save()
            new_order.foods.add(*food_list)
            new_order.restaurant_id = list(rest_set)[0]
            new_order.customer_id = customer_id
            new_order.address = Customer.objects.filter(
                AName=request.session['user_name']).values(
                    'address')[0]['address']
            new_order.save()

            # 购物车清空
            request.session['CART-ID'] = False
            new_cart = Cart(request)

            return redirect('/index/customer_order/')

    context = {'cart': Cart(request), 'message': message}

    return render(request, 'cart.html', context=context)
コード例 #4
0
def process_request(request, orderItem: cmod.OrderItem, order: cmod.Order):
    orderItem.status = 'deleted'
    orderItem.save()
    order.recalculate()

    if order.num_items() < 1:
        return HttpResponseRedirect('/catalog/')
    else:
        return HttpResponseRedirect('/catalog/cart/' + str(order.id))
コード例 #5
0
def process_request(request, order: cmod.Order):

    order.recalculate()

    form = CheckOut(request, order=order)
    form.submit_text = None
    if form.is_valid():
        #form.commit()
        return HttpResponseRedirect('/catalog/thankyou/')

    context = {
        'form': form,
        'order': order,
    }
    return request.dmp.render('checkout.html', context)
コード例 #6
0
ファイル: views.py プロジェクト: tmars/DS_CW
def reserve_car(car_id, start_date, end_date):
    try:
        car = Car.objects.get(pk=car_id)
    except:
        return False
    
    start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
    end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
    
    if not car.is_free_for(start_date, end_date):
        return False
    
    order = Order()
    order.reserve(car=car, start_date=start_date, end_date=end_date)
    order.save()
    return [order.id, order.sum]
コード例 #7
0
ファイル: receipt.py プロジェクト: yaejinlee93/IS413-FOMO
def process_request(request, order: cmod.Order = None):
    person = None
    if order is None:
        order = cmod.Order.objects.filter(user=request.user,
                                          status='sold').order_by('-id')[0]
        if order is None:
            return HttpResponseRedirect('/catalog/cart/')
    else:
        person = order.user
    if order.user != request.user:
        if not request.user.is_staff:
            return HttpResponseRedirect('/catalog/cart/')
    if order.order_date is not None:
        order.order_date = '{:%m/%d/%Y}'.format(order.order_date)
    cart = cmod.OrderItem.objects.filter(
        order=order, status='active').exclude(description='TaxAmount')
    context = {
        'order': order,
        'cart': cart,
    }

    #email the receipt
    # if send == 'yes':
    #     email(request,order)

    return request.dmp.render('receipt.html', context)
コード例 #8
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     categories = Category.get_categories_with_dishes()
     order = Order.get_current_temp_order(self.request.session)
     context['current_category'] = self.category
     context['categories'] = categories
     context['order'] = order
     return context
コード例 #9
0
    def get_queryset(self):
        self.category = get_object_or_404(Category, slug=self.kwargs['slug'])
        order = Order.get_current_temp_order(self.request.session)

        dishes = Dish.objects.filter(category=self.category, is_draft=False)
        if order:
            for dish in dishes:
                dish_in_order = order.order_dish.filter(dish=dish).first()
                if dish_in_order:
                    dish.count = dish_in_order.count
        return dishes
コード例 #10
0
ファイル: thanks.py プロジェクト: andersonsmike4/IS_413
def process_request(request, cart:cmod.Order):
    tax_product = cmod.Product.objects.get(id=74)
    items = cart.active_items().exclude(description=tax_product.name)
    tax = cart.items.get(description=tax_product.name)
    print('>>>>>>>>>>>.cart yay i have items', items)
    context = {
        # sent to index.html:
        'cart': cart,
        'items': items,
        'tax': tax,
    }
    return request.dmp.render('thanks.html', context)
コード例 #11
0
def run(request):
    categories = Category.get_categories_with_dishes()
    dishes = Dish.objects.filter(is_draft=False)

    order = Order.get_current_temp_order(request.session)

    if order:
        for dish in dishes:
            dish_in_order = order.order_dish.filter(dish=dish).first()
            if dish_in_order:
                dish.count = dish_in_order.count

    return render(request,
                  'catalog/index.html',
                  context={
                      'categories': categories,
                      'dishes': dishes,
                      'order': order
                  })
コード例 #12
0
def process_request(request, order: cmod.Order = None):
    if order is not None and order.num_items() > 0 and order.status == "cart":
        HttpResponseRedirect('/homepage/')
        items = order.active_items(False)
        tax = order.get_item(cmod.Product.objects.get(name="Sales Tax"))
        for i in items:
            i.recalculate()
        order.recalculate()

        if order.num_items() < 2:
            HttpResponseRedirect('/catalog/')

        context = {'items': items, 'order': order, 'tax': tax}

        return request.dmp.render('cart.html', context)
    else:
        return HttpResponseRedirect('/catalog/')
コード例 #13
0
def make_order_view(request):
    try:
        cart_id = request.session['cart_id']
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id
        cart = Cart.objects.get(id=cart_id)
    comp_id = 0
    for i in cart.items.all():
        comp_id = i.product.owner.id
        break
    form = OrderForm(request.POST or None)
    if form.is_valid():
        name = form.cleaned_data['name']
        phone = form.cleaned_data['phone']
        comments = form.cleaned_data['comments']
        new_order = Order()
        new_order.user = request.user
        new_order.owner = Company.objects.get(id=comp_id)
        new_order.save()
        new_order.items.add(cart)
        new_order.name = name
        new_order.phone = phone
        new_order.comments = comments
        new_order.total = cart.cart_total
        new_order.save()
        slug = slugify(
            translit(unicode('заказ' + str(new_order.id)), reversed=True))
        new_order.slug = slug
        new_order.save()
        path = 'media/files/' + new_order.slug + '.xlsx'
        new_order.path = path
        new_order.save()
        del request.session['cart_id']
        del request.session['total']
        return HttpResponseRedirect(reverse('thanks'))
コード例 #14
0
def BasketResidentConvert(request, pk):
    product = Product.objects.all()
    instance = get_object_or_404(Resident, pk=pk)
    order_list = BasketResident.objects.filter(user_basket=instance)
    verifpoint = request.POST.get('verifpoint')
    date = datetime.date.today()
    start_week = date - datetime.timedelta(date.weekday())
    end_week = start_week + datetime.timedelta(7)
    family = Resident.objects.filter(badge=instance.badge)
    pklist = []
    for f in family:
        pklist.append(f.id)
    entries = Order.objects.filter(date__range=[start_week, end_week],
                                   order_user__in=pklist)
    point = 0

    for p in entries:
        point += p.points
    pts = 0
    can_save = True
    error = []
    if not BasketResident.objects.filter(user_basket=instance).exists():
        error.append("panier vide")
        can_save = False
    else:
        for p in order_list:
            pts += p.product.prod_limit * p.qty
            if p.qty > p.product.prod_stock:
                error.append("Stock insuffisant de : " + p.product.prod_name +
                             " - Stock restant :" + str(p.product.prod_stock))
                p.save()
                can_save = False

        if verifpoint:
            instance = get_object_or_404(Resident, pk=pk)
            family = Resident.objects.filter(badge=instance.badge)
            familynumber = family.count()
            user_points = get_object_or_404(
                LimitFamily, compo_family=str(familynumber)).point_by_week
            restant = user_points - point
            if pts > restant:
                error.append("limite de point dépassé, point restant :" +
                             str(restant))
                can_save = False
        else:
            pts = 0

    if can_save:

        #for p in order_list :

        id = Order.objects.latest('id')
        title = "AMC_Shop_" + datetime.datetime.now().strftime(
            "%d%m%Y") + "_" + str((id.id + 1))
        instance_order = Order(order_user=instance, title=title, points=pts)
        instance_order.save()
        for p in order_list:
            instance_item = OrderItem(product=p.product,
                                      order=instance_order,
                                      qty=p.qty)
            instance_item.save()
            p.delete()
    responseData = {
        'error': error,
        'verifpoint': verifpoint,
        #'entries':list(entries.values()),
        'point': point,
    }
    return JsonResponse(responseData)