Ejemplo n.º 1
0
    def test_get_orders(self):
        order1 = Order.create(
            uuid=uuid.uuid4(),
            total_price=10,
            user=self.user1.id,
        )
        OrderItem.create(
            order=order1.id,
            item=self.item1.id,
            quantity=1,
            subtotal=self.item1.price,
        )

        order2 = Order.create(
            uuid=uuid.uuid4(),
            total_price=7,
            user=self.user1.id,
        )
        OrderItem.create(
            order=order2.id,
            item=self.item1.id,
            quantity=1,
            subtotal=self.item1.price,
        )

        resp = self.app.get('/orders/')
        assert resp.status_code == OK
        assert json.loads(resp.data.decode()) == [order1.json(), order2.json()]
Ejemplo n.º 2
0
    def test_delete_order__success(self):
        order1 = Order.create(
            uuid=uuid.uuid4(),
            total_price=10,
            user=self.user1,
        )
        OrderItem.create(
            order=order1.id,
            item=self.item1.id,
            quantity=1,
            subtotal=self.item1.price,
        )

        order2 = Order.create(
            uuid=uuid.uuid4(),
            total_price=12,
            user=self.user1,
        )
        OrderItem.create(
            order=order2.id,
            item=self.item1.id,
            quantity=1,
            subtotal=self.item1.price,
        )

        resp = self.app.delete('/orders/{}'.format(order1.uuid))
        assert resp.status_code == NO_CONTENT

        orders = Order.select()
        assert len(orders) == 1
        assert Order.get(Order.uuid == order2.uuid)

        order_items = OrderItem.select().where(OrderItem.order_id == order1.id)
        assert len(order_items) == 0
Ejemplo n.º 3
0
def new_order():
    received = request.get_json()
    form = OrderForm(data=received)

    if form.validate():
        customer_id = int(received['customer_id'])
        order = Order(customer_id=customer_id)

        for product_id in received['products']:
            product = Product.query.get(product_id)
            order.products.append(product)
        order.save()

        success = {"message" : "success"}
        return make_response(jsonify(success), 201)

    if form.errors:
        validation_err = []
        for entry in form.errors:
            validation_err.append({"message": "incorrect value: < {0} : {1} >".format(entry, received[entry])})
        return make_response(jsonify(validation_err), 400)

    # Something went really bad
    err = {"message": "internal server error"}
    return make_response(jsonify(err), 500)
Ejemplo n.º 4
0
    def test_a_3_001_order_insert(self):
        order1 = Order(user_id=20, product_id=5, amount=5)
        order1.insert()
        orders = Order.query.all()

        self.assertEqual(len(orders), 9)
        print("Test a_3_1: Order insert")
Ejemplo n.º 5
0
    def test_non_dict_raises_error(self):
        """ Pass invalid data structure deserialize """
        data = [1, 2, 3]
        order = Order()

        with self.assertRaises(DataValidationError):
            order.deserialize(data)
Ejemplo n.º 6
0
def checkout(request, step=0):
    if (request.method == 'POST'):
        if request.user.is_authenticated():
            now = datetime.datetime.utcnow().replace(tzinfo=utc)
            current_user = request.user
            current_order = Order(date_time=now, user=current_user)
            current_order.save()
            for i in range(1, 6):
                print(request.POST)
                try:
                    item_quantity = int(request.POST['item_quantity_' +
                                                     str(i)])
                except:
                    item_quantity = None
                if not item_quantity is None:
                    item_id = request.POST['item_options_' +
                                           str(i)].split(' ')[1]
                    print(item_id)
                    current_sticker = Sticker.objects.get(pk=int(item_id))
                    print(current_sticker)
                    order_item = OrderItem(order=current_order,
                                           sticker=current_sticker,
                                           quantity=item_quantity)
                    order_item.save()
    return redirect('/order/' + str(current_order.id) + '/1')
Ejemplo n.º 7
0
 def testPost4(self):
     #create an order that already exists in our database
     order = Order(orderId=1,pickup_lat=1.0,pickup_lon=1.0,dropoff_lat=2.0,dropoff_lon=2.0)
     order.put()
     params ={'id':1,'plat':3.0,'plon':4.0,'dlat':11.0,'dlon':11.0}
     response = self.testapp.post('/order/new',params)
     self.assertEqual(333, response.status_int)
Ejemplo n.º 8
0
def buy(request, **kw):
    ret_str = u""
    if kw['order'] is None or kw['openId'] is None:
        mOrder = request.GET.get(u'order', None)
        mOpenId = request.GET.get(u'openId', None)
    else:
        mOrder = kw['order']
        mOpenId = kw['openId']
    print mOpenId, " ", mOrder
    if (mOrder == '' or mOrder is None or mOpenId == '' or mOpenId is None):
        result = JsonUtil.obj2json(Result('error', '非法订单'))
        return HttpResponse(result, mimetype="text/html")
    mTotal = getTotal(mOrder)
    if mTotal == -1:
        result = Result('error', '非法订单!请重新购买.')
        ret_str += unicode(result.getData(), 'utf-8')
    else:
        o = Order(openId=mOpenId, order_list=mOrder, total=mTotal)
        o.save()
        result = Result('success', '点餐成功')
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
        ret_str += unicode(result.getData(), 'utf-8') + u',购买时间:' + now + u'  谢谢您的惠顾:-)'
    if request is None:
        return ret_str
    else:
        return HttpResponse(result, mimetype="text/html")
Ejemplo n.º 9
0
    def test_delete_order__success_admin_not_own_order(self):
        user = add_user('*****@*****.**', TEST_USER_PSW)
        addr_A = add_address(user=user)
        addr_B = add_address(user=user)

        item1 = Item.create(
            uuid='429994bf-784e-47cc-a823-e0c394b823e8',
            name='mario',
            price=20.20,
            description='svariati mariii',
            availability=2,
            category='scarpe',
        )
        order1 = Order.create(delivery_address=addr_A, user=user)
        order1.add_item(item1, 2)

        order2 = Order.create(delivery_address=addr_B, user=user)

        user_B = add_admin_user('*****@*****.**', TEST_USER_PSW)
        path = 'orders/{}'.format(order1.uuid)
        resp = open_with_auth(self.app, API_ENDPOINT.format(path), 'DELETE',
                              user_B.email, TEST_USER_PSW, None, None)

        assert resp.status_code == NO_CONTENT
        assert len(Order.select()) == 1
        assert len(OrderItem.select()) == 0
        assert Order.get(uuid=order2.uuid)
Ejemplo n.º 10
0
    def run(self):
        first_customer = Customer(**{
            'username': '******',
            'email': '*****@*****.**',
            'age': 30,
        })

        second_customer = Customer(**{
            'username': '******',
            'email': '*****@*****.**',
        })

        first_order = Order(**{
            'name': 'some order',
            'customer_id': 1,
        })

        second_order = Order(**{
            'name': 'another order',
            'customer_id': 1,
        })

        db.session.add_all(
            [first_customer, second_customer, first_order, second_order])
        db.session.commit()
Ejemplo n.º 11
0
def create_order():
    try:
        shipping = 10
        subtotal = get_cart_total() + shipping
        session['subtotal'] = subtotal
        customer = User.query.filter_by(
            email=session.get(constants.PROFILE_KEY)['email']).first()
        order = Order(customer=customer,
                      order_number=sid.generate(),
                      order_date=str(
                          maya.now().datetime(to_timezone='Asia/Calcutta')),
                      order_total=subtotal)
        order.insert()
        session['order'] = order.format()
        for product in session['cart']:
            ordered_item = Vegetable.query.get(int(product['id']))
            order_details = OrderDetails(ordered_item=ordered_item,
                                         order=order,
                                         price=product['price'],
                                         qty=product['qty'],
                                         total=subtotal)
            order_details.insert()
        session.pop('cart', None)
        return redirect(url_for('order_confirm'))

    except Exception as e:
        print(f'Error ==> {e}')
        flash('Something went wrong')
        return redirect(request.referrer)
Ejemplo n.º 12
0
def prepare_payment(request):
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            product = Clothes.objects.get(id=request.POST['product_id'])
            order = Order(
                buyer_id = request.user.id,
                address = form.cleaned_data['address'],
                phone = form.cleaned_data['phone'],
                email = request.user.email,
                amount = product.price,
                create_date = datetime.now(),
                payment_system = '11'
            )
            order.save()
            order.products.add(product)
            order.save()
            return HttpResponse(prepare_order('11', order.id, order.amount, order.phone, order.email))         
    else:
        raise Http404

    variables = RequestContext(request, {
        'form': form,
        'product': Clothes.objects.get(id=request.POST['product_id']),
    })
    return render_to_response(
        'prepare_order.html',
        variables
    )
Ejemplo n.º 13
0
  def post(self, event_id):
    """save the new order into db

    all items in the event have been confirmed by the contact person.. we need:
    - close the current event
    - create a new order
    """
    event = Event.get_by_id(event_id)
    if not event:
      self.error(404)
      return
    event.status = 'ordered'
    json = self.request.get('json')
    json = simplejson.loads(json)
    purchases = []
    for p in json['purchases']:
      purchase = Purchase.get(p['key'])
      purchase.item = Item.get(p['item'])
      purchase.status = 'collected'
      purchases.append(purchase.put())
    order = Order(contact=users.get_current_user(),
                  vendor=event.vendor,
                  purchases=purchases)
    order.put()
    event.put()
Ejemplo n.º 14
0
def checkout(request, step=0):
    if (request.method == 'POST'):
        if request.user.is_authenticated():
            now = datetime.datetime.utcnow().replace(tzinfo=utc)
            current_user = request.user
            current_order = Order(date_time=now, user=current_user)
            current_order.save()
            for i in range(1, 6):
                print(request.POST)
                try:
                    item_quantity = int(
                        request.POST['item_quantity_' + str(i)])
                except:
                    item_quantity = None
                if not item_quantity is None:
                    item_id = request.POST['item_options_' +
                                           str(i)].split(' ')[1]
                    print(item_id)
                    current_sticker = Sticker.objects.get(pk=int(item_id))
                    print(current_sticker)
                    order_item = OrderItem(
                        order=current_order,
                        sticker=current_sticker,
                        quantity=item_quantity)
                    order_item.save()
    return redirect('/order/' + str(current_order.id) + '/1')
Ejemplo n.º 15
0
    def test_update(self):
        order = Order(name='Dummy Order')
        order.save()

        for i in range(2):
            item = Item(name='Item %i' % i, sku=str(i) * 13, price=D('9.99'), order=order, status=0)
            item.save()

        tag = Tag(name='Test', content_object=order)
        tag.save()

        res = self.client.get('/inlines/1/')

        self.assertEqual(res.status_code, 200)
        order = Order.objects.get(id=1)

        self.assertEquals(2, order.item_set.count())
        self.assertEquals('Item 0', order.item_set.all()[0].name)

        data = {
            'name': u'Dummy Order',
            'item_set-TOTAL_FORMS': u'4',
            'item_set-INITIAL_FORMS': u'2',
            'item_set-MAX_NUM_FORMS': u'',
            'item_set-0-name': 'Bubble Bath',
            'item_set-0-sku': '1234567890123',
            'item_set-0-price': D('9.99'),
            'item_set-0-status': 0,
            'item_set-0-order': 1,
            'item_set-0-id': 1,
            'item_set-1-name': 'Bubble Bath',
            'item_set-1-sku': '1234567890123',
            'item_set-1-price': D('9.99'),
            'item_set-1-status': 0,
            'item_set-1-order': 1,
            'item_set-1-id': 2,
            'item_set-2-name': 'Bubble Bath',
            'item_set-2-sku': '1234567890123',
            'item_set-2-price': D('9.99'),
            'item_set-2-status': 0,
            'item_set-2-order': 1,
            'item_set-3-DELETE': True,
            'tests-tag-content_type-object_id-TOTAL_FORMS': 3,
            'tests-tag-content_type-object_id-INITIAL_FORMS': 1,
            'tests-tag-content_type-object_id-MAX_NUM_FORMS': u'',
            'tests-tag-content_type-object_id-0-name': u'Test',
            'tests-tag-content_type-object_id-0-id': 1,
            'tests-tag-content_type-object_id-0-DELETE': True,
            'tests-tag-content_type-object_id-1-name': u'Test 2',
            'tests-tag-content_type-object_id-2-name': u'Test 3',
        }

        res = self.client.post('/inlines/1/', data, follow=True)
        self.assertEqual(res.status_code, 200)

        order = Order.objects.get(id=1)

        self.assertEquals(3, order.item_set.count())
        self.assertEquals(2, Tag.objects.count())
        self.assertEquals('Bubble Bath', order.item_set.all()[0].name)
Ejemplo n.º 16
0
    def test_get_order__non_existing(self):
        user = add_user(None, TEST_USER_PSW)
        addr = add_address(user=user)
        Order.create(delivery_address=addr, user=user)

        resp = self.app.get('/orders/{}'.format(uuid4()))
        assert resp.status_code == NOT_FOUND
Ejemplo n.º 17
0
def create_order():
    user_authenticated_id = get_jwt_identity()
    helper_id = request.form.get('helper_id')
    description = request.form.get('description')
    long_description = request.form.get('long_description')

    order = Order(description=description,
                  long_description=long_description,
                  helper_id=helper_id,
                  status_id=1)
    order.save()

    documentURL = request.form.get('files')
    if documentURL:
        filename = 'Documents URL'
        document = Document(name=filename,
                            url=documentURL,
                            order=order,
                            user_id=user_authenticated_id)
        document.save()

    DBManager.commitSession()

    orderSerialized = order.serialize()
    if orderSerialized:
        new_order_mail(order.helper, order)
    # Añadir los documentos al objeto
    orderSerialized["documents"] = list(
        map(lambda document: document.serialize(), order.documents))
    return jsonify({"status": "ok", "order": orderSerialized})
Ejemplo n.º 18
0
    def test_repr(self):
        """ Test that string representation is correct """
        date = datetime.now()
        order = Order(customer_id=1, date=date, shipped=True)
        order.save()

        self.assertEqual(order.__repr__(), "<Order>")
Ejemplo n.º 19
0
    def test_get_orders__success(self):
        item = Item.create(
            uuid='429994bf-784e-47cc-a823-e0c394b823e8',
            name='mario',
            price=20.20,
            description='svariati mariii',
            availability=12,
            category='accessori',
        )
        user = add_user(None,
                        TEST_USER_PSW,
                        id='f3f72634-7054-43ef-9119-9e8f54a9531e')
        addr = add_address(user=user,
                           id='85c6cba6-3ddd-4847-9d07-1337ff4e8506')
        Order.create(delivery_address=addr,
                     user=user,
                     uuid='06451e0a-8fa2-40d2-8c51-1af50d369ca6').add_item(
                         item, 2)

        Order.create(delivery_address=addr,
                     user=user,
                     uuid='429994bf-784e-47cc-a823-e0c394b823e8').add_item(
                         item, 5)

        resp = self.app.get('/orders/')

        expected_result = EXPECTED_RESULTS['get_orders__success']

        assert resp.status_code == OK
        assert_valid_response(resp.data, expected_result)
Ejemplo n.º 20
0
def place_order(data):
    # check if the required arguments exist
    try:
        origin = data["origin"]
        destination = data["destination"]
    except KeyError:
        app.logger.error(f"Missing required arguments: {data}/data")
        return generate_error_message("Missing required arguments.")
    # check if the coordinates are valid
    if not is_valid_coordinate(origin) or not is_valid_coordinate(destination):
        app.logger.error(
            f"Invalid coordinates: {origin}/origin, {destination}/destination")
        return generate_error_message("Invalid coordinates.")
    # create an order
    try:
        distance = get_distance(origin, destination)
    except Exception as e:
        return generate_error_message(str(e))
    _order = Order(distance, "UNASSIGNED")
    db_session.add(_order)
    db_session.commit()
    message = f"{_order} is created"
    app.logger.info(message)
    return Response(response=json.dumps(_order.to_dict()),
                    status=200,
                    mimetype='application/json')
Ejemplo n.º 21
0
 def post(self, **kwargs):
     current_user = self.auth_current_user
     products = self.get_cart_content()
     items = []
     
     if self.form.validate():
         user = current_user
         delivery_method = self.form.delivery_method.data
         delivery_area = self.form.delivery_area.data
         delivery_info = self.form.delivery_info.data
         delivery_address = self.form.delivery_address.data
         delivery_city = self.form.delivery_city.data
         delivery_zip = self.form.delivery_zip.data
         comment = self.form.comment.data
         items = str(products)
         order = Order(items=items, user=user.key(), delivery_method=delivery_method, delivery_address=delivery_address, delivery_city=delivery_city, delivery_zip=delivery_zip, comment=comment, delivery_info=delivery_info, delivery_area=delivery_area)
         
         if order.put():
             url = '/mail/notify/order/'
             order_id = str(order.key().id())
             payload = { 'order_id': order_id }
             task = taskqueue.add(url=url, params=payload)
             return redirect('shop/thankyou')
         
         
     return self.get(**kwargs)
Ejemplo n.º 22
0
    def test_create_order__success(self):
        new_order_data = {
            'user':
            self.user1.uuid,
            'items':
            json.dumps([[str(self.item1.uuid), 2], [str(self.item2.uuid), 1]])
        }

        resp = self.app.post('/orders/', data=new_order_data)
        assert resp.status_code == CREATED

        order_from_server = json.loads(resp.data.decode())
        order_from_db = Order.get(
            Order.uuid == order_from_server['uuid']).json()

        assert len(Order.select()) == 1
        assert order_from_db == order_from_server

        order_from_server.pop('uuid')
        assert order_from_server['user'] == str(new_order_data['user'])
        assert len(order_from_server['items']) == 2

        order_items_ids = [str(self.item1.uuid), str(self.item2.uuid)]
        assert order_from_server['items'][0]['uuid'] in order_items_ids
        assert order_from_server['items'][1]['uuid'] in order_items_ids

        order_total = (self.item1.price * 2) + self.item2.price
        assert order_from_server['total_price'] == order_total
Ejemplo n.º 23
0
def checkout(request):
	quantityChanged = False
	userProfile = UserProfile.objects.get(user=request.user)
	if not request.session.get(settings.CART_KEY):
		return redirect('/cart')
	cart = request.session[settings.CART_KEY]
	if not cart:
		request.flash['message'] = 'No items in cart to checkout with.'
		return redirect('/cart', context_instance=RequestContext(request))
	lineItems = line_items_from_cart(request)
	for li in lineItems:
		li.item = Item.objects.get(pk=li.item_id)
		if li.item.onHand < li.quantity:
			quantityChanged = True
			li.quantity = li.item.onHand
			request.flash[li.item.name] = 'Quantity on hand for %s is less than ordered, order changed to the number on hand.' % li.item.name
	if quantityChanged:
		request = update_cart_with_list_line_item(request, lineItems)
		return redirect('/cart', context_instance=RequestContext(request))
	order = Order(userProfile=userProfile)
	order.save()
	for li in lineItems:
		li_save = LineItem(order=order,item=li.item, quantity=li.quantity)
		li_save.save()
		update_item = Item.objects.get(pk=li.item.id)
		update_item.onHand -= li.quantity
		update_item.save()
	request.session[settings.CART_KEY] = None
	return render_to_response('checkout.html', {'order': order}, context_instance=RequestContext(request))
Ejemplo n.º 24
0
def truck_page(truck):
    items = session.query(Item).filter(Item.operator_id == truck)
    if request.method == "POST":
        user = User()
        user.firstName = request.form.get("firstName")
        user.lastName = request.form.get("lastName")
        user.email = request.form.get("email")
        session.add(user)
        session.commit()
        order = Order()
        order.operator_id = truck
        order.user = user
        order.status = "created"
        session.add(order)
        session.commit()
        for item_id in request.form.getlist("item"):
            orderitem = OrderItems()
            orderitem.order_id = order.id
            orderitem.item_id = item_id
            item = items.filter(Item.id == item_id).first()
            session.add(orderitem)
            session.commit()
        return render_template("checkout.html", key=stripe_keys["publishable_key"], order=order, user=user)
    else:
        items = items.all()
        items = filter(lambda x: x.count > 0, items)
        return render_template("truckPage.html", items=items)
Ejemplo n.º 25
0
    def test_update(self):
        order = Order(name="Dummy Order")
        order.save()

        for i in range(2):
            item = Item(name="Item %i" % i, sku=str(i) * 13, price=D("9.99"), order=order, status=0)
            item.save()

        tag = Tag(name="Test", content_object=order)
        tag.save()

        res = self.client.get("/inlines/1/")

        self.assertEqual(res.status_code, 200)
        order = Order.objects.get(id=1)

        self.assertEquals(2, order.item_set.count())
        self.assertEquals("Item 0", order.item_set.all()[0].name)

        data = {
            "name": u"Dummy Order",
            "item_set-TOTAL_FORMS": u"4",
            "item_set-INITIAL_FORMS": u"2",
            "item_set-MAX_NUM_FORMS": u"",
            "item_set-0-name": "Bubble Bath",
            "item_set-0-sku": "1234567890123",
            "item_set-0-price": D("9.99"),
            "item_set-0-status": 0,
            "item_set-0-order": 1,
            "item_set-0-id": 1,
            "item_set-1-name": "Bubble Bath",
            "item_set-1-sku": "1234567890123",
            "item_set-1-price": D("9.99"),
            "item_set-1-status": 0,
            "item_set-1-order": 1,
            "item_set-1-id": 2,
            "item_set-2-name": "Bubble Bath",
            "item_set-2-sku": "1234567890123",
            "item_set-2-price": D("9.99"),
            "item_set-2-status": 0,
            "item_set-2-order": 1,
            "item_set-3-DELETE": True,
            "tests-tag-content_type-object_id-TOTAL_FORMS": 3,
            "tests-tag-content_type-object_id-INITIAL_FORMS": 1,
            "tests-tag-content_type-object_id-MAX_NUM_FORMS": u"",
            "tests-tag-content_type-object_id-0-name": u"Test",
            "tests-tag-content_type-object_id-0-id": 1,
            "tests-tag-content_type-object_id-0-DELETE": True,
            "tests-tag-content_type-object_id-1-name": u"Test 2",
            "tests-tag-content_type-object_id-2-name": u"Test 3",
        }

        res = self.client.post("/inlines/1/", data, follow=True)
        self.assertEqual(res.status_code, 200)

        order = Order.objects.get(id=1)

        self.assertEquals(3, order.item_set.count())
        self.assertEquals(2, Tag.objects.count())
        self.assertEquals("Bubble Bath", order.item_set.all()[0].name)
Ejemplo n.º 26
0
def order_submit(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    market_abbrev = request.POST['market']
    amount = float(request.POST['amount'])
    market_order = ('market_order' in request.POST.keys)
    price = float(request.POST['price'])
    order_type = request.POST['type']

    market = Market.objects.get(abbrev=market_abbrev)
    order = Order()
    order.market = market
    order.amount = amount
    order.type = order_type
    if market_order:
        order.market_order = True
    else:
        order.market_order = False
        order.price = price

    order.save()
    market.market_api.api_execute_order(order)

    return render_to_response('trader/json/success_plain.json',
                              content_type="application/json",
                              context_instance=RequestContext(request))
Ejemplo n.º 27
0
def check_new_order(text, res):
    global order_id
    global order_heap
    tokens = text.split()
    if tokens and (tokens[0].lower() in start_tokens):
        if (len(tokens) == 1):
            res['response']['text'] = 'Хз что готовить'
            return True
        recipe = ' '.join(tokens[1:])

        if (recipes.get(recipe) != None):
            timestamp = datetime.datetime.now().time()
            timestamp = time(timestamp.hour, timestamp.minute,
                             timestamp.second)
            order_id += 1
            item = recipes.get(recipe)
            if item.second == 0:
                order = Order(order_id, recipe, time(0, 7 - item.minute, 0),
                              timestamp, "ожидает")
            else:
                order = Order(order_id, recipe,
                              time(0, 6 - item.minute, 60 - item.second),
                              timestamp, "ожидает")
            heappush(order_heap, order)
            res['response'][
                'text'] = 'Заказ с блюдом {} добавлен в очередь!'.format(
                    order.orderName)
            return True
    return False
Ejemplo n.º 28
0
def match_order(existing_order, order):  
    if (existing_order.sell_amount < order.buy_amount):
        #print("\n current: SELL " + str(order.sell_amount) + " " + order.sell_currency + " / BUY " + str(order.buy_amount) + " " + order.buy_currency)
        remaining_buy_amt = order.buy_amount - existing_order.sell_amount
        remaining_sell_amt = order.sell_amount - existing_order.buy_amount
        derived_implied_fx=remaining_buy_amt/remaining_sell_amt
        #print("\n order FX = " + str(parent_implied_fx)  + " // existing FX = " + str(existing_implied_fx) + " // derived FX = " + str(derived_implied_fx))
        derived_order = Order (
            creator_id=order.id, 
            sender_pk=order.sender_pk,
            receiver_pk=order.receiver_pk, 
            buy_currency=order.buy_currency, 
            sell_currency=order.sell_currency, 
            buy_amount=remaining_buy_amt, 
            sell_amount= remaining_sell_amt)
        derived_order.timestamp = datetime.now()
        derived_order.relationship = (derived_order.id, order.id)
        session.add(derived_order)
        session.commit()
        existing_order.filled = order.timestamp 
        order.filled = order.timestamp
        existing_order.counterparty_id = order.id
        order.counterparty_id = existing_order.id
        existing_implied_fx=existing_order.buy_amount/existing_order.sell_amount
        parent_implied_fx= order.buy_amount/order.sell_amount
        #print("created: SELL " + str(child_order.sell_amount) + " " + child_order.sell_currency + " / BUY " + str(child_order.buy_amount) + " " + child_order.buy_currency)
    return 0
Ejemplo n.º 29
0
def create_order():
    try:
        subtotal = 0
        for product in session['cart_items']:
            subtotal += float(product['price']) * float(product['qty'])
        session['subtotal'] = subtotal
        customer = User.query.get(int(session['user']['id']))
        order = Order(customer=customer,
                      order_number=sid.generate(),
                      order_date=date,
                      order_total=subtotal)
        order.insert()
        for product in session['cart_items']:
            ordered_item = Vegetable.query.get(int(product['id']))
            order_details = OrderDetails(ordered_item=ordered_item,
                                         order=order,
                                         price=product['price'],
                                         qty=product['qty'],
                                         total=subtotal)
            order_details.insert()
        session.pop('cart_items', None)
        return redirect(url_for('order_confirm', isOrderSuccess=True))

    except Exception as e:
        print(f'Error ==> {e}')
        return 'Failed'
Ejemplo n.º 30
0
    def test_update_order__failure_non_existing(self):
        user = add_user('*****@*****.**', TEST_USER_PSW)
        addr = add_address(user=user,
                           id='429994bf-784e-47cc-a823-e0c394b823e8')
        Order.create(delivery_address=addr, user=user)

        order_uuid = str(uuid4())

        order = {
            'relationships': {
                'items': [
                    {
                        'id': '429994bf-784e-47cc-a823-e0c394b823e8',
                        'type': 'item',
                        'quantity': 5
                    },
                ],
            }
        }
        data = format_jsonapi_request('order', order)

        path = 'orders/{}'.format(order_uuid)
        resp = open_with_auth(self.app, API_ENDPOINT.format(path), 'PATCH',
                              '*****@*****.**', TEST_USER_PSW,
                              'application/json', json.dumps(data))

        assert resp.status_code == NOT_FOUND
Ejemplo n.º 31
0
def api_create_order(request, *, customer, phone, province, city=' ', area=' ',address, payment, notes, price):

    # check_admin(request)

    if not price or not price.strip() or rubbish_filter(price):
        raise APIValueError('产品', '请选择产品')

    if not customer or not customer.strip() or rubbish_filter(customer):
        raise APIValueError("姓名","请填写姓名")

    if not phone or not phone.strip() or not phone_filter(phone):
        raise APIValueError("电话","请填写正确的手机号码")

    if not province or not city  or not address or not province.strip() or not city.strip()  or not address.strip() or rubbish_filter(province) or rubbish_filter(city) or area_filter(area) or rubbish_filter(address):
        raise APIValueError('地址', '请填写完整地址')
    address = province+city+area.strip()+address
    if not payment or not payment.strip() or rubbish_filter(payment):
        raise APIValueError("付款方式","请选择付款方式")
    if payment == '支付宝付款':
        raise APIValueError("付款方式","请选择货到付款,支付宝付款通道尚未开通")
    if rubbish_filter(notes):
        raise APIValueError("订单备注","请预留有效的备注信息")
    order = Order(customer=customer.strip(), price=price.strip(),phone=phone.strip(), address=address.strip(), payment=payment.strip(), notes=notes.strip())
    yield from order.save()
    return order
def order(request):
    ID = request.GET["sNumber"]
    sNumber = ID
    rNumber = request.GET["rNumber"]
    orderlist = Order.objects.filter(Sender=sNumber, Receiver=rNumber)
    if "ad" in request.POST:
        post = request.POST
        neworder = Order(
            Sender=sNumber,
            Receiver=rNumber,
            Time=post["time"],
            Event=post["event"],
            State="0",
        )
        neworder.save()
        HttpResponseRedirect("/appoinment/?sNumber=" + sNumber + "&rNumber=" +
                             rNumber)
    if "but" in request.POST:
        post = request.POST
        d3 = post["but"]
        n = Order.objects.get(id=d3)
        n.delete()
        HttpResponseRedirect("/appoinment/?sNumber=" + sNumber + "&rNumber=" +
                             rNumber)
    return render_to_response(
        "order.html",
        RequestContext(
            request, {
                "sNumber": sNumber,
                "rNumber": rNumber,
                "orderlist": orderlist,
                "ID": ID,
            }))
Ejemplo n.º 33
0
def create_order():
    user_authenticated_id = get_jwt_identity()
    helper_id = request.form.get('helper_id')
    description = request.form.get('description')

    order = Order(description=description, helper_id=helper_id, status_id=1)
    order.save()

    if os.environ.get('AWS_S3_BUCKET_NAME'):
        files = request.files
        for key in files:
            file = files[key]
            if file:
                url_document = upload_file_to_s3(
                    file, os.environ.get('AWS_S3_BUCKET_NAME'))
                if url_document:
                    document = Document(name=file.filename,
                                        url=url_document,
                                        order=order,
                                        user_id=user_authenticated_id)
                    document.save()
    else:
        print("Faltan las credenciales de AWS")

    DBManager.commitSession()

    orderSerialized = order.serialize()

    if orderSerialized:
        new_order_mail(order.helper, order)
    #Añadir los documentos al objeto
    orderSerialized["documents"] = list(
        map(lambda document: document.serialize(), order.documents))
    return jsonify({"status": "ok", "order": orderSerialized})
Ejemplo n.º 34
0
def add_order_item():

    data = request.get_json()
    products = data['products']
    total_price = 0
    new_order_public_id = str(uuid.uuid4())
    new_order = Order(
        public_id=new_order_public_id,
        customer_id=data['customer_id'],
        store_id=data['store_id'],
        date=datetime.datetime.utcnow(),
        payment_method=data['payment_method'],
        payment_confirmation_id=data['payment_confirmation_id']
    )
    print(new_order)
    db.session.add(new_order)
    db.session.commit()

    for product in products:
        new_product = OrderItem(
            public_id=str(uuid.uuid4()),
            product_id=product['product_id'],
            quantity=product['quantity'],
            price=product['price'],
            order_obj=new_order
        )
        total_price = total_price + (product['quantity']*product['price'])
        db.session.add(new_product)
        db.session.commit()

        new_order = Order.query.filter_by(public_id=new_order_public_id).first()
        new_order.amount = total_price
        db.session.commit()

    return jsonify({'message': 'order created'})
Ejemplo n.º 35
0
    def test_modify_order__success(self):
        order1 = self.create_order(self.user1)
        order2 = self.create_order(self.user1)

        start_availability = self.item2.availability

        updates = {'items': json.dumps([[str(self.item2.uuid), 2]])}

        resp = self.open_with_auth('/orders/{}'.format(order1.uuid),
                                   'put',
                                   self.user1.email,
                                   'p4ssw0rd',
                                   data=updates)
        assert resp.status_code == OK

        order1_upd = Order.get(Order.uuid == order1.uuid).json()
        total_price = self.item2.price * 2
        assert order1_upd['total_price'] == total_price

        order2_db = Order.get(Order.uuid == order2.uuid).json()
        assert order2_db == order2.json()

        order1_items = OrderItem.select().where(OrderItem.order == order1)
        assert len(order1_items) == 1
        assert str(order1_items[0].item.uuid) == str(self.item2.uuid)

        temp_item = Item.get(Item.uuid == self.item2.uuid)
        assert temp_item.availability == (start_availability - 2)
Ejemplo n.º 36
0
    def setup_method(self):
        super(TestUserSchema, self).setup_method()
        # Setup the same mock database data for every test
        self.user1 = add_user(
            **USER_TEST_DICT,
            id='cfe57aa6-76c6-433d-93fe-443363978904',
        )
        self.addr1 = add_address(
            self.user1,
            id='e8c4607a-a271-423f-981b-1aaefdac87e8',
        )

        self.order1 = Order.create(delivery_address=self.addr1, user=self.user1,
                                   uuid='4cefa833-2f45-4662-b2fc-083ddad4f7a3',
                                   created_at=datetime(2017, 5, 1, 3, 5, 57),
                                   )
        self.order2 = Order.create(delivery_address=self.addr1, user=self.user1,
                                   uuid='8d449938-5745-4489-ab32-89dc8178e347',
                                   created_at=datetime(2017, 5, 1, 11, 16, 25),
                                   )

        # User 2 has no relationships, just a plain user
        self.user2 = add_user(
            first_name="Monty",
            last_name="Python",
            email="*****@*****.**",
            password="******",
            id='94495ece-559b-4b3a-87ed-799259c921bf',
        )
Ejemplo n.º 37
0
 def post(self):
     try:
         id = int(self.request.get("id"))
         plat = float(self.request.get("plat"))
         plon = float(self.request.get("plon"))
         dlat = float(self.request.get("dlat"))
         dlon = float(self.request.get("dlon"))
         #check if order already exists
         pastOrder = db.GqlQuery("SELECT * FROM Order WHERE orderId = :1",
                                 id).get()
         if pastOrder is None:
             order = Order(orderId=id,
                           pickup_lat=plat,
                           pickup_lon=plon,
                           dropoff_lat=dlat,
                           dropoff_lon=dlon)
             order.put()
             assign.assignDelivery()
             self.redirect('/order/needPickup')
         else:
             self.response.set_status(333, "Order already exists")
             self.response.headers['Content-Type'] = 'text/html'
             template = jinja_env.get_template('newOrder.html')
             d = {'error': 'Order {} already exists'.format(id)}
             self.response.out.write(template.render())
     except ValueError:
         self.response.set_status(344, 'Invalid values')
         self.response.headers['Content-Type'] = 'text/html'
         template = jinja_env.get_template('newOrder.html')
         d = {'error': 'Invalid input parameters'}
         self.response.out.write(template.render(d))
Ejemplo n.º 38
0
def sec_tops(secs):
    lt = {}
    bb = {}
    ba = {}
    for sec in secs:
        # Last traded price
        t = Trade.query(Trade.security == sec).order(-Trade.timestamp)
        t = list(t)
        if len(t) > 0:
            lt[sec.key.id()] = t[0].price
        else:
            lt[sec.key.id()] = 0
        
        # Best bid
        t = Order.query(Order.security == sec, Order.buysell == 'Buy', Order.active == True).order(-Order.price)
        t = list(t)
        if len(t) > 0:
            bb[sec.key.id()] = t[0].price
        else:
            bb[sec.key.id()] = 0
        
        # Best ask
        t = Order.query(Order.security == sec, Order.buysell == 'Sell', Order.active == True).order(Order.price)
        t = list(t)
        if len(t) > 0:
            ba[sec.key.id()] = t[0].price
        else:
            ba[sec.key.id()] = 0
    
    tops = {'lt':lt, 'bb':bb, 'ba':ba}
    return tops
Ejemplo n.º 39
0
    def post_order(payload):
        try:
            data = request.get_json()

            resto_id = data['restaurant_id']
            name = data['name']
            calories = data['calories']
            total_fat = data['total_fat']
            cholesterol = data['cholesterol']
            sodium = data['sodium']
            total_carbs = data['total_carbs']
            protein = data['protein']

            new_order = Order(restaurant_id=resto_id,
                              name=name,
                              calories=calories,
                              total_fat=total_fat,
                              cholesterol=cholesterol,
                              sodium=sodium,
                              total_carbs=total_carbs,
                              protein=protein)
            new_order.insert()
        except Exception:
            abort(400)

        return jsonify({'success': True, 'orders': [new_order.format()]})
Ejemplo n.º 40
0
def user_page(request):
	''' This will return the page with the generated email and manage user '''
	
	email = request.REQUEST['email']

	m = hashlib.md5()

	
	# create a new order and put the requester's email in it
	new_order = Order(user_email = email)
	generated_id = str(new_order.id)

	m.update(generated_id)

	generated_email = m.hexdigest() + "@jimini.co"
	jimini_order_link = 'jimini.co/orders/' + m.hexdigest()

	# update database entry with the generated email and order link
	new_order.generated_email = generated_email
	new_order.jimini_order_link = jimini_order_link
	new_order.save()   ## TODO WEBSITE NOT TALKING

	print generated_email
	print jimini_order_link
	
	return render_to_response('user_page.html', {'generated_email' : generated_email})
Ejemplo n.º 41
0
    def test_delete_order__success(self):
        order1 = self.create_order(self.user1)
        order2 = self.create_order(self.user1)

        items_quantity = {
            oi.item.uuid: (oi.item.availability, oi.quantity)
            for oi in order1.order_items
        }

        resp = self.open_with_auth('/orders/{}'.format(str(order1.uuid)),
                                   'delete',
                                   self.user1.email,
                                   'p4ssw0rd',
                                   data='')
        assert resp.status_code == NO_CONTENT

        orders = Order.select()
        assert len(orders) == 1
        assert Order.get(Order.uuid == order2.uuid)

        order_items = OrderItem.select().where(OrderItem.order == order1)
        assert len(order_items) == 0

        for item_uuid, (availability, quantity) in items_quantity.items():
            item = Item.get(Item.uuid == item_uuid)
            assert item.availability == availability + quantity
Ejemplo n.º 42
0
def inititalize_redis():  # pragma: no cover
    global redis
    redis = None
    # Get the crdentials from the Bluemix environment
    if 'VCAP_SERVICES' in os.environ:
        app.logger.info("Using VCAP_SERVICES...")
        VCAP_SERVICES = os.environ['VCAP_SERVICES']
        services = json.loads(VCAP_SERVICES)
        creds = services['rediscloud'][0]['credentials']
        app.logger.info("Conecting to Redis on host %s port %s" %
                        (creds['hostname'], creds['port']))
        redis = connect_to_redis(creds['hostname'], creds['port'],
                                 creds['password'])
    else:
        app.logger.info(
            "VCAP_SERVICES not found, checking localhost for Redis")
        redis = connect_to_redis('127.0.0.1', 6379, None)
        if not redis:
            app.logger.info("No Redis on localhost, using: redis")
            redis = connect_to_redis('redis', 6379, None)
    if not redis:
        # if you end up here, redis instance is down.
        app.logger.error(
            '*** FATAL ERROR: Could not connect to the Redis Service')
    # Have the Order model use Redis
    Order.use_db(redis)
Ejemplo n.º 43
0
 def post(self):
     try:
         id = int(self.request.get("id"))
         plat = float(self.request.get("plat"))
         plon = float(self.request.get("plon"))
         dlat = float(self.request.get("dlat"))
         dlon = float(self.request.get("dlon"))
         #check if order already exists
         pastOrder = db.GqlQuery("SELECT * FROM Order WHERE orderId = :1",id).get()
         if pastOrder is None:
             order = Order(orderId =id,pickup_lat=plat,pickup_lon=plon,dropoff_lat=dlat,dropoff_lon=dlon)
             order.put()
             assign.assignDelivery()
             self.redirect('/order/needPickup')
         else:
             self.response.set_status(333,"Order already exists")
             self.response.headers['Content-Type'] = 'text/html'
             template = jinja_env.get_template('newOrder.html')
             d = {'error':'Order {} already exists'.format(id)}
             self.response.out.write(template.render())
     except ValueError:
         self.response.set_status(344,'Invalid values')
         self.response.headers['Content-Type'] = 'text/html'
         template = jinja_env.get_template('newOrder.html')
         d = {'error':'Invalid input parameters'}
         self.response.out.write(template.render(d))
Ejemplo n.º 44
0
    def get_queryset(self):
        orders = Order.objects.filter(stakeholder=self.request.user)
        if orders.count() == 0:
            order = Order()
            order.stakeholder = self.request.user
            order.save()

        return Order.objects.filter(stakeholder=self.request.user)
Ejemplo n.º 45
0
def save_order_to_db(request, instance):
	
 	cart_items = get_cart_items(request)
 	for cart_item in cart_items:

 		order = Order(product = cart_item['product'], quantity = cart_item['quantity'], order_details_id = instance)
 		order.save()
 	request.session.clear()
Ejemplo n.º 46
0
 def testPost3(self):
     #courier found, but order not found
     order = Order(orderId=1,pickup_lat=1.0,pickup_lon=1.0,dropoff_lat=2.0,dropoff_lon=2.0)
     order.put()
     courier = Courier(courierId=7,lat=2.0,lon=3.0)
     courier.put()
     response = self.testapp.post('/courier/7/complete')
     self.assertEqual(333,response.status_int)
Ejemplo n.º 47
0
 def testOrder(self):
     order = Order(orderId=1,pickup_lat=1.0,pickup_lon=1.0,dropoff_lat=2.0,dropoff_lon=2.0)
     order.put()
     order = db.GqlQuery("SELECT * FROM Order WHERE orderId = :1 AND state = :2",1,'enRoute').get()
     self.assertEqual(None, order)
     
     order = db.GqlQuery("SELECT * FROM Order WHERE orderId = :1 AND state = :2",1,'needPickup').get()
     self.assertNotEqual(None, order)
Ejemplo n.º 48
0
def api_orders(*, page='1'):
    page_index = get_page_index(page)
    num = yield from Order.findNumber('count(order_id)')
    p = Page(num, page_index)
    if num == 0:
        return dict(page=p, orders=())
    orders = yield from Order.findAll(orderBy='created_at desc', limit=(p.offset, p.limit))
    return dict(page=p, orders=orders)
Ejemplo n.º 49
0
def add(request):
    data = request.POST.getlist('data')
    total = float(data[-1].encode('utf-8'))
    price = float(data[-2].encode('utf-8'))
    total_price = "%.2f" %(total*price)
    o1 = Order(datetime=data[0],office=data[1],subject=data[2],\
	school=data[3],grade=data[4],classs=data[5],total=total,price=price,total_price=total_price)
    o1.save()
    return HttpResponseRedirect('/information/order/')
Ejemplo n.º 50
0
def add_order():
    
    deliveryid = request.json['delivery_id']
    #userID = session['userID']
    userID = session['id']
    
    orderID = Order.create_order(deliveryid, userID)
    
    return json.dumps(Order.get_order_by_id(orderID).serializable())
Ejemplo n.º 51
0
def construct_book(sec): 
    """Create buy and sell top depths"""
    # Get sorted
    b1 = Order.query(Order.security == sec, Order.buysell == 'Buy', Order.active == True, ancestor=sec.key).order(-Order.price)
    s1 = Order.query(Order.security == sec, Order.buysell == 'Sell', Order.active == True, ancestor=sec.key).order(Order.price)
    
    # BUYS
    # Combine price volume
    b2 = {}
    for order in b1:
        b2[order.price] = b2.get(order.price, 0) + order.volume
    b2 = OrderedDict(sorted(b2.items(), reverse = True))
    
    # Get top of buy book
    n = list(islice(b2.items(), 0, 1))
    b3 = {}
    if len(n) != 0:
        k = n[0][0]
        b3[k] = n[0][1]
    else:
        k = 0
        b3[k] = 0
    
    # Keep top BOOK_TOP_LEVELS number of prices
    for i in range(BOOK_TOP_LEVELS):
        if k - i - 1 <= 0:
            break
        b3[k-i-1] = b2.get(k-i-1, 0)
    b3 = OrderedDict(sorted(b3.items(), reverse = True))
    
    # SELLS
    # Combine price volume
    s2 = {}
    for order in s1:
        s2[order.price] = s2.get(order.price, 0) + order.volume
    s2 = OrderedDict(sorted(s2.items()))
    
    # Get top of sell book
    n = list(islice(s2.items(), 0, 1))
    s3 = {}
    if len(n) != 0:
        k = n[0][0]
        s3[k] = n[0][1]
    else:
        k = list(islice(b3.items(), 0, 1))[0][0]+1
        s3[k] = 0
    
    # Keep top BOOK_TOP_LEVELS number of prices
    for i in range(BOOK_TOP_LEVELS):
        s3[k+i+1] = s2.get(k+i+1, 0)
    s3 = OrderedDict(sorted(s3.items(), reverse = True))
    
    # Combine books
    book = {'buys':b3, 'sells':s3}
    
    return book
Ejemplo n.º 52
0
 def testPost2(self):
     #courier not found
     order = Order(orderId=1,pickup_lat=1.0,pickup_lon=1.0,dropoff_lat=2.0,dropoff_lon=2.0)
     order.put()
     courier = Courier(courierId=1,lat=2.0,lon=3.0,orderId=1)
     courier.put()
     self.assertEqual(1,len(Courier.all().fetch(20)))
     # if the courier is not found, nothing should be changed
     response = self.testapp.post('/courier/2/complete')
     self.assertEqual(333,response.status_int)
Ejemplo n.º 53
0
    def test_post(self):
        order = Order(name='Dummy Order')
        order.save()
        data = {}
        data.update(self.management_data)

        res = self.client.post('/inlineformset/1/', data, follow=True)
        self.assertEqual(res.status_code, 200)
        self.assertTrue('formset' in res.context)
        self.assertFalse('form' in res.context)
Ejemplo n.º 54
0
    def test_context(self):
        order = Order(name='Dummy Order')
        order.save()

        for i in range(10):
            item = Item(name='Item %i' % i, sku=str(i) * 13, price=D('9.99'), order=order, status=0)
            item.save()

        res = self.client.get('/modelformset/simple/')
        self.assertTrue('object_list' in res.context)
        self.assertEquals(len(res.context['object_list']), 10)
Ejemplo n.º 55
0
 def testAvailableCourierId(self):
     order = Order(orderId=1,pickup_lat=1.0,pickup_lon=1.0,dropoff_lat=2.0,dropoff_lon=2.0,state='enRoute',courierId= 3)
     order.put()
     courier = Courier(courierId=1,lat=2.0,lon=3.0,online=True)
     courier.put()
     
     courier = Courier(courierId=3,lat=4.0,lon=3.0,online=True)
     courier.put()
     courier = Courier(courierId=8,lat=4.0,lon=3.0,online=True)
     courier.put()
     self.assertEqual([1,8],assign.availableCourierId())
Ejemplo n.º 56
0
    def test_context(self):
        order = Order(name="Dummy Order")
        order.save()

        for i in range(10):
            item = Item(name="Item %i" % i, sku=str(i) * 13, price=D("9.99"), order=order, status=0)
            item.save()

        res = self.client.get("/modelformset/simple/")
        self.assertTrue("object_list" in res.context)
        self.assertEquals(len(res.context["object_list"]), 10)
Ejemplo n.º 57
0
def add_order(request):
  form = FormOrder(request.POST, request.FILES)
  
  if form.is_valid():
    values = form.cleaned_data
    item = Order(quantity=values['quantity'])
    item.save()
    return render_to_response("save.html", {})
    
  else:
    form = FormOrder()
    return render_to_response("add_order.html", {'form' : form}, context_instance=RequestContext(request))
Ejemplo n.º 58
0
def test_fill_order():
    order = Order("item #1", 50)

    mocker = Mocker()
    inventory = mocker.mock()
    inventory.remove("item #1", 50)

    mocker.replay()
    order.fill(inventory)

    mocker.verify()
    assert order.filled
Ejemplo n.º 59
0
    def test_create(self):
        order = Order(name='Dummy Order')
        order.save()

        for i in range(10):
            item = Item(name='Item %i' % i,sku=str(i)*13,price=D('9.99'),order=order, status=0)
            item.save()

        res = self.client.get('/inlineformset/1/')
        self.assertEqual(res.status_code, 200)
        self.assertTrue('formset' in res.context)
        self.assertFalse('form' in res.context)