コード例 #1
0
def complete_order(order, username):
    order_number = Order.objects.aggregate(Max('order_number'))
    if order_number['order_number__max'] == None:
        order_number = 1
    else:
        order_number = order_number['order_number__max'] + 1
    for item in order:
        extras = clean_extras_string(item['extras'])
        item_id = int(item['itemId'])
        item_type = item['itemType'].split(' ')[1]
        if item_type == 'Pizza':
            content_type = pizza_type
        if item_type == 'Subs':
            content_type = sub_type
        if item_type == 'Pasta':
            content_type = pasta_type
        if item_type == 'Salad':
            content_type = salad_type
        if item_type == 'Platter':
            content_type = platter_type
        order_item = Order(
            order_number=order_number,
            username=username,
            object_id=item_id,
            content_type=content_type,
            extras=extras,
            completed=False
            )
        order_item.save()
    return order_number
コード例 #2
0
 def post(self, request):
     if self.request.user.is_authenticated(
     ) and self.request.user.activation:
         order = Order()
         #order.id = generate_order_id(16)
         self.order_id += 1
         order.id = str(self.order_id)
         while Order.objects.filter(id=order.id):
             self.order_id += 1
             order.id = str(self.order_id)
             #order.id = generate_order_id(16)
         order.user = self.request.user
         for item in self.request.POST:
             for i in range(8):
                 if Goods.objects.filter(id='0' * i + str(item)):
                     order.goods = Goods.objects.get(id='0' * i + str(item))
                     if order.goods.sale_percentage is not None:
                         order.sale_percentage = order.goods.sale_percentage
                     break
         order.state = 'pending'
         order.save()
         goods_items = Goods.objects.all()
         return render(request, "success.html", locals())
     elif self.request.user.is_authenticated():
         send_register_email(self.request.user.username, "register")
         return render(request, "goods.html", locals())
     else:
         return HttpResponseRedirect("/login/")
コード例 #3
0
    def test_failure_order_additional_validation(self):
        """
        Tests if HTTP304 when order additional validation signal raises
        ValidationError exception.
        """
        def custom_validation_listener(sender=None,
                                       request=None,
                                       order=None,
                                       backend=None,
                                       **kwargs):
            raise ValidationError("BOOM!")

        suid = 'test-order_additional_validation'
        signals.order_additional_validation.connect(custom_validation_listener,
                                                    dispatch_uid=suid)

        order = Order(name='Test order custom validation',
                      total=100,
                      currency='PLN')
        order.save()
        try:
            url = reverse('getpaid:new-payment', kwargs={'currency': 'PLN'})
            data = {'order': order.pk, 'backend': 'getpaid.backends.payu'}
            response = self.client.post(url, data)
            self.assertEqual(response.status_code, 403)
        finally:
            signals.order_additional_validation.disconnect(dispatch_uid=suid)
コード例 #4
0
ファイル: utils.py プロジェクト: gridl/qexx
def create_new_order(checkout_form):
    """
    Создает новый заказ, используя информацию о форме чекаута, корзине и пользователе
    :param checkout_form:
    :param cart:
    :param user:
    :return:
    """
    data = checkout_form.cleaned_data
    cart_summary = checkout_form.cart_summary

    shipping_method = methods[data['shipment']](cart=checkout_form.cart)
    payment_method = gateways[data['payment']]()
    order = Order(cart=checkout_form.cart,
                  user=checkout_form.user,
                  shipping_method=data['shipment'],
                  payment_method=data['payment'],
                  order_status=shipping_method.order_status,
                  payment_status=payment_method.payment_status,
                  shipping_price=cart_summary['shipping_price'],
                  shipping_address=data.get('address', ''),
                  phone=data.get('phone', ''),
                  email=data['email'],
                  contact_person=data['first_name'] + ' ' + data['last_name'],
                  discount=cart_summary['discount'])
    order.save()

    # Сформировать и отправить письмо с заказом
    send_new_order_email(data['email'], order)

    # ToDo Письмо администраторам

    return order
コード例 #5
0
ファイル: cron.py プロジェクト: HackBil/jeudizza
    def do(self):
        last_order = Order.objects.all().order_by('pk').last()
        last_order.open = False
        last_order.save()

        o = Order(date=next_thursday())
        o.save()
コード例 #6
0
ファイル: booking.py プロジェクト: cs98jrb/Trinity
    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
コード例 #7
0
    def test_payment_failed_flow(self):
        Payment = apps.get_model('getpaid', 'Payment')
        order = Order(name='Test PLN order', total='20.00', currency='PLN')
        order.save()
        payment = Payment(pk=23, order=order, amount=order.total, currency=order.currency,
                          backend='getpaid.backends.payu_rest')
        payment.save(force_insert=True)

        confirm_url = "http://localhost" + reverse('getpaid:payu_rest:confirm')

        # Fake PayU pings on confirmation URL
        # PENDING
        data_1 = b"""{"order":{"orderId":"6N73GWVD9P180712GUEST000P01","extOrderId":"23","orderCreateDate":"2018-07-12T14:55:18.209+02:00","notifyUrl":"http://getpaid.requestcatcher.com/","customerIp":"127.0.0.1","merchantPosId":"123456","description":"Test Payment","currencyCode":"PLN","totalAmount":"2000","status":"PENDING","products":[{"name":"Order #123456 from example.com","unitPrice":"2000","quantity":"1"}]},"properties":[{"name":"PAYMENT_ID","value":"73543299"}]}"""
        with mock.patch("getpaid.backends.payu_rest.views.get_request_body", return_value=data_1):
            self.client.post(confirm_url,
                             data={},
                             **{
                                 "HTTP_OPENPAYU_SIGNATURE": "sender=checkout;signature=f5482f0bca32c3094f6840637ae0c52f;algorithm=MD5;content=DOCUMENT"
                             })
            payment.refresh_from_db()
            assert payment.status == 'in_progress'

        # FAILED
        data_2 = b"""{"order":{"orderId":"6N73GWVD9P180712GUEST000P01","extOrderId":"23","orderCreateDate":"2018-07-12T14:55:18.209+02:00","notifyUrl":"http://getpaid.requestcatcher.com/","customerIp":"127.0.0.1","merchantPosId":"123456","description":"Test Payment","currencyCode":"PLN","totalAmount":"2000","status":"CANCELED","products":[{"name":"Order #123456 from example.com","unitPrice":"2000","quantity":"1"}]},"properties":[{"name":"PAYMENT_ID","value":"73543299"}]}"""
        with mock.patch("getpaid.backends.payu_rest.views.get_request_body", return_value=data_2):
            self.client.post(confirm_url,
                             data={},
                             **{
                                 "HTTP_OPENPAYU_SIGNATURE": "sender=checkout;signature=c69bc143125a7423e5fdfa6714db9753;algorithm=MD5;content=DOCUMENT"
                             })
            payment.refresh_from_db()
            assert payment.status == 'cancelled'
コード例 #8
0
ファイル: test_models.py プロジェクト: gello94/buyit
    def test_order_model(self):
        # create a user
        user = User.objects.create(username='******')

        # Create an order
        order = Order(full_name='name',
                      email_address='*****@*****.**',
                      phone_number='0000',
                      town_or_city='city',
                      street_address1='street address 1',
                      street_address2='street address 2',
                      country='country',
                      county='county',
                      postcode='postcode',
                      order_status='Order Received',
                      date='2019-10-21')

        order.user_id = user.id
        order.save()

        # check to see that the review summary equal the saved review value
        self.assertEqual(order.full_name, "name")
        self.assertEqual(order.email_address, '*****@*****.**')
        self.assertEqual(order.phone_number, '0000')
        self.assertEqual(order.town_or_city, "city")
        self.assertEqual(order.street_address1, 'street address 1')
        self.assertEqual(order.street_address2, 'street address 2')
        self.assertEqual(order.country, "country")
        self.assertEqual(order.county, 'county')
        self.assertEqual(order.postcode, 'postcode')
        self.assertEqual(order.order_status, 'Order Received')
        self.assertEqual(order.date, '2019-10-21')
        ''' Test order as string'''
        self.assertEqual('1-2019-10-21-name', str(order))
コード例 #9
0
ファイル: views.py プロジェクト: Si1veR123/tesco-orderer
def add_slot(r):
    if r.method != "POST":
        raise Http404

    for val in r.POST:
        if not val:
            return redirect("/")

    orders = Order.objects.filter(creator=r.user.id)

    if len(orders) > 1:
        return redirect("/?error=max")

    min_date = r.POST["min-date"]
    max_date = r.POST["max-date"]
    min_time = r.POST["min-time"]
    max_time = r.POST["max-time"]

    valid = validate_date_time(min_date, max_date, min_time, max_time)
    if valid is not True:
        return redirect("/?error=" + valid)

    order = Order(min_date=min_date,
                  max_date=max_date,
                  min_time=min_time,
                  max_time=max_time,
                  creator=r.user)
    order.save()

    return redirect("/")
コード例 #10
0
ファイル: utils.py プロジェクト: juntatalor/qexx
def create_new_order(checkout_form):
    """
    Создает новый заказ, используя информацию о форме чекаута, корзине и пользователе
    :param checkout_form:
    :param cart:
    :param user:
    :return:
    """
    data = checkout_form.cleaned_data
    cart_summary = checkout_form.cart_summary

    shipping_method = methods[data['shipment']](cart=checkout_form.cart)
    payment_method = gateways[data['payment']]()
    order = Order(cart=checkout_form.cart,
                  user=checkout_form.user,
                  shipping_method=data['shipment'],
                  payment_method=data['payment'],
                  order_status=shipping_method.order_status,
                  payment_status=payment_method.payment_status,
                  shipping_price=cart_summary['shipping_price'],
                  shipping_address=data.get('address', ''),
                  phone=data.get('phone', ''),
                  email=data['email'],
                  contact_person=data['first_name'] + ' ' + data['last_name'],
                  discount=cart_summary['discount']
                  )
    order.save()

    # Сформировать и отправить письмо с заказом
    send_new_order_email(data['email'], order)

    # ToDo Письмо администраторам

    return order
コード例 #11
0
ファイル: views.py プロジェクト: drzazga888/book-rental
def finalize(request):
    if request.method == 'POST':
        if request.user.is_authenticated():
            print request.POST
            order = Order(first_name=request.POST['first_name'], last_name=request.POST['last_name'],
                          street=request.POST['street'], number=request.POST['number'], zip=request.POST['zip'], \
                          city=request.POST['city'], price=request.POST['summary'], withdrawtype=request.POST['collection'], \
                          user=request.user, paid=0, \
                          phone=request.POST['phone'], title=request.POST['title'])
            order.save()
            for book in request.POST.getlist("book[]"):
                tmpbook = Book.objects.get(id=book)
                orderedbook = OrderedBook(title=tmpbook.title, author=tmpbook.author, publisher=tmpbook.publisher, price=tmpbook.price, returned=0, book=tmpbook, order=order)
                orderedbook.save()
            request.session["message"] = u"Zamówienie zostało złożone. Zostanie zrealizowane niezwłocznie po zaksięgowaniu wpłaty"
            request.session["message_context"] = "success"
            return HttpResponseRedirect('/')
        else:
            request.session["message"] = u"Przed złożeniem zamówienia zaloguj się lub załóż konto"
            request.session["message_context"] = "danger"
            return HttpResponseRedirect('/users/authenticate')
    else:
        request.session["message"] = u"Zamówienie nie zostało wysłane poprawnie"
        request.session["message_context"] = "danger"
        return HttpResponseRedirect('/orders/checkout')
コード例 #12
0
    def test_payment_get_paid(self, mock_Request):
        Payment = apps.get_model('getpaid', 'Payment')
        order = Order(name='Test PLN order', total='123.45', currency='PLN')
        order.save()
        payment = Payment(pk=99,
                          order=order,
                          amount=order.total,
                          currency=order.currency,
                          backend='getpaid.backends.payu')
        payment.save(force_insert=True)
        payment = Payment.objects.get(
            pk=99
        )  # this line is because django bug https://code.djangoproject.com/ticket/5903
        processor = getpaid.backends.payu.PaymentProcessor(payment)
        processor.get_payment_status(u'99:1342616247.41')
        self.assertEqual(payment.status, u'paid')
        self.assertNotEqual(payment.paid_on, None)
        self.assertNotEqual(payment.amount_paid, Decimal('0'))

        url = 'https://secure.payu.com/paygw/UTF/Payment/get/txt'
        callargs = mock_Request.call_args_list
        self.assertEqual(url, callargs[0][0][0])
        if six.PY3:
            self.assertIsInstance(callargs[0][0][1], bytes)
            self.assertTrue(b'pos_id=123456789' in callargs[0][0][1])
            self.assertTrue(
                b'session_id=99%3A1342616247.41' in callargs[0][0][1])
        else:
            self.assertIsInstance(callargs[0][0][1], str)
            self.assertTrue('pos_id=123456789' in callargs[0][0][1])
            self.assertTrue(
                'session_id=99%3A1342616247.41' in callargs[0][0][1])
コード例 #13
0
ファイル: test_payu.py プロジェクト: cypreess/django-getpaid
    def test_payment_get_paid(self, mock_Request):
        Payment = apps.get_model('getpaid', 'Payment')
        order = Order(name='Test PLN order', total='123.45', currency='PLN')
        order.save()
        payment = Payment(pk=99, order=order, amount=order.total, currency=order.currency,
                          backend='getpaid.backends.payu')
        payment.save(force_insert=True)
        payment = Payment.objects.get(
            pk=99)  # this line is because django bug https://code.djangoproject.com/ticket/5903
        processor = getpaid.backends.payu.PaymentProcessor(payment)
        processor.get_payment_status(u'99:1342616247.41')
        self.assertEqual(payment.status, u'paid')
        self.assertNotEqual(payment.paid_on, None)
        self.assertNotEqual(payment.amount_paid, Decimal('0'))

        url = 'https://secure.payu.com/paygw/UTF/Payment/get/txt'
        callargs = mock_Request.call_args_list
        self.assertEqual(url, callargs[0][0][0])
        if six.PY3:
            self.assertIsInstance(callargs[0][0][1], bytes)
            self.assertTrue(b'pos_id=123456789' in callargs[0][0][1])
            self.assertTrue(b'session_id=99%3A1342616247.41' in callargs[0][0][1])
        else:
            self.assertIsInstance(callargs[0][0][1], str)
            self.assertTrue('pos_id=123456789' in callargs[0][0][1])
            self.assertTrue('session_id=99%3A1342616247.41' in callargs[0][0][1])
コード例 #14
0
ファイル: views.py プロジェクト: dmoury/lengowtest
def upload(request):
    orders = getOrders()
    for order in orders:
        orderId = getField(order, 'order_id')
        try:
            newOrder = Order.objects.get(order_id=orderId)
        except:
            marketplace = getField(order, 'marketplace')
            # Status fields
            status = order.getElementsByTagName("order_status").item(0)
            marketplaceStatus = getField(status, 'marketplace')
            lengowStatus = getField(status, 'lengow')

            orderDate = getField(order, 'order_purchase_date')
            formatedDate = orderDate if orderDate != '' else None
            amount = getField(order, 'order_amount')
            currency = getField(order, 'order_currency')
            newOrder = Order(None, orderId, marketplace, amount, currency,
                             marketplaceStatus, lengowStatus, formatedDate)

            newOrder.save()
    #delete temporary file
    os.remove(filename)
    messages.success(request, "Orders uploaded successfuly !")
    return redirect("/list")
コード例 #15
0
ファイル: test_order.py プロジェクト: cypreess/django-getpaid
    def test_failure_order_additional_validation(self):
        """
        Tests if HTTP304 when order additional validation signal raises
        ValidationError exception.
        """

        def custom_validation_listener(sender=None, request=None, order=None,
                                       backend=None, **kwargs):
            raise ValidationError("BOOM!")

        suid = 'test-order_additional_validation'
        signals.order_additional_validation.connect(custom_validation_listener,
                                                    dispatch_uid=suid)

        order = Order(name='Test order custom validation',
                      total=100,
                      currency='PLN')
        order.save()
        try:
            url = reverse('getpaid:new-payment', kwargs={'currency': 'PLN'})
            data = {'order': order.pk, 'backend': 'getpaid.backends.payu'}
            response = self.client.post(url, data)
            self.assertEqual(response.status_code, 403)
        finally:
            signals.order_additional_validation.disconnect(dispatch_uid=suid)
コード例 #16
0
ファイル: views_upload.py プロジェクト: sina-chaichi/ocr
def model_form_upload(request):
    upload_check = False
    if request.method == 'POST':
        upload_check = False
        current_user = request.user
        order_list = Order.objects.filter(user=current_user,
                                          is_finished=False).order_by('-id')
        if len(order_list) > 0:
            order = order_list[0]
        else:
            order = Order(user=current_user)
            order.save()
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid:
            document = form.save(commit=False)
            document.user = current_user
            document.order = order
            document.save()
            # order.is_finished = True
            upload_check = True

        else:
            print(form.errors)
    else:
        form = DocumentForm()
    return render(request, 'relatedpages/upload.html', {
        'form': form,
        'upload_check': upload_check
    })
コード例 #17
0
ファイル: views.py プロジェクト: PixLix1/donations_point
def request_product(request, item_id, page_num=None):
    try:
        product = Products.objects.get(id=item_id)
        submitted_orders = Order.objects.filter(status=1).filter(
            user_id=request.user.id)
        requested_prod_ids = [product.item_id for product in submitted_orders]

        # owner should not request their products
        # avoid multiple requests for same product
        # avoid requests on inactive products
        if product.user != request.user and item_id not in requested_prod_ids and product.status < 3:
            order = Order(user=request.user,
                          item=Products.objects.get(id=item_id),
                          owner=product.user)
            order.save()
            if product.status == 1:
                product.status = 2
            product.save()

    except Products.DoesNotExist:
        raise Http404('Products with id %s is not available' % item_id)

    previous_url = request.META['HTTP_REFERER']
    if not page_num or 'search_term' in previous_url:
        return redirect(previous_url)

    return redirect('%s?page=%s' % (reverse('products:items:list'), page_num))
コード例 #18
0
ファイル: booking.py プロジェクト: cs98jrb/Trinity
    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
コード例 #19
0
ファイル: views.py プロジェクト: jishnusaurav/CovTech
def ordering():
    if (sb.temp == 1):
        resp = sb.handle("show list")
        resp, sb.other = resp
        resp = "Processing.... \nEnter your phone number:"
    elif (sb.temp == 2):
        sb.phone = int(s)
        resp = "Processing.... \nEnter your address:"
    else:
        sb.address = s
        for product, quantity in sb.other:
            p = Product.objects.get(slug=product)
            u = User.objects.get(username=request.user.username)
            o = Order(item=product,
                      quantity=quantity,
                      price=p.price,
                      total=(int(quantity) * int(p.price)),
                      name=request.user.username,
                      phone=sb.phone,
                      email=u.email,
                      address=sb.address,
                      user_id=u.id)
            o.save()
        resp = "Adding... \nCheck Dashboard"
        sb.handle("clear list")
        sb.temp = 0
    # print(other)
    return HttpResponse(resp)
コード例 #20
0
ファイル: views.py プロジェクト: hzy/Cafe-Au-Lait
def submit(request):
	message = 'Something went wrong :('
	if request.is_ajax():
		if request.method == 'POST':
			# Here we can access the POST data
			itemlist = simplejson.loads(request.raw_post_data)
			o = None
			#loops through the provided json
			for item in itemlist:
				if item['value']:
					if int(item['value']) > 0:
						#checks if the order exists yet
						if o == None:
							o = Order(tendered="1000", table="1")
							o.save()
						c = Content(order= o, quantity= item['value'])
						#determines the type of the drink
						if str(item['name'])[:1] == "d":
							c.takeaway = False
						elif str(item['name'])[:1] == "t":
							c.takeaway = True
						c.beverage = Beverage.objects.get(pk= str(item['name'])[2::])
						c.save()
			cache.delete_many(['orders_current_orders', 'orders_current_contents'])
			message = "XHR Complete"
	return HttpResponse(message)
コード例 #21
0
ファイル: getdata.py プロジェクト: pixelkfr/django-ecommerce
    def handle(self, *args, **options):
        logger = logging.getLogger()
        steam_handler = logging.StreamHandler()
        steam_handler.setLevel(logging.DEBUG)
        logger.addHandler(steam_handler)
        try:
            request = urllib2.urlopen(
                "http://test.ecommerce.io/orders-test.xml")
            tree = ET.parse(request)
        except:
            raise CommandError('Xml file is not valid')

        orders = tree.find("orders")
        for item in orders.getiterator('order'):
            if ((item.find('marketplace').text) is not None)\
                 and(item.find('order_purchase_date').text is not None)\
                 and(item.find('order_amount').text is not None)\
                 and(item.find('order_currency').text is not None)\
                 and(item.find('order_id').text is not None):
                marketplace = item.find('marketplace')
                order_purchase_date = item.find('order_purchase_date')
                order_amount = item.find('order_amount')
                order_currency = item.find('order_currency')
                order_id = item.find('order_id')
                # add and save a new order
                new_order = Order(marketplace=marketplace.text,
                                  order_purchase_date=order_purchase_date.text,
                                  order_amount=order_amount.text,
                                  order_currency=order_currency.text,
                                  order_id=order_id.text)
                new_order.save()
            else:
                logger.warning("A required argument is missing"
                               " for one order, please look at your xml file.")
コード例 #22
0
ファイル: tests.py プロジェクト: MaralKay/pizza-service
class ModelTestCase(TestCase):
    def setUp(self):
        self.customer_name = 'Test Name'
        self.customer_address = 'Test Address'
        self.customer = Customer(customer_name=self.customer_name,
                                 customer_address=self.customer_address)

        self.pizza_size = True
        self.pizza_flavor = 'Surprise'
        self.pizza = Pizza(pizza_size=self.pizza_size,
                           pizza_flavor=self.pizza_flavor)

        self.order = Order(customer=self.customer, pizza=self.pizza)

    def test_model_create_order(self):
        old_count = Customer.objects.count()
        self.customer.save()
        new_count = Customer.objects.count()
        self.assertNotEqual(old_count, new_count)

        old_count = Pizza.objects.count()
        self.pizza.save()
        new_count = Pizza.objects.count()
        self.assertNotEqual(old_count, new_count)

        old_count = Order.objects.count()
        self.order = Order(customer=Customer.objects.latest('customer_id'),
                           pizza=Pizza.objects.latest('pizza_id'))
        self.order.save()
        new_count = Order.objects.count()
        self.assertNotEqual(old_count, new_count)
コード例 #23
0
def confrm_checkout(request):
	if len(request.session['cart']) != 0:
		if request.method == 'POST':
			name = request.POST['name']
			phone = request.POST['phonenumber']
			email = request.POST['email']
			address = request.POST['address']
			user_id = request.user.id
			if name and phone and email and address:
				for key,value in request.session['cart'].items():
					item = value['title']
					quantity = value['quantity']
					price = value['price']
					total = (float(quantity) * float(price))
					order = Order(item=item,quantity=quantity,price=price,total=total,name=name,phone=phone,email=email,address=address,user_id=user_id)
					order.save()
				cart_clear(request)
				messages.success(request,'Order Created SuccessFully')
				return redirect('users:dashboard')
			else:
				messages.info(request,'Filled All The Field')
				return redirect('cart:checkout')
		else:
			messages.warning(request,'SomeThing Went Wrong')
			return redirect('cart:checkout')
	else:
		messages.info(request,"Your cart Is Empty")
		return redirect('/')
コード例 #24
0
ファイル: test_e2e.py プロジェクト: hossamelneily/nexchange
 def test_import_payeer_invalid_status(self, convert_to_cash, trans_hist):
     convert_to_cash.return_value = None
     sender = 'zaza'
     # TODO: get fixutre
     trans_hist.return_value = {
         '1': {
             'id': '1',
             'type': 'transfer',
             'status': 'None',
             'creditedCurrency': self.EUR.code,
             'creditedAmount': str(self.payeer_order_data['amount_quote']),
             'to': 'tata',
             'shopOrderId': self.payeer_order_data['unique_reference'],
             'comment': self.payeer_order_data['unique_reference'],
             'from': sender
         }
     }
     order = Order(**self.payeer_order_data)
     order.save()
     import_payeer_payments = PayeerPaymentChecker()
     import_payeer_payments.run()
     p = Payment.objects.filter(amount_cash=order.amount_quote,
                                currency=order.pair.quote,
                                reference=order.unique_reference)
     self.assertEqual(0, len(p))
コード例 #25
0
def checkout(request, slug):
    order = Order.objects.get(slug=slug)
    order_items = OrderItem.objects.filter(order=order)
    order_total = 0
    order_items_total = 0
    order.customer = request.user
    for item in order_items:
        subtotal = item.quantity * item.unity_price
        order_total = order_total + subtotal
        order_items_total = order_items_total + item.quantity

    if order.status == "pending":
        order.status = "on_hold"
        order.save()

        restaurant = order.restaurant
        order = Order(restaurant=restaurant)

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

    context = {
        'order': order,
        'order_items': order_items,
        'order_total': order_total,
        'order_items_total': order_items_total,
    }
    return render(request, 'orders/simple_checkout.html', context=context)
コード例 #26
0
def order_create(request):
    # Getting data
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)
    content = json.loads(body['order_data'])

    # Getting the new sequence
    new_sequence = Order.objects.order_by("-id")[0].id
    new_sequence += 1

    # Creating the object to save
    order = Order(id=new_sequence,
                  date=content['date'],
                  state='A',
                  observation=content['observation'],
                  commentary=content['commentary'],
                  warehouse_id=content['warehouse']['code'],
                  branch_id=content['branch']['code'],
                  travel_id=content['travel']['code'],
                  applicant_id=content['applicant']['id'],
                  user_created=content['userCreated'],
                  date_created=content['dateCreated'])

    order.save()

    detail_sequence = 0
    for d in content['detail']:
        detail_sequence += 1
        OrderDetail.objects.create(order_id=new_sequence,
                                   sequence=detail_sequence,
                                   quantity=d['quantity'],
                                   detail=d['detail'])

    return JSONResponse({'id': new_sequence}, status=status.HTTP_200_OK)
コード例 #27
0
ファイル: getdata.py プロジェクト: tilwing/django-ecommerce
    def handle(self, *args, **options):
        logger = logging.getLogger()
        steam_handler = logging.StreamHandler()
        steam_handler.setLevel(logging.DEBUG)
        logger.addHandler(steam_handler)
        try:
            request = urllib2.urlopen("http://test.ecommerce.io/orders-test.xml")
            tree = ET.parse(request)
        except:
            raise CommandError('Xml file is not valid')

        orders = tree.find("orders")
        for item in orders.getiterator('order'):
            if ((item.find('marketplace').text) is not None)\
                 and(item.find('order_purchase_date').text is not None)\
                 and(item.find('order_amount').text is not None)\
                 and(item.find('order_currency').text is not None)\
                 and(item.find('order_id').text is not None):
                marketplace = item.find('marketplace')
                order_purchase_date = item.find('order_purchase_date')
                order_amount = item.find('order_amount')
                order_currency = item.find('order_currency')
                order_id = item.find('order_id')
                # add and save a new order
                new_order = Order(marketplace=marketplace.text,
                                  order_purchase_date=order_purchase_date.text,
                                  order_amount=order_amount.text,
                                  order_currency=order_currency.text,
                                  order_id=order_id.text)
                new_order.save()
            else:
                logger.warning("A required argument is missing"
                              " for one order, please look at your xml file.")
def PlaceOrder(request):

#API to place and order. Gets the appropriate customer and restaurant object using the ids, then creates an order object and updates the placed_order table too. then each item is added to the order_content one by one. finally the items in the tempItem table are deleted using the restaurant and customer object as they are no longer needed.
    if request.method == 'POST':
    
        c = request.data.get('customer')
        customer= Customer.objects.get(customer_id=c)
        
        r = request.data.get('restaurant')
        restaurant= Restaurant.objects.get(restaurant_id=r)
        
        order = Order(status='P')      
        order.save()
        
        placed_order = Placed_order(customer = customer,restaurant = restaurant, order = order)
        placed_order.save()
        
        tempItems = TempItem.objects.filter(customer=customer, restaurant=restaurant)
        
        totalprice = 0
        for i in range(len(tempItems)):
            item = tempItems[i]
            
            index= item.item.item_id
            originalItem = Item.objects.get(item_id= index, restaurant= restaurant)
            
            price=item.price
            totalprice+=price
            
            orderqty=item.quantity
            
            oldqty = originalItem.quantity
            
            newqty = oldqty-orderqty
            
            if(newqty>=0):
                originalItem.quantity=newqty
                originalItem.save()
                
                
                order_content = Order_content(restaurant = restaurant, order = order, item = originalItem, quantity = orderqty, total_price = price)
                order_content.save()
                
                TempItem.objects.filter(restaurant = restaurant, customer = customer, item = originalItem).delete()
                
                
                
                
            
            else:
                TempItem.objects.filter(restaurant = restaurant, customer = customer, item = originalItem).delete()


        response = {
            'price' : totalprice
            }
        
        return Response(response, status.HTTP_200_OK)
        
            
コード例 #29
0
    def handle(self, *args, **options):
        # Récupération du fichier xml
        response = requests.get(URL)
        data = response.content

        # Récupération de la racine du fichier XML
        xml_root = et.fromstring(data)

        # On récupère le noeud parent qui nous interesse : <orders></orders>
        orders = xml_root.find("orders")

        # On parcours les balises <order></order>
        for order_xml in orders.iter('order'):
            # Pour chaque order, on initialise une nouvelle commande
            # que l'on remplit puis sauvegarde.
            new_order = Order()

            new_order.id = order_xml.find("order_id").text
            new_order.marketplace = order_xml.find("marketplace").text
            new_order.idFlux = order_xml.find("idFlux").text
            new_order.order_amount = order_xml.find("order_amount").text

            if order_xml.find("order_purchase_date").text is not None:
                dt = parser.parse(order_xml.find("order_purchase_date").text)
                new_order.order_purchase_date = date(dt.year, dt.month, dt.day)
            if order_xml.find("order_purchase_heure").text is not None:
                dt = parser.parse(order_xml.find("order_purchase_heure").text)
                new_order.order_purchase_heure = time(dt.hour, dt.minute,
                                                      dt.second)

            new_order.save()
コード例 #30
0
ファイル: tests.py プロジェクト: KirillAKostin/TRPOProject
 def test_order_accept(self):
     order_test = Order(client_phone=8432424,
                        type=Order.TYPE_DINNER_WAGON,
                        state=Order.STATE_DONE,
                        order_date=date(2014, 12, 12),
                        execute_date=datetime(2014, 12, 12).date())
     order_test.accept()
     self.assertEqual(order_test.state, Order.STATE_IN_PROGRESS)
コード例 #31
0
ファイル: tests.py プロジェクト: ork-a/pan_kanapka
 def test_simple_order(self):
     sandwich = Sandwich.objects.get(id=1)
     order = OrderSandwiches(sandwich=sandwich, quantity=2)
     order.save()
     order_list = Order()
     order_list.save()
     order_list.sandwiches.add(order)
     self.assertIn(order, order_list.sandwiches.all())
コード例 #32
0
ファイル: order_data_access.py プロジェクト: skaidan/burger
 def save_new_order(self, order_entity, user):
     self.order = Order()
     self.order.created_by = user
     self.order.created_at = datetime.datetime.now()
     self.order.save()
     self._update_order_elements(user.id, order_entity)
     self._apply_offers()
     return self._order_total_price(self.order)
コード例 #33
0
ファイル: views.py プロジェクト: imadarshj/covaid
def confrm_checkout(request):
	if len(request.session['cart']) != 0:
		if request.method == 'POST':
			name = request.POST['name']
			phone = request.POST['phonenumber']
			email = request.POST['email']
			address = request.POST['address']
			user_id = request.user.id
			orders=[]
			tot_price=0
			if name and phone and email and address:
				for key,value in request.session['cart'].items():
					item = value['title']
					product_id = value['productid']
					product_object = Product.objects.filter(productid = product_id)[0]
					quantity = value['quantity']
					price = value['price']
					total = (float(quantity) * float(price))
					order = Order(item=item,
					productid=product_object ,
					quantity=quantity,
					price=price,
					total=total,
					name=name,
					phone=phone,
					email=email,
					address=address,
					user_id=user_id
					)
					order.save()
					orders.append(order)
					tot_price += order.total

				content='Hi '+request.user.username+'\n\nYour recent order with order id: '+str(order.id)+' has been successfully placed.\
				Kindly, wait for the Seller to respond to your order.\n'
				send_mail("Order INVOICE", content, settings.SENDER_EMAIL, [request.user.email], fail_silently=False)
				content='Hi '+product_object.user.username+'\n\nCurrently an order with order id: '+str(order.id)+' has been successfully placed at your account.\
				Kindly, check the order and respond favourably to the customer.\n'
				send_mail("Order Alert!!", content, settings.SENDER_EMAIL, [product_object.user.email], fail_silently=True)
				# cart = Cart(request)
				# cart.clear()
				context ={
					'key': settings.STRIPE_PUBLISHABLE_KEY,
        			'orders': orders,
        			'price':int(tot_price)*100,
					'price2':tot_price
				}
				# messages.success(request,'Order Created SuccessFully')
				return render(request, 'payments/home.html', context)
			else:
				messages.info(request,'Filled All The Field')
				return redirect('cart:checkout')
		else:
			messages.warning(request,'SomeThing Went Wrong')
			return redirect('cart:checkout')
	else:
		messages.info(request,"Your cart Is Empty")
		return redirect('/')
コード例 #34
0
    def update_order(self, user):
        """
        Because for every Payout a requisition is made, we automatically
        generate the associated Order using this method. This Order
        object is pre filled with default information and has the
        Requisition Number field blank for future update.
        """
        if not orders_module_installed:
            return

        # no finance project is associated
        if self.project is None:

            # remove the existing order
            if self.order is not None:
                self.order.orderexpensecode_set.all().delete()
                self.order.delete()
                self.order = None

        elif self.order is None:

            supplier, created = Supplier.objects.get_or_create(
                supplier_name="Human resources")

            expensecode = ExpenseCode.objects.get(
                expensecode_number="01",
                project=self.project,
            )
            neworder = Order(
                order_amount=self.total_amount(),
                order_req=user.username,
                responsible=user,
                supplier=supplier,
                currency=Currency.objects.get(
                    currency_name=settings.DEFAULT_CURRENCY_NAME),
                order_desc="%s's - contract" % self.contract.person,
                order_reqdate=timezone.now(),
                group=AuthGroup.objects.get(
                    name=settings.PROFILE_HUMAN_RESOURCES),
            )
            neworder.save(expensecode_kwargs=dict(expensecode=expensecode))
            self.order = neworder

        elif self.order.order_reqnum is None:

            # In case the requisition was not placed yet,
            # we can still update the order
            self.order.order_amount = self.total_amount()
            self.order.save()

            expcode = OrderExpenseCode.objects.get(order=self.order, )
            expcode.orderexpensecode_amount = self.total_amount()
            expcode.save()

        else:
            raise Exception(
                'Sorry you cannot change the Payout, '
                'because the requisition number was already submitted.')
コード例 #35
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)
コード例 #36
0
ファイル: tests.py プロジェクト: KirillAKostin/TRPOProject
 def test_order_make(self):
     order_test = Order(client_phone=8432424,
                        type=Order.TYPE_DINNER_WAGON,
                        state=Order.STATE_DONE,
                        order_date=date(2014, 12, 12),
                        execute_date=datetime(2014, 12, 12).date())
     order_test.make()
     self.assertEqual(order_test.state.__str__(), '4', 'State of order is not equal')
     self.assertEqual(order_test.type, Order.TYPE_DINNER_WAGON)
コード例 #37
0
ファイル: tests.py プロジェクト: KirillAKostin/TRPOProject
 def test_order_perform(self):
     order_test = Order(client_phone=8432424,
                        type=Order.TYPE_DINNER_WAGON,
                        state=Order.STATE_DONE,
                        order_date=date(2014, 12, 12),
                        execute_date=datetime(2014, 12, 12).date(),
                        dinner_wagon=DinnerWagon(seats=2))
     order_test.perform()
     self.assertEqual(order_test.state, Order.STATE_DONE)
コード例 #38
0
ファイル: views.py プロジェクト: hardik-kgp/DBMS_term_project
def my_orders(request):
    if request.user.is_authenticated and request.user.profile.type == "E":
        messages.warning(request, "You can't order as employees")
        return redirect('users:dashboard')
    orders = Order.find_orders_of_customer(request.user.profile.customer_id)
    orders_box = []
    for order in orders:
        orders_box.append((order, Order.find_order_items(order.order_id)))
    return render(request, 'users/my_orders.html', {'orders': orders_box})
コード例 #39
0
ファイル: serializers.py プロジェクト: ZininEgor/FoodBoxes
 def create(self, validated_data):
     order = Order(recipient=validated_data['recipient'],
                   address=validated_data['address'],
                   delivery_at=validated_data['delivery_at'],
                   cart=validated_data['recipient'].current_cart,
                   total_cost=self.validated_data['recipient'].current_cart.
                   total_cost)
     order.save()
     return order
コード例 #40
0
def order_webhook(request):
    """
    Syncs the incoming order data from shopify to Order model.
    """
    if not request.body:
        return
    order_data = process_webhook_order_data(json.loads(request.body))
    order_instance = Order()
    order_instance.save_order(**order_data)
コード例 #41
0
ファイル: views.py プロジェクト: dsethan/tripping-dangerzone
def process_order(request):
    context = RequestContext(request)
    user = request.user
    increment_clicks(user)
    profile = get_associated_profile(user)
    cart = get_cart(profile)

    items_to_package = []
    total_price = 0
    for item in CartItem.objects.all():
        if item.cart == cart:
            items_to_package.append(item.item)
            total_price = total_price + item.item.price

    entry_id = request.POST.get("entry_id")
    entry = Entry.objects.get(id=entry_id)

    new_order = Order(
        user_profile=profile,
        restaurant=profile.restaurant,
        total=total_price,
        entry=entry,
        status="PDG",
        order_success=False,
        order_rating=0,
    )

    new_order.save()

    order_dict = {}

    for item in items_to_package:
        if item.id in order_dict.keys():
            order_dict[item.id] = order_dict[item.id] + 1
        else:
            order_dict[item.id] = 1

    order_items = []
    for key in order_dict.keys():
        item = Item.objects.get(id=key)
        quantity = order_dict[key]
        new_order_item = OrderItem(item=item, order=new_order, quantity=quantity)
        new_order_item.save()
        order_items.append(new_order_item)

        # cart.delete()

        # print order_dict.keys()
    cart_id = cart.id
    print cart.id

    return render_to_response(
        "confirm.html",
        {"total_price": total_price, "user": user, "profile": profile, "order_items": order_items, "cart_id": cart_id},
        context,
    )
コード例 #42
0
ファイル: tests.py プロジェクト: snarlygoster/ordersystem
 def test_creating_a_new_order_and_saving(self):
     order = Order()
     order.ticket = 'Ticket 1234'
     #
     order.save()
     all_orders = Order.objects.all()
     self.assertEqual(len(all_orders), 1)
     only_order = all_orders[0]
     self.assertEqual(only_order,order)
     self.assertEqual(only_order.ticket, order.ticket)
コード例 #43
0
ファイル: booking.py プロジェクト: cs98jrb/Trinity
    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
コード例 #44
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
                }))
コード例 #45
0
ファイル: views.py プロジェクト: Nrptuner-smallj/graduate
    def get(self, request):
        ids = request.GET.getlist('record_id')
        address = request.GET.get('address','')
        if not address:
            records = ShopCartRecord.objects.filter(id__in=ids)
            addresses = request.user.address_set.all()
            return render(request, 'informationconfirm.html', dict(records=records, addresses=addresses,msg='地址不得为空'))

        new_ids = []
        for id in ids:
            new_ids.append(int(id))
        total_price = 0.0
        records = ShopCartRecord.objects.filter(id__in=new_ids)

        # 创建订单
        for record in records:
            total_price = total_price + (record.nums * record.commodity.price)
        order = Order()
        # 订单总价
        order.total_price = total_price
        # 订单状态
        order.status = 'unpaid'
        # 用户
        order.user = request.user
        # 唯一的订单号生成 时间戳+四位随机数+用户四位标识符
        t = time.time()
        timestamp = str(round(t * 1000))
        ran = random.randint(1, 9999)
        id = ''
        while True:
            if request.user.id < 10000:
                id = 'D' + str(int(timestamp) * 100000000 + ran * 10000 + request.user.id)
            else:
                id = 'D' + str(int(timestamp) * 100000000 + ran * 10000 + int(str(request.user.id))[-5:-1])
            if not Order.objects.filter(id=id):
                break
        order.id = id
        order.save()
        if not records:
            order.delete()
        # 分别创建发货单
        for i, record in enumerate(records):
            delivery_order = DeliveryOrder()
            delivery_order.id = order.id.replace('D', 'C') + str(i)
            delivery_order.address = address
            delivery_order.order = order
            delivery_order.commodity = record.commodity
            delivery_order.nums = record.nums
            delivery_order.status = 'ing'
            delivery_order.save()

        # 删去购物车的记录
        l = len(records)
        records.delete()
        return render(request, 'pay.html', dict(order=order))
コード例 #46
0
ファイル: tests.py プロジェクト: mskarbek/django-getpaid
 def test_online_payment_failure(self):
     Payment = get_model('getpaid', 'Payment')
     order = Order(name='Test EUR order', total='123.45', currency='PLN')
     order.save()
     payment = Payment(order=order, amount=order.total, currency=order.currency, backend='getpaid.backends.payu')
     payment.save(force_insert=True)
     self.assertEqual('TRUE', getpaid.backends.transferuj.PaymentProcessor.online('195.149.229.109', '1234', '1', '',
                                                                                  payment.pk, '123.45', '23.45', '',
                                                                                  False, 0, '',
                                                                                  '21b028c2dbdcb9ca272d1cc67ed0574e'))
     payment = Payment.objects.get(pk=payment.pk)
     self.assertEqual(payment.status, 'failed')
コード例 #47
0
ファイル: test_order.py プロジェクト: cypreess/django-getpaid
 def test_failure_create_payment_eur(self):
     """
     Tests if payment fails when wrong currency for backend.
     PayU accepts only PLN currency payments.
     """
     order = Order(name='Test EUR order', total=100, currency='EUR')
     order.save()
     response = self.client.post(reverse('getpaid:new-payment',
                                         kwargs={'currency': 'EUR'}),
                                 {
                                     'order': order.pk,
                                     'backend': 'getpaid.backends.payu'})
     self.assertEqual(response.status_code, 403)
コード例 #48
0
 def form_valid(self, form):
     context = self.get_context_data()
     formset = context['formset']
     if formset.is_valid():
         self.object = form.save()  # saving customer
         order = Order(customer=self.object)
         order.save()  # creating order
         formset.instance = order
         formset.save()  # saving items
         order.save()  # updating total price
         return HttpResponseRedirect('/admin/orders/order/')
     else:
         return self.render_to_response(self.get_context_data(form=form))
コード例 #49
0
def order_list(request, format=None):
  """
  List all orders, or create a new order.
  """
  if request.method == 'GET':
    orders = Order.objects.all()
    serializer = OrderSerializer(orders, many=True)
    return Response(serializer.data)

  elif request.method == 'POST':
    order = Order()
    order.save()
    serializer = OrderSerializer(order)
    return Response(serializer.data)
コード例 #50
0
ファイル: tests.py プロジェクト: mskarbek/django-getpaid
    def test_get_payment_status_failed(self):
        Payment = get_model('getpaid', 'Payment')
        order = Order(name='Test PLN order', total='123.45', currency='PLN')
        order.save()

        payment = Payment(pk=192, order=order, amount=order.total, currency=order.currency,
                          backend='getpaid.backends.przelewy24')
        payment.save(force_insert=True)
        payment = Payment.objects.get(pk=192)
        processor = getpaid.backends.przelewy24.PaymentProcessor(payment)
        processor.get_payment_status(p24_session_id='192:xxx:xxx', p24_order_id='192:external', p24_kwota='12245')
        self.assertEqual(payment.status, 'failed')
        self.assertEqual(payment.paid_on, None)
        self.assertEqual(payment.amount_paid, Decimal('0.0'))
コード例 #51
0
ファイル: tests.py プロジェクト: mskarbek/django-getpaid
 def test_payment_get_failed(self):
     Payment = get_model('getpaid', 'Payment')
     order = Order(name='Test EUR order', total='123.45', currency='PLN')
     order.save()
     payment = Payment(pk=98, order=order, amount=order.total, currency=order.currency,
                       backend='getpaid.backends.payu')
     payment.save(force_insert=True)
     payment = Payment.objects.get(
         pk=98)  # this line is because django bug https://code.djangoproject.com/ticket/5903
     processor = getpaid.backends.payu.PaymentProcessor(payment)
     processor.get_payment_status('98:1342616247.41')
     self.assertEqual(payment.status, 'failed')
     self.assertEqual(payment.paid_on, None)
     self.assertEqual(payment.amount_paid, Decimal('0'))
コード例 #52
0
ファイル: views.py プロジェクト: Valentincrasnier/lengow
def index(request):

    from lxml import etree
    import requests
    from orders.models import Order
    Order.objects.all().delete()
    xml = requests.get("http://test.lengow.io/orders-test.xml")

    tree = etree.fromstring(xml.content)
    for order in tree.xpath("/statistics/orders/order"):
      o = Order()
      for child in order:
        setattr(o, child.tag, child.text)
      o.save()
    return HttpResponse("L'importation de orders-test.xml s'est déroulée avec succès. <br /> <a href='/api/orders/'>consulter les données</a>")
コード例 #53
0
ファイル: views.py プロジェクト: matsinvasion/motome
def login(request):
    user = request.session['customer']

    if request.method == 'POST':
        password_form = PasswordForm(request.POST, user=user)
        customer_form = CustomerForm(request.POST)

        if password_form.is_valid() and customer_form.is_valid():
            customer = request.session['customer']

            customer.first_name = customer_form.cleaned_data['first_name']
            customer.last_name = customer_form.cleaned_data['last_name']
            customer.email = customer_form.cleaned_data['email']
            customer.save()

            user = auth.authenticate(username=customer.username, password=password_form.cleaned_data['password'])
            auth.login(request, user)
            order = Order.from_request(request)
            order.user = user
            order.save()

            if 'location' in request.session:
                location = request.session['location']
                return HttpResponseRedirect("%s?lat=%s&lng=%s" % (reverse('public.location_create'), location.lat, location.lng))
            else:
                return HttpResponseRedirect(reverse('public.location_create'))
    else:
        password_form = PasswordForm(user=user)
        customer_form = CustomerForm(initial={'first_name':user.first_name, 'last_name':user.last_name, 'email': user.email})

    context = dict(password_form=password_form, customer_form=customer_form, user=user)
    return render_to_response('public/login.html', context, context_instance=RequestContext(request))
コード例 #54
0
ファイル: views.py プロジェクト: matsinvasion/motome
def cart(request):
    order = Order.from_request(request)
    country = Country.objects.get(country_code='RW')

    if request.method == 'POST':
        if 'add_product' in request.REQUEST:
            product = Product.objects.get(id=request.REQUEST['add_product'], is_active=True)
            order.add_single(product)

        if set(('update', 'checkout', 'shop')).intersection(set(request.REQUEST.keys())):
            for item in order.items.all():
                if 'remove_%d' % item.id in request.REQUEST:
                    order.items.filter(pk=item.id).update(is_active=False)

                for addon in item.product.addons.all():
                    exists_in_order = item.addons.filter(addon=addon)
                    form_name = 'addon_%d_%d' % (item.id, addon.id)
                    exists_in_form = form_name in request.REQUEST

                    if exists_in_order and not exists_in_form:
                        exists_in_order.update(is_active=False)

                    elif exists_in_form and not exists_in_order:
                        item.add_on(addon)

            if 'checkout' in request.REQUEST:
                return HttpResponseRedirect(reverse('public_checkout'))
            elif 'shop' in request.REQUEST:
                return HttpResponseRedirect("%s?password=iamhungry" % reverse('public_home'))

    context = dict(cart=True, order=order, country=country, currency=country.currency)
    return render_to_response('public/cart.html', context, context_instance=RequestContext(request))
コード例 #55
0
ファイル: client_views.py プロジェクト: kpx13/derm_svp
def history(request):
    c = get_client_context(request)
    
    if request.method == 'GET':
        pass
    elif request.method == 'POST':
        order = Order.get_by_id(request.POST.get('id'))
        action = request.POST.get('action')
        if action == 'pay':
            cost = order.cost
            if c['user_profile'].pay(cost):
                order.set_waiting()
                messages.success(request, u'Ваш заказ успешно оплачен.')
            else:
                messages.error(request, u'У Вас недостаточно средств для совершения платежа.')
        elif action == 'del':
            order.delete()
            messages.success(request, u'Заказ удален.')
        elif action == 'close':
            order.set_closed()
            order.handler.person.get_profile().earn(order.cost * 0.9)
            messages.success(request, u'Вы подтвердили выполнение заказа. Спасибо за использование нашего сервиса.')
        return HttpResponseRedirect('/cabinet/history')

    c['orders'] = Order.objects.filter(customer=c['client'])
    return render_to_response('client/history.html', c, context_instance=RequestContext(request))
コード例 #56
0
ファイル: tests.py プロジェクト: skotcarruth/buybay
 def setUp(self):
     self.ipn_record = IPNRecord(
         transaction_id=1,
         data='a=1',
     )
     self.ipn_record.save()
     self.order = Order(
         donation=100,
         status=Order.SHOPPING_CART,
     )
     self.order.save()
     self.product = Product(
         name='Test Product',
         slug='test-product',
         price=500,
         tax_deductible=50,
         min_quantity=0,
         max_quantity=10,
         current_quantity=5,
         status=Product.FOR_SALE,
     )
     self.product.save()
     self.product_in_order = ProductInOrder(
         order=self.order,
         product=self.product,
         quantity=1,
     )
     self.product_in_order.save()
コード例 #57
0
ファイル: views.py プロジェクト: thomwiggers/eetFestijn
def overview(request):
    if request.method == 'POST':
        if 'process' in request.POST:
            orders = []
            for order in Order.objects.all():
                orderdict = model_to_dict(order)
                orderdict['items'] = [{'name': item.name,
                                       'price': item.real_price(order.date)}
                                      for item in order.items.all()]
                orderdict['total'] = order.total()
                orders.append(orderdict)
            if orders:
                receipt = {'grandtotal': Order.grandtotal(),
                           'orders': orders}
                contents = json.dumps(receipt, cls=DateTimeEncoder)
                Receipt(contents=contents).save()
                Order.objects.all().delete()
            messages.success(request, "Alle bestellingen verwerkt!")
        elif 'remove' in request.POST:
            order = Order.objects.get(pk=request.POST['remove'])
            msg = "Bestelling van {.name} verwijderd!".format(order)
            order.delete()
            messages.success(request, msg)
        elif 'slack' in request.POST and hasattr(settings, 'SLACK'):
            jsondata = {'text': 'Nieuwe bestelling!',
                        'channel': settings.SLACK['channel'],
                        'username': settings.SLACK['username'],
                        'icon_emoji': settings.SLACK['icon_emoji']}
            for order in Order.objects.all():
                jsondata['text'] += '\n*{}* ({}):'.format(
                    order.name, euro(order.total()))
                items = [' {} ({})'.format(item.name,
                                           euro(item.real_price(order.date)))
                         for item in order.items.all()]
                jsondata['text'] += ', '.join(items)
            payload = {'payload': json.dumps(jsondata)}
            data = urllib.parse.urlencode(payload).encode('UTF-8')
            req = urllib.request.Request(settings.SLACK['webhook'], data)
            urllib.request.urlopen(req)
            messages.success(request, "Bestellingen gedeeld via Slack!")
        return HttpResponseRedirect(reverse('overview'))

    orders = Order.objects.all()
    context = {'orders': orders, 'grandtotal': Order.grandtotal(),
               'slack': hasattr(settings, 'SLACK')}
    return render(request, 'orders/overview.html', context)
コード例 #58
0
ファイル: views.py プロジェクト: skotcarruth/buybay
def update_cart(request):
    """Updates the user's shopping cart."""
    order = Order.get_or_create(request)
    order_form = OrderForm(request.REQUEST, prefix='btb', instance=order)
    if order_form.is_valid():
        order = order_form.save()
        return order.get_as_cart()
    return False
コード例 #59
0
ファイル: views.py プロジェクト: chensheng123/Django-Projects
	def get(self, request, *args, **kwargs):
		get_data = super(CheckoutView, self).get(request, *args, **kwargs)

		cart = self.get_object()
		user_checkout_id = request.session.get("user_checkout_id")
		if user_checkout_id != None:
			user_checkout = UserCheckout.objects.get(id=user_checkout_id)
			billing_address_id = request.session.get("billing_address_id")
			shipping_address_id = request.session.get("shipping_address_id")

			if billing_address_id == None or shipping_address_id == None:
				return redirect("order_address")
			else:
				billing_address = UserAddress.objects.get(id=billing_address_id)
				shipping_address = UserAddress.objects.get(id=shipping_address_id)
			
			

			new_order = Order()
			new_order.cart = cart
			new_order.user = user_checkout
			new_order.billing_address = billing_address
			new_order.shipping_address = shipping_address
			new_order.save()
		return get_data
コード例 #60
0
ファイル: views.py プロジェクト: dsethan/OverEasy
def create_order(cart_id, user, context):
	cart = Cart.objects.get(id=cart_id)
	items = cart.get_items_and_quantities()
	profile = users.views.return_associated_profile_type(user)
	entry = cart.entry

	total = cart.get_total_price_of_cart()

	tax = cart.get_tax_for_cart()

	new_order = Order(
		profile=profile,
		total=total + tax,
		entry=entry,
		status='PDG',
		)

	new_order.save()

	for item in items.keys():
		new_order_item = OrderItem(
			item=item,
			order=new_order,
			quantity=items[item]
			)
		item.number_ordered = item.number_ordered + 1
		item.save()
		
		new_order_item.save()

	entry.available = entry.available - 1
	entry.save()

	cart.cart_still_active = False
	cart.delete()

	profile = UserProfile.objects.get(user=user)
	send_receipt_text(profile, new_order)

	return render_to_response(
		'successful_charge.html',
		{
		'entry':entry,
		},
		context)